@cortexkit/opencode-antigravity-auth 3.1.8 → 3.1.10

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 (118) hide show
  1. package/README.md +4 -0
  2. package/dist/cli.js +256 -179
  3. package/dist/cli.js.map +4 -4
  4. package/dist/cli.meta.json +88 -44
  5. package/dist/index.js +5466 -4823
  6. package/dist/index.js.map +4 -4
  7. package/dist/index.meta.json +333 -269
  8. package/dist/server.js +1321 -608
  9. package/dist/server.js.map +4 -4
  10. package/dist/server.meta.json +1 -1
  11. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +16 -5
  12. package/dist/src/common-auth-embedded/claustrum/custody.js +31 -14
  13. package/dist/src/common-auth-embedded/fs/private-files.js +8 -3
  14. package/dist/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  15. package/dist/src/common-auth-embedded/opencode2/index.js +1 -1
  16. package/dist/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  17. package/dist/src/common-auth-embedded/opencode2/install.js +14 -4
  18. package/dist/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  19. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +71 -16
  20. package/dist/src/common-auth-embedded/routing-accessor/index.js +123 -17
  21. package/dist/src/common-auth-embedded/setup/process-fence.js +20 -3
  22. package/dist/src/common-auth-embedded/source-output.json +44 -44
  23. package/dist/src/common-auth-embedded/store/mutate.js +34 -13
  24. package/dist/src/ga/server/index.d.ts +1 -1
  25. package/dist/src/ga/server/index.d.ts.map +1 -1
  26. package/dist/src/ga/server/index.js +58 -19
  27. package/dist/src/ga/server/index.js.map +1 -1
  28. package/dist/src/plugin/__fixtures__/release-model-ids.d.ts.map +1 -1
  29. package/dist/src/plugin/__fixtures__/release-model-ids.js +1 -0
  30. package/dist/src/plugin/__fixtures__/release-model-ids.js.map +1 -1
  31. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  32. package/dist/src/plugin/auth-loader.d.ts.map +1 -1
  33. package/dist/src/plugin/auth-loader.js +102 -80
  34. package/dist/src/plugin/auth-loader.js.map +1 -1
  35. package/dist/src/plugin/config/models.d.ts +1 -1
  36. package/dist/src/plugin/config/models.d.ts.map +1 -1
  37. package/dist/src/plugin/config/models.js +10 -5
  38. package/dist/src/plugin/config/models.js.map +1 -1
  39. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  40. package/dist/src/plugin/fetch-interceptor.js +27 -13
  41. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  42. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  43. package/dist/src/plugin/ga-location-services.js +21 -11
  44. package/dist/src/plugin/ga-location-services.js.map +1 -1
  45. package/dist/src/plugin/index.d.ts.map +1 -1
  46. package/dist/src/plugin/index.js +13 -5
  47. package/dist/src/plugin/index.js.map +1 -1
  48. package/dist/src/plugin/request.d.ts.map +1 -1
  49. package/dist/src/plugin/request.js +8 -8
  50. package/dist/src/plugin/request.js.map +1 -1
  51. package/dist/src/plugin/shared/opencode-retry-hints.d.ts +2 -0
  52. package/dist/src/plugin/shared/opencode-retry-hints.d.ts.map +1 -0
  53. package/dist/src/plugin/shared/opencode-retry-hints.js +22 -0
  54. package/dist/src/plugin/shared/opencode-retry-hints.js.map +1 -0
  55. package/dist/src/plugin/shared/request-services.d.ts +2 -0
  56. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  57. package/dist/src/plugin/shared/request-services.js +410 -112
  58. package/dist/src/plugin/shared/request-services.js.map +1 -1
  59. package/dist/src/plugin/shared/vault-routing-purpose.d.ts +6 -2
  60. package/dist/src/plugin/shared/vault-routing-purpose.d.ts.map +1 -1
  61. package/dist/src/plugin/shared/vault-routing-purpose.js +13 -7
  62. package/dist/src/plugin/shared/vault-routing-purpose.js.map +1 -1
  63. package/dist/src/plugin/shared/vault-routing.d.ts +8 -1
  64. package/dist/src/plugin/shared/vault-routing.d.ts.map +1 -1
  65. package/dist/src/plugin/shared/vault-routing.js +12 -4
  66. package/dist/src/plugin/shared/vault-routing.js.map +1 -1
  67. package/dist/src/plugin/storage.d.ts +1 -0
  68. package/dist/src/plugin/storage.d.ts.map +1 -1
  69. package/dist/src/plugin/storage.js +3 -3
  70. package/dist/src/plugin/storage.js.map +1 -1
  71. package/dist/src/plugin/vault-custody.d.ts +6 -13
  72. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  73. package/dist/src/plugin/vault-custody.js +19 -16
  74. package/dist/src/plugin/vault-custody.js.map +1 -1
  75. package/dist/tui-build-map.json +5 -5
  76. package/dist/tui-ga-build-map.json +1 -1
  77. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +16 -5
  78. package/dist/types/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  79. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  80. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  81. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +71 -16
  82. package/dist/types/src/ga/server/index.d.ts +1 -1
  83. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  84. package/dist/types/src/plugin/auth-loader.d.ts.map +1 -1
  85. package/dist/types/src/plugin/config/models.d.ts +1 -1
  86. package/dist/types/src/plugin/config/models.d.ts.map +1 -1
  87. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  88. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  89. package/dist/types/src/plugin/index.d.ts.map +1 -1
  90. package/dist/types/src/plugin/request.d.ts.map +1 -1
  91. package/dist/types/src/plugin/shared/opencode-retry-hints.d.ts +2 -0
  92. package/dist/types/src/plugin/shared/opencode-retry-hints.d.ts.map +1 -0
  93. package/dist/types/src/plugin/shared/request-services.d.ts +2 -0
  94. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  95. package/dist/types/src/plugin/shared/vault-routing-purpose.d.ts +6 -2
  96. package/dist/types/src/plugin/shared/vault-routing-purpose.d.ts.map +1 -1
  97. package/dist/types/src/plugin/shared/vault-routing.d.ts +8 -1
  98. package/dist/types/src/plugin/shared/vault-routing.d.ts.map +1 -1
  99. package/dist/types/src/plugin/storage.d.ts +1 -0
  100. package/dist/types/src/plugin/storage.d.ts.map +1 -1
  101. package/dist/types/src/plugin/vault-custody.d.ts +6 -13
  102. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  103. package/package.json +2 -2
  104. package/src/common-auth-embedded/claustrum/custody.d.ts +16 -5
  105. package/src/common-auth-embedded/claustrum/custody.js +31 -14
  106. package/src/common-auth-embedded/fs/private-files.js +8 -3
  107. package/src/common-auth-embedded/opencode2/index.d.ts +1 -1
  108. package/src/common-auth-embedded/opencode2/index.js +1 -1
  109. package/src/common-auth-embedded/opencode2/install.d.ts +6 -1
  110. package/src/common-auth-embedded/opencode2/install.js +14 -4
  111. package/src/common-auth-embedded/opencode2/types.d.ts +10 -7
  112. package/src/common-auth-embedded/routing-accessor/index.d.ts +71 -16
  113. package/src/common-auth-embedded/routing-accessor/index.js +123 -17
  114. package/src/common-auth-embedded/setup/process-fence.js +20 -3
  115. package/src/common-auth-embedded/source-output.json +44 -44
  116. package/src/common-auth-embedded/store/mutate.js +34 -13
  117. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +8 -3
  118. 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";
@@ -4126,6 +4129,8 @@ function getGemini38FlashAntigravityModel(tier) {
4126
4129
  }
4127
4130
  function getQuotaGroupForModel(modelId, hasArgonPool = false) {
4128
4131
  const normalized = modelId.toLowerCase();
4132
+ if (isGeminiNeonModel(normalized))
4133
+ return "gemini";
4129
4134
  if (isGeminiHydrogenModel(normalized))
4130
4135
  return "gemini";
4131
4136
  if (isGeminiCarbonModel(normalized))
@@ -4159,6 +4164,23 @@ function getGeminiHydrogenAntigravityModel(tier) {
4159
4164
  }
4160
4165
  }, tier);
4161
4166
  }
4167
+ function isGeminiNeonModel(model) {
4168
+ return /^(?:antigravity-)?gemini-4-neon(?:-(?:low|medium|high|xhigh))?$/i.test(model);
4169
+ }
4170
+ function supportsGeminiXHigh(model) {
4171
+ return isGeminiHydrogenModel(model) || isGeminiNeonModel(model);
4172
+ }
4173
+ function getGeminiNeonAntigravityModel(tier) {
4174
+ return getTieredAntigravityModel({
4175
+ defaultModel: "gemini-4-neon-high",
4176
+ byTier: {
4177
+ low: "gemini-4-neon-low",
4178
+ medium: "gemini-4-neon-medium",
4179
+ high: "gemini-4-neon-high",
4180
+ xhigh: "gemini-4-neon-xhigh"
4181
+ }
4182
+ }, tier);
4183
+ }
4162
4184
  function getGeminiCarbonAntigravityModel(tier) {
4163
4185
  return getTieredAntigravityModel({
4164
4186
  defaultModel: "gemini-4-carbon-medium",
@@ -4191,6 +4213,35 @@ var init_model_registry = __esm({
4191
4213
  DEFAULT_COST = { input: 0, output: 0 };
4192
4214
  DEFAULT_OPTIONS = {};
4193
4215
  AGY_NATIVE_MODEL_DEFINITIONS = {
4216
+ // Native CLI 1.5.9 catalog: all four Neon routes share the same limits.
4217
+ "gemini-4-neon-low": {
4218
+ displayName: "Gemini 4 Neon (Low)",
4219
+ maxTokens: 1048576,
4220
+ maxOutputTokens: 262144,
4221
+ model: "MODEL_PLACEHOLDER_M534",
4222
+ supportsThinking: true
4223
+ },
4224
+ "gemini-4-neon-medium": {
4225
+ displayName: "Gemini 4 Neon (Medium)",
4226
+ maxTokens: 1048576,
4227
+ maxOutputTokens: 262144,
4228
+ model: "MODEL_PLACEHOLDER_M533",
4229
+ supportsThinking: true
4230
+ },
4231
+ "gemini-4-neon-high": {
4232
+ displayName: "Gemini 4 Neon (High)",
4233
+ maxTokens: 1048576,
4234
+ maxOutputTokens: 262144,
4235
+ model: "MODEL_PLACEHOLDER_M532",
4236
+ supportsThinking: true
4237
+ },
4238
+ "gemini-4-neon-xhigh": {
4239
+ displayName: "Gemini 4 Neon (XHigh)",
4240
+ maxTokens: 1048576,
4241
+ maxOutputTokens: 262144,
4242
+ model: "MODEL_PLACEHOLDER_M535",
4243
+ supportsThinking: true
4244
+ },
4194
4245
  // Context: Google's "Introducing Gemini 4 Hydrogen" announcement (12 Nov 2026).
4195
4246
  // Output caps and route enums: native CLI 1.5.5 capture (13 Nov 2026).
4196
4247
  "gemini-4-hydrogen-low": {
@@ -4375,6 +4426,18 @@ var init_model_registry = __esm({
4375
4426
  };
4376
4427
  RETIRED_AGY_MODEL_MESSAGE = "This Antigravity model is no longer offered. Use Gemini 3.8 Flash, or Claude Sonnet 5.5 or Opus 5.5.";
4377
4428
  ALL_MODEL_DEFINITIONS = {
4429
+ "antigravity-gemini-4-neon": defineModel("antigravity-gemini-4-neon", {
4430
+ name: "Gemini 4 Neon (Antigravity)",
4431
+ reasoning: true,
4432
+ limit: { context: 1048576, output: 262144 },
4433
+ modalities: DEFAULT_MODALITIES,
4434
+ variants: {
4435
+ low: { thinkingLevel: "low" },
4436
+ medium: { thinkingLevel: "medium" },
4437
+ high: { thinkingLevel: "high" },
4438
+ xhigh: { thinkingLevel: "xhigh" }
4439
+ }
4440
+ }),
4378
4441
  "antigravity-gemini-4-hydrogen": defineModel("antigravity-gemini-4-hydrogen", {
4379
4442
  name: "Gemini 4 Hydrogen (Antigravity)",
4380
4443
  reasoning: true,
@@ -4556,6 +4619,7 @@ var init_model_registry = __esm({
4556
4619
  "antigravity-gemini-4-argon",
4557
4620
  "antigravity-gemini-4-carbon",
4558
4621
  "antigravity-gemini-4-hydrogen",
4622
+ "antigravity-gemini-4-neon",
4559
4623
  "antigravity-gemini-3.8-flash",
4560
4624
  "antigravity-gemini-3.1-flash-image",
4561
4625
  "antigravity-claude-sonnet-5-5",
@@ -4569,8 +4633,8 @@ var init_model_registry = __esm({
4569
4633
  // ../core/dist/rotation.js
4570
4634
  function unconfirmedRateLimitDelayMs(retryAfter, now2 = Date.now()) {
4571
4635
  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;
4636
+ const delay5 = value ? /^\d+(?:\.\d+)?$/.test(value) ? Number(value) * 1e3 : Date.parse(value) - now2 : Number.NaN;
4637
+ 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
4638
  }
4575
4639
  function parseRateLimitReason(reason, message, status) {
4576
4640
  if (status === 529 || status === 503)
@@ -5358,6 +5422,7 @@ var init_account_selector = __esm({
5358
5422
  const state2 = {
5359
5423
  parentId: identity4.parentId ?? null,
5360
5424
  currentAccountIndexByFamily: { claude: -1, gemini: -1 },
5425
+ routedByFamily: { claude: false, gemini: false },
5361
5426
  cursorByFamily: { ...this.cursorByFamily },
5362
5427
  offsetAppliedByFamily: { claude: false, gemini: false },
5363
5428
  usedAccounts: /* @__PURE__ */ new Set(),
@@ -5391,13 +5456,14 @@ var init_account_selector = __esm({
5391
5456
  getActiveIndex(family, identity4) {
5392
5457
  return identity4 ? this.getRequestSessionState(identity4).currentAccountIndexByFamily[family] : this.currentAccountIndexByFamily[family];
5393
5458
  }
5394
- setActiveIndex(family, index, identity4) {
5459
+ setActiveIndex(family, index, identity4, routed = false) {
5395
5460
  if (!identity4) {
5396
5461
  this.setGlobalActiveIndex(family, index);
5397
5462
  return;
5398
5463
  }
5399
5464
  const state2 = this.getRequestSessionState(identity4);
5400
5465
  state2.currentAccountIndexByFamily[family] = index;
5466
+ state2.routedByFamily[family] = routed;
5401
5467
  if (!state2.parentId) {
5402
5468
  this.setGlobalActiveIndex(family, index);
5403
5469
  }
@@ -5451,6 +5517,18 @@ var init_account_selector = __esm({
5451
5517
  }
5452
5518
  return null;
5453
5519
  }
5520
+ getRoutedAccountForFamily(family, identity4) {
5521
+ return this.getRequestSessionState(identity4).routedByFamily[family] ? this.getCurrentAccountForFamily(family, identity4) : null;
5522
+ }
5523
+ /** Use a roster row already admitted by routing, without local quota or retry filters. */
5524
+ useRoutedAccount(account, family, model, identity4, pinSelection) {
5525
+ if (this.accounts[account.index] !== account || account.enabled === false || account.accountIneligible || account.verificationRequired)
5526
+ return null;
5527
+ this.markTouchedForQuota(account, getQuotaKey(family, model));
5528
+ if (pinSelection)
5529
+ this.setActiveIndex(family, account.index, identity4, true);
5530
+ return account;
5531
+ }
5454
5532
  /**
5455
5533
  * Numeric active indexes for each model family. Exposed so callers
5456
5534
  * that persist `activeIndexByFamily` (e.g. command-data's remove
@@ -5486,7 +5564,7 @@ var init_account_selector = __esm({
5486
5564
  this.lastToastAccountIndex = accountIndex;
5487
5565
  this.lastToastTime = this.now();
5488
5566
  }
5489
- getCurrentOrNextForFamily(family, model, strategy = "sticky", pidOffsetEnabled = false, softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1e3, identity4, excludeIndexes) {
5567
+ getCurrentOrNextForFamily(family, model, strategy = "sticky", pidOffsetEnabled = false, softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1e3, identity4, excludeIndexes, pinSelection = true) {
5490
5568
  const quotaKey = getQuotaKey(family, model);
5491
5569
  const effectiveSoftQuotaThreshold = this.getEffectiveSoftQuotaThreshold(softQuotaThresholdPercent, excludeIndexes);
5492
5570
  if (identity4) {
@@ -5495,6 +5573,8 @@ var init_account_selector = __esm({
5495
5573
  clearExpiredRateLimits(pinned, this.now);
5496
5574
  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
5575
  if (!unavailable2) {
5576
+ if (pinSelection)
5577
+ this.getRequestSessionState(identity4).routedByFamily[family] = false;
5498
5578
  this.markTouchedForQuota(pinned, quotaKey);
5499
5579
  return pinned;
5500
5580
  }
@@ -5504,7 +5584,8 @@ var init_account_selector = __esm({
5504
5584
  const next2 = this.getNextForFamily(family, model, effectiveSoftQuotaThreshold, softQuotaCacheTtlMs, identity4, excludeIndexes);
5505
5585
  if (next2) {
5506
5586
  this.markTouchedForQuota(next2, quotaKey);
5507
- this.setActiveIndex(family, next2.index, identity4);
5587
+ if (pinSelection)
5588
+ this.setActiveIndex(family, next2.index, identity4);
5508
5589
  }
5509
5590
  return next2;
5510
5591
  }
@@ -5532,12 +5613,14 @@ var init_account_selector = __esm({
5532
5613
  if (selected) {
5533
5614
  this.touchLastUsed(selected);
5534
5615
  this.markTouchedForQuota(selected, quotaKey);
5535
- this.setActiveIndex(family, selected.index, identity4);
5616
+ if (pinSelection)
5617
+ this.setActiveIndex(family, selected.index, identity4);
5536
5618
  return selected;
5537
5619
  }
5538
5620
  }
5539
5621
  }
5540
5622
  const offsetApplied = identity4 ? this.getRequestSessionState(identity4).offsetAppliedByFamily : this.sessionOffsetApplied;
5623
+ let temporaryIndex;
5541
5624
  if (pidOffsetEnabled && !offsetApplied[family] && this.accounts.length > 1) {
5542
5625
  const pidOffset = this.pid % this.accounts.length;
5543
5626
  const activeIndex = this.getActiveIndex(family, identity4);
@@ -5550,10 +5633,14 @@ var init_account_selector = __esm({
5550
5633
  fromIndex: baseIndex,
5551
5634
  toIndex: newIndex
5552
5635
  });
5553
- this.setActiveIndex(family, newIndex, identity4);
5554
- offsetApplied[family] = true;
5636
+ if (pinSelection) {
5637
+ this.setActiveIndex(family, newIndex, identity4);
5638
+ offsetApplied[family] = true;
5639
+ } else {
5640
+ temporaryIndex = newIndex;
5641
+ }
5555
5642
  }
5556
- const current = this.getCurrentAccountForFamily(family, identity4);
5643
+ const current = temporaryIndex === void 0 ? this.getCurrentAccountForFamily(family, identity4) : this.accounts[temporaryIndex] ?? null;
5557
5644
  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
5645
  if (current && preferred.includes(current)) {
5559
5646
  clearExpiredRateLimits(current, this.now);
@@ -5567,7 +5654,8 @@ var init_account_selector = __esm({
5567
5654
  const next = this.getNextForFamily(family, model, effectiveSoftQuotaThreshold, softQuotaCacheTtlMs, identity4, excludeIndexes);
5568
5655
  if (next) {
5569
5656
  this.markTouchedForQuota(next, quotaKey);
5570
- this.setActiveIndex(family, next.index, identity4);
5657
+ if (pinSelection)
5658
+ this.setActiveIndex(family, next.index, identity4);
5571
5659
  }
5572
5660
  return next;
5573
5661
  }
@@ -8548,7 +8636,7 @@ function writeConsoleLog(level, ...args) {
8548
8636
  }
8549
8637
  function createLogger(module) {
8550
8638
  const service = `antigravity.${module}`;
8551
- const log18 = (level, message, extra) => {
8639
+ const log19 = (level, message, extra) => {
8552
8640
  if (_sink) {
8553
8641
  try {
8554
8642
  _sink({ service, level, message, extra });
@@ -8562,10 +8650,10 @@ function createLogger(module) {
8562
8650
  }
8563
8651
  };
8564
8652
  return {
8565
- debug: (message, extra) => log18("debug", message, extra),
8566
- info: (message, extra) => log18("info", message, extra),
8567
- warn: (message, extra) => log18("warn", message, extra),
8568
- error: (message, extra) => log18("error", message, extra)
8653
+ debug: (message, extra) => log19("debug", message, extra),
8654
+ info: (message, extra) => log19("info", message, extra),
8655
+ warn: (message, extra) => log19("warn", message, extra),
8656
+ error: (message, extra) => log19("error", message, extra)
8569
8657
  };
8570
8658
  }
8571
8659
  var ENV_CONSOLE_LOG, _sink;
@@ -8917,9 +9005,9 @@ async function acquireWithRetry(path5, sleep5) {
8917
9005
  return lock;
8918
9006
  }
8919
9007
  if (attempt < RETRY_DELAYS_MS.length) {
8920
- const delay4 = RETRY_DELAYS_MS[attempt];
8921
- if (delay4 !== void 0) {
8922
- await sleep5(delay4);
9008
+ const delay5 = RETRY_DELAYS_MS[attempt];
9009
+ if (delay5 !== void 0) {
9010
+ await sleep5(delay5);
8923
9011
  }
8924
9012
  }
8925
9013
  }
@@ -10000,6 +10088,12 @@ var init_account_manager = __esm({
10000
10088
  getCurrentAccountForFamily(family, identity4) {
10001
10089
  return this.selection.getCurrentAccountForFamily(family, identity4);
10002
10090
  }
10091
+ getRoutedAccountForFamily(family, identity4) {
10092
+ return this.selection.getRoutedAccountForFamily(family, identity4);
10093
+ }
10094
+ useRoutedAccount(account, family, model, identity4, pinSelection) {
10095
+ return this.selection.useRoutedAccount(account, family, model, identity4, pinSelection);
10096
+ }
10003
10097
  /**
10004
10098
  * Numeric active indexes for each model family. Exposed so callers
10005
10099
  * that persist `activeIndexByFamily` (e.g. command-data's remove
@@ -10022,8 +10116,8 @@ var init_account_manager = __esm({
10022
10116
  markToastShown(accountIndex) {
10023
10117
  this.selection.markToastShown(accountIndex);
10024
10118
  }
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);
10119
+ getCurrentOrNextForFamily(family, model, strategy = "sticky", pidOffsetEnabled = false, softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1e3, identity4, excludeIndexes, pinSelection = true) {
10120
+ return this.selection.getCurrentOrNextForFamily(family, model, strategy, pidOffsetEnabled, softQuotaThresholdPercent, softQuotaCacheTtlMs, identity4, excludeIndexes, pinSelection);
10027
10121
  }
10028
10122
  getNextForFamily(family, model, softQuotaThresholdPercent = 100, softQuotaCacheTtlMs = 10 * 60 * 1e3, identity4, excludeIndexes) {
10029
10123
  return this.selection.getNextForFamily(family, model, softQuotaThresholdPercent, softQuotaCacheTtlMs, identity4, excludeIndexes);
@@ -15458,14 +15552,19 @@ var init_torn = __esm({
15458
15552
  });
15459
15553
 
15460
15554
  // ../core/dist/common-auth-embedded/store/mutate.js
15461
- import { setTimeout as snapshotDelay } from "node:timers/promises";
15555
+ import { setTimeout as delay } from "node:timers/promises";
15462
15556
  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;
15557
+ for (let attempt = 0; ; attempt++) {
15558
+ try {
15559
+ return await readPrivateText(path5, windowsPrivateFiles);
15560
+ } catch (error) {
15561
+ if (error.code === "ENOENT")
15562
+ return void 0;
15563
+ const wait2 = sharingRetryDelays[attempt];
15564
+ if (wait2 === void 0 || !isWindowsSharingViolation(error))
15565
+ throw error;
15566
+ await delay(wait2);
15567
+ }
15469
15568
  }
15470
15569
  }
15471
15570
  function parseFile(text2) {
@@ -15482,12 +15581,21 @@ async function readPoolConfig(path5) {
15482
15581
  }
15483
15582
  async function readPool(ctx) {
15484
15583
  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);
15584
+ let configText;
15585
+ let stateText;
15586
+ let checkedConfigText;
15587
+ try {
15588
+ configText = await readText(ctx.configPath);
15589
+ stateText = await readText(ctx.statePath);
15590
+ checkedConfigText = await readText(ctx.configPath);
15591
+ } catch (error) {
15592
+ if (isWindowsSharingViolation(error))
15593
+ break;
15594
+ throw error;
15595
+ }
15488
15596
  if (configText !== checkedConfigText) {
15489
15597
  if (attempt < 2)
15490
- await snapshotDelay(2 + Math.floor(Math.random() * 4));
15598
+ await delay(2 + Math.floor(Math.random() * 4));
15491
15599
  continue;
15492
15600
  }
15493
15601
  const config = classifyConfig(parseFile(configText));
@@ -15667,7 +15775,7 @@ async function runOperation(ctx, operation, rowId2, onFailure, body) {
15667
15775
  await locks.releaseAll();
15668
15776
  }
15669
15777
  }
15670
- var Transaction;
15778
+ var sharingRetryDelays, Transaction;
15671
15779
  var init_mutate = __esm({
15672
15780
  "../core/dist/common-auth-embedded/store/mutate.js"() {
15673
15781
  "use strict";
@@ -15680,6 +15788,7 @@ var init_mutate = __esm({
15680
15788
  init_reserved();
15681
15789
  init_schema();
15682
15790
  init_torn();
15791
+ sharingRetryDelays = [5, 10, 20, 40, 80, 160, 320, 400];
15683
15792
  Transaction = class {
15684
15793
  ctx;
15685
15794
  snapshot;
@@ -17631,11 +17740,11 @@ var init_quota_writer = __esm({
17631
17740
  overlay(rows) {
17632
17741
  return rows.map((row) => this.overlayRow(row));
17633
17742
  }
17634
- schedule(delay4) {
17743
+ schedule(delay5) {
17635
17744
  if (this.running || this.timer || !this.pending.size || this.stopped)
17636
17745
  return;
17637
17746
  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), () => {
17747
+ this.timer = this.clock.schedule(Math.max(delay5, remaining), () => {
17639
17748
  this.timer = void 0;
17640
17749
  return this.flush();
17641
17750
  });
@@ -17735,8 +17844,8 @@ var init_quota_writer = __esm({
17735
17844
  this.running = void 0;
17736
17845
  for (const wake of this.wake)
17737
17846
  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);
17847
+ const delay5 = this.failures ? Math.min(5e3, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS;
17848
+ this.schedule(delay5);
17740
17849
  }
17741
17850
  })();
17742
17851
  return this.running;
@@ -21424,12 +21533,12 @@ var init_watch = __esm({
21424
21533
  this.#options.logger?.debug("claustrum vault watch", { mode, reason });
21425
21534
  this.#options.onMode?.(mode);
21426
21535
  }
21427
- #later(delay4, run) {
21536
+ #later(delay5, run) {
21428
21537
  this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
21429
21538
  this.#timer = void 0;
21430
21539
  if (!this.#stopped)
21431
21540
  run();
21432
- }, delay4);
21541
+ }, delay5);
21433
21542
  this.#timer.unref?.();
21434
21543
  }
21435
21544
  async #open(resubscribed) {
@@ -21501,10 +21610,10 @@ var init_watch = __esm({
21501
21610
  const now2 = (this.#options.now ?? Date.now)();
21502
21611
  if (watch2.acceptedAt !== void 0 && now2 - watch2.acceptedAt >= SAFETY_POLL_MS)
21503
21612
  this.#closes = 0;
21504
- const delay4 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
21613
+ const delay5 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
21505
21614
  this.#closes++;
21506
21615
  this.#setMode("polling", "resubscribing");
21507
- this.#later(delay4, () => void this.#open(true));
21616
+ this.#later(delay5, () => void this.#open(true));
21508
21617
  return;
21509
21618
  }
21510
21619
  this.#fallback(end.kind);
@@ -21795,12 +21904,12 @@ var init_insula = __esm({
21795
21904
  watch2?.handle?.stop();
21796
21905
  this.#mode = "polling";
21797
21906
  }
21798
- #later(delay4) {
21907
+ #later(delay5) {
21799
21908
  this.#timer = (this.#timers.setTimeoutImpl ?? setTimeout)(() => {
21800
21909
  this.#timer = void 0;
21801
21910
  if (this.#watchers > 0 && !this.#watch)
21802
21911
  this.#open();
21803
- }, delay4);
21912
+ }, delay5);
21804
21913
  this.#timer.unref?.();
21805
21914
  }
21806
21915
  #open() {
@@ -21848,10 +21957,10 @@ var init_insula = __esm({
21848
21957
  return;
21849
21958
  }
21850
21959
  if (watch2.notices > 0) {
21851
- const delay4 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
21960
+ const delay5 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
21852
21961
  this.#closes++;
21853
21962
  this.#mode = "polling";
21854
- this.#later(delay4);
21963
+ this.#later(delay5);
21855
21964
  return;
21856
21965
  }
21857
21966
  this.#mode = "fallback";
@@ -23029,22 +23138,22 @@ function credentialTypeOf(row, family) {
23029
23138
  return notMine;
23030
23139
  if ("classify" in family) {
23031
23140
  const metadata = rowFactsOf(row);
23032
- let type;
23141
+ let type2;
23033
23142
  switch (metadata.authMethod) {
23034
23143
  case "apikey":
23035
- type = "api_key";
23144
+ type2 = "api_key";
23036
23145
  break;
23037
23146
  case "chatgpt":
23038
23147
  case "antigravity":
23039
23148
  case "oauth":
23040
- type = "oauth";
23149
+ type2 = "oauth";
23041
23150
  break;
23042
23151
  default:
23043
23152
  return { kind: "refused", code: "unknown-auth-method" };
23044
23153
  }
23045
23154
  const facts = {
23046
23155
  credentialId: row.id,
23047
- credentialType: type,
23156
+ credentialType: type2,
23048
23157
  categories: row.categories,
23049
23158
  refreshAdapter: row.refreshAdapter,
23050
23159
  ...metadata
@@ -23056,24 +23165,37 @@ function credentialTypeOf(row, family) {
23056
23165
  if (result.kind === "not-mine")
23057
23166
  return notMine;
23058
23167
  if (result.kind === "mine" && typeof result.member === "string")
23059
- return { kind: "mine", type, member: result.member };
23168
+ return { kind: "mine", type: type2, member: result.member };
23060
23169
  if (result.kind === "refused" && typeof result.code === "string" && /^[a-z][a-z0-9-]{0,31}$/.test(result.code) && !result.code.includes("\n") && family.refusalCodes.includes(result.code))
23061
23170
  return { kind: "refused", code: result.code };
23062
23171
  } catch {
23063
23172
  }
23064
23173
  return { kind: "refused", code: "unclassified" };
23065
23174
  }
23066
- if (row.credentialType !== "oauth" && row.credentialType !== "api_key")
23175
+ const type = row.credentialType;
23176
+ if (type === "oauth") {
23177
+ if (row.refreshAdapter !== family.refreshAdapter)
23178
+ return notMine;
23179
+ } else if (type === "api_key") {
23180
+ if (!family.apiKeys || row.refreshAdapter !== void 0)
23181
+ return notMine;
23182
+ } else {
23067
23183
  return notMine;
23068
- if (row.credentialType === "oauth")
23069
- return row.refreshAdapter === family.refreshAdapter ? { kind: "mine", type: "oauth" } : notMine;
23070
- if (row.credentialType === "api_key" && family.apiKeys)
23071
- return row.refreshAdapter === void 0 ? { kind: "mine", type: "api_key" } : notMine;
23072
- return notMine;
23184
+ }
23185
+ const { authMethod } = rowFactsOf(row, { includeProviderIds: false });
23186
+ if (authMethod !== void 0) {
23187
+ const matchesType = type === "oauth" ? authMethod === "chatgpt" || authMethod === "antigravity" || authMethod === "oauth" : authMethod === "apikey";
23188
+ if (!matchesType)
23189
+ return { kind: "refused", code: "unknown-auth-method" };
23190
+ }
23191
+ return { kind: "mine", type };
23073
23192
  }
23074
- function rowFactsOf(row) {
23193
+ function rowFactsOf(row, { includeProviderIds = true } = {}) {
23075
23194
  const metadata = row;
23076
- return { providerIds: metadata.providerIds, authMethod: metadata.authMethod };
23195
+ return {
23196
+ providerIds: includeProviderIds ? metadata.providerIds : void 0,
23197
+ authMethod: metadata.authMethod
23198
+ };
23077
23199
  }
23078
23200
  function grantReachOf(listed) {
23079
23201
  const { grants, grantTuples } = listed;
@@ -23405,14 +23527,15 @@ var init_custody = __esm({
23405
23527
  for (const record5 of skipped)
23406
23528
  this.#logger.warn("skipped malformed vault record", record5);
23407
23529
  const grantReach = grantReachOf(inventory);
23530
+ const classifying = "classify" in this.#family;
23408
23531
  return {
23409
23532
  view: inventory.view,
23410
23533
  credentials: Object.freeze(credentials),
23411
23534
  skipped: Object.freeze(skipped),
23412
- ..."classify" in this.#family && {
23413
- refused: Object.freeze(refused2),
23414
- notMine
23535
+ ...(classifying || refused2.length > 0) && {
23536
+ refused: Object.freeze(refused2)
23415
23537
  },
23538
+ ...classifying && { notMine },
23416
23539
  ...grantReach && { grantReach }
23417
23540
  };
23418
23541
  }
@@ -23540,9 +23663,9 @@ var init_custody = __esm({
23540
23663
  users: 0,
23541
23664
  error,
23542
23665
  pending: Promise.resolve().then(async () => {
23543
- let delay4 = 250;
23666
+ let delay5 = 250;
23544
23667
  for (; ; ) {
23545
- await this.#receiptBackoff(delay4, controller.signal);
23668
+ await this.#receiptBackoff(delay5, controller.signal);
23546
23669
  try {
23547
23670
  return await this.#authorizeFresh(identity4, token, controller.signal);
23548
23671
  } catch (failure2) {
@@ -23550,7 +23673,7 @@ var init_custody = __esm({
23550
23673
  if (classifyVaultFailure(failure2) !== "unreachable")
23551
23674
  throw failure2;
23552
23675
  created.error = failure2;
23553
- delay4 = Math.min(delay4 * 2, 1e3);
23676
+ delay5 = Math.min(delay5 * 2, 1e3);
23554
23677
  }
23555
23678
  }
23556
23679
  })
@@ -23604,7 +23727,7 @@ var init_custody = __esm({
23604
23727
  }
23605
23728
  }
23606
23729
  }
23607
- #receiptBackoff(delay4, signal) {
23730
+ #receiptBackoff(delay5, signal) {
23608
23731
  this.#check(signal);
23609
23732
  return new Promise((resolve34, reject) => {
23610
23733
  const abort = () => {
@@ -23615,7 +23738,7 @@ var init_custody = __esm({
23615
23738
  const timer = this.#setTimeout(() => {
23616
23739
  signal.removeEventListener("abort", abort);
23617
23740
  resolve34();
23618
- }, delay4);
23741
+ }, delay5);
23619
23742
  timer.unref?.();
23620
23743
  signal.addEventListener("abort", abort, { once: true });
23621
23744
  if (signal.aborted)
@@ -24639,11 +24762,11 @@ function pendingVaultQuota(path5, roster) {
24639
24762
  function hasPendingVaultQuota(path5) {
24640
24763
  return !!writers.get(resolve11(path5))?.pending.size;
24641
24764
  }
24642
- function schedule(writer, delay4) {
24765
+ function schedule(writer, delay5) {
24643
24766
  if (writer.running || writer.timer || !writer.pending.size || writer.abort.signal.aborted)
24644
24767
  return;
24645
24768
  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), () => {
24769
+ writer.timer = writer.clock.schedule(Math.max(delay5, remaining), () => {
24647
24770
  writer.timer = void 0;
24648
24771
  return flush(writer);
24649
24772
  });
@@ -25080,13 +25203,13 @@ var init_consumer = __esm({
25080
25203
  }
25081
25204
  if (this.#shutdown.signal.aborted)
25082
25205
  return;
25083
- const delay4 = this.#options.pollIntervalMs ?? 5e3;
25084
- if (delay4 <= 0)
25206
+ const delay5 = this.#options.pollIntervalMs ?? 5e3;
25207
+ if (delay5 <= 0)
25085
25208
  return;
25086
25209
  this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
25087
25210
  this.#timer = void 0;
25088
25211
  void this.#track(tick());
25089
- }, delay4);
25212
+ }, delay5);
25090
25213
  this.#timer.unref?.();
25091
25214
  };
25092
25215
  void this.#track(tick());
@@ -26556,13 +26679,13 @@ var init_hub = __esm({
26556
26679
  }
26557
26680
  if (this.#shutdown.signal.aborted)
26558
26681
  return;
26559
- const delay4 = this.#options.pollIntervalMs ?? 5e3;
26560
- if (delay4 <= 0)
26682
+ const delay5 = this.#options.pollIntervalMs ?? 5e3;
26683
+ if (delay5 <= 0)
26561
26684
  return;
26562
26685
  this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
26563
26686
  this.#timer = void 0;
26564
26687
  void this.#track(this.#tick());
26565
- }, delay4);
26688
+ }, delay5);
26566
26689
  this.#timer.unref?.();
26567
26690
  }
26568
26691
  /**
@@ -26853,12 +26976,12 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
26853
26976
  if (!released && lastUpdate + RENEWAL_STALE < Date.now())
26854
26977
  compromise();
26855
26978
  }
26856
- function schedule2(delay4 = UPDATE) {
26979
+ function schedule2(delay5 = UPDATE) {
26857
26980
  if (released)
26858
26981
  return;
26859
26982
  timer = setTimeout(() => {
26860
26983
  void update();
26861
- }, delay4);
26984
+ }, delay5);
26862
26985
  timer.unref();
26863
26986
  }
26864
26987
  function retry(error) {
@@ -27638,31 +27761,6 @@ var init_harness_identity = __esm({
27638
27761
  }
27639
27762
  });
27640
27763
 
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
27764
  // ../core/dist/pre-response-deadline.js
27667
27765
  function preResponseTimeoutResponse() {
27668
27766
  return new Response(JSON.stringify({
@@ -27818,6 +27916,150 @@ var init_pre_response_deadline = __esm({
27818
27916
  }
27819
27917
  });
27820
27918
 
27919
+ // ../core/dist/vault-folder-refusal.js
27920
+ function sharedVaultTokenFolder(error) {
27921
+ if (!(error instanceof Error))
27922
+ return void 0;
27923
+ const client = CLIENT_REFUSAL.exec(error.message);
27924
+ if (client?.[1] && client[2] && SHARED_FOLDER_REASON.test(client[2]))
27925
+ return client[1];
27926
+ const embedded = EMBEDDED_REFUSAL.exec(error.message);
27927
+ if (embedded?.[1])
27928
+ return embedded[1];
27929
+ return void 0;
27930
+ }
27931
+ function sharedVaultTokenFolderText(folder) {
27932
+ 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.`;
27933
+ }
27934
+ function sharedVaultTokenFolderOutcome(error) {
27935
+ const folder = sharedVaultTokenFolder(error);
27936
+ return folder === void 0 ? void 0 : {
27937
+ ok: false,
27938
+ text: sharedVaultTokenFolderText(folder),
27939
+ code: SHARED_VAULT_TOKEN_FOLDER_CODE
27940
+ };
27941
+ }
27942
+ var CLIENT_REFUSAL, SHARED_FOLDER_REASON, EMBEDDED_REFUSAL, SHARED_VAULT_TOKEN_FOLDER_CODE;
27943
+ var init_vault_folder_refusal = __esm({
27944
+ "../core/dist/vault-folder-refusal.js"() {
27945
+ "use strict";
27946
+ CLIENT_REFUSAL = /^enrollment token folder (.+) is not private: (.+)$/s;
27947
+ SHARED_FOLDER_REASON = /^(?:foreign owner|world-writable ancestor|group-writable ancestor|could not (?:read|parse) \S+ to establish a user-private group)/;
27948
+ EMBEDDED_REFUSAL = /^Claustrum enrollment path has a writable ancestor: (.+?)\. Another user could replace it\./s;
27949
+ SHARED_VAULT_TOKEN_FOLDER_CODE = "vault-folder-shared";
27950
+ }
27951
+ });
27952
+
27953
+ // ../core/dist/host-failure.js
27954
+ function markUpstreamFailure(error) {
27955
+ const failure2 = error instanceof Error ? error : new Error(String(error));
27956
+ upstreamFailures.add(failure2);
27957
+ return failure2;
27958
+ }
27959
+ function isUpstreamFailure(error) {
27960
+ return error instanceof Error && upstreamFailures.has(error);
27961
+ }
27962
+ function errorChain(error) {
27963
+ const chain = [];
27964
+ for (let current = error; current instanceof Error && !chain.includes(current); current = current.cause) {
27965
+ chain.push(current);
27966
+ }
27967
+ return chain;
27968
+ }
27969
+ function failureMessage2(chain) {
27970
+ if (chain.some((error) => error.name === "PiSlotError"))
27971
+ return HOST_CREDENTIAL_SLOT_FAILURE;
27972
+ if (chain.some((error) => [
27973
+ "LockContentionError",
27974
+ "LockOwnershipError",
27975
+ "FileLockOwnershipError",
27976
+ "AccountStorageLockContentionError"
27977
+ ].includes(error.name) || error instanceof AccountRepositoryError && ["lock-contention", "lock-ownership"].includes(error.failure.kind)))
27978
+ return HOST_STORE_LOCK_FAILURE;
27979
+ if (chain.some((error) => sharedVaultTokenFolder(error) !== void 0))
27980
+ return HOST_VAULT_FOLDER_FAILURE;
27981
+ if (chain.some((error) => error instanceof AccountRepositoryError || [
27982
+ "PrivateFileError",
27983
+ "AccountStorageUnreadableError",
27984
+ "AccountStoreNotReadyError",
27985
+ "AccountStoreAdmissionError"
27986
+ ].includes(error.name)))
27987
+ return HOST_STORE_READ_FAILURE;
27988
+ return HOST_REQUEST_FAILURE;
27989
+ }
27990
+ function diagnostics(chain, error) {
27991
+ const messages = chain.length ? chain.map((entry) => {
27992
+ const details = entry;
27993
+ return [
27994
+ entry.name,
27995
+ details.code,
27996
+ entry.message,
27997
+ ...[
27998
+ details.path,
27999
+ details.details?.path,
28000
+ details.details?.target
28001
+ ].filter((path5) => path5 && !entry.message.includes(path5)),
28002
+ details.details?.backupPath,
28003
+ details.details?.reason
28004
+ ].filter(Boolean).join(": ");
28005
+ }) : [String(error)];
28006
+ return redactCredentialText([...new Set(messages)].join("; caused by "));
28007
+ }
28008
+ function hostFailure(error, log19) {
28009
+ 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")
28010
+ return error;
28011
+ const chain = errorChain(error);
28012
+ log19(diagnostics(chain, error));
28013
+ if (error instanceof Error && error.name === "ClaustrumCredentialError" && "code" in error && error.code === "grant_denied") {
28014
+ return Object.assign(new HostRefusalError("The vault refused access to the selected account. Check the plugin log for details."), { code: "grant_denied" });
28015
+ }
28016
+ return new HostRefusalError(failureMessage2(chain));
28017
+ }
28018
+ var HOST_STORE_READ_FAILURE, HOST_STORE_LOCK_FAILURE, HOST_CREDENTIAL_SLOT_FAILURE, HOST_VAULT_FOLDER_FAILURE, HOST_REQUEST_FAILURE, HostRefusalError, upstreamFailures;
28019
+ var init_host_failure = __esm({
28020
+ "../core/dist/host-failure.js"() {
28021
+ "use strict";
28022
+ init_account_migration();
28023
+ init_account_repository();
28024
+ init_credential_redaction();
28025
+ init_pre_response_deadline();
28026
+ init_vault_folder_refusal();
28027
+ HOST_STORE_READ_FAILURE = "antigravity-auth could not read its account store. Check the plugin log for details.";
28028
+ HOST_STORE_LOCK_FAILURE = "antigravity-auth could not secure its account store. Check the plugin log for details.";
28029
+ HOST_CREDENTIAL_SLOT_FAILURE = "antigravity-auth could not update the host credential slot. Check the plugin log for details.";
28030
+ HOST_VAULT_FOLDER_FAILURE = "antigravity-auth could not use its vault folder. Check the plugin log for details.";
28031
+ HOST_REQUEST_FAILURE = "antigravity-auth could not complete the operation. Check the plugin log for details.";
28032
+ HostRefusalError = class extends Error {
28033
+ };
28034
+ upstreamFailures = /* @__PURE__ */ new WeakSet();
28035
+ }
28036
+ });
28037
+
28038
+ // ../core/dist/model-types.js
28039
+ var init_model_types = __esm({
28040
+ "../core/dist/model-types.js"() {
28041
+ "use strict";
28042
+ }
28043
+ });
28044
+
28045
+ // ../core/dist/pi-paths.js
28046
+ import { homedir } from "node:os";
28047
+ import { dirname as dirname13, join as join10 } from "node:path";
28048
+ function getPiConfigDir() {
28049
+ return process.env.PI_AGENT_DIR?.trim() || join10(homedir(), ".pi", "agent");
28050
+ }
28051
+ function getPiAntigravityAuthFile() {
28052
+ return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join10(getPiConfigDir(), "antigravity-accounts.json");
28053
+ }
28054
+ function getPiAntigravityVaultDir() {
28055
+ return join10(dirname13(getPiAntigravityAuthFile()), "antigravity-auth-vault");
28056
+ }
28057
+ var init_pi_paths = __esm({
28058
+ "../core/dist/pi-paths.js"() {
28059
+ "use strict";
28060
+ }
28061
+ });
28062
+
27821
28063
  // ../core/dist/project.js
27822
28064
  function buildBootstrapRequestBody(extra = {}) {
27823
28065
  return {
@@ -28665,7 +28907,7 @@ function applyAgyNativeGenerationConfig(wireModel, generationConfig, options = {
28665
28907
  includeThoughts: true,
28666
28908
  ...typeof budget === "number" ? { thinkingBudget: budget } : { thinkingLevel: capturedTier.toUpperCase() }
28667
28909
  };
28668
- } else if (isGeminiHydrogenModel(wireModel)) {
28910
+ } else if (supportsGeminiXHigh(wireModel)) {
28669
28911
  const tier = wireModel.toLowerCase().split("-").at(-1);
28670
28912
  generationConfig.thinkingConfig = {
28671
28913
  includeThoughts: true,
@@ -29542,10 +29784,10 @@ function getAgyGemini31ProThinkingBudget(tier) {
29542
29784
  function resolveModelWithTier(requestedModel) {
29543
29785
  const isAntigravity = QUOTA_PREFIX_REGEX.test(requestedModel);
29544
29786
  const modelWithoutQuota = requestedModel.replace(QUOTA_PREFIX_REGEX, "");
29545
- if (isGeminiHydrogenModel(modelWithoutQuota)) {
29546
- const tier2 = modelWithoutQuota.toLowerCase().match(HYDROGEN_TIER_REGEX)?.[1];
29787
+ if (supportsGeminiXHigh(modelWithoutQuota)) {
29788
+ const tier2 = modelWithoutQuota.toLowerCase().match(XHIGH_TIER_REGEX)?.[1];
29547
29789
  return {
29548
- actualModel: getGeminiHydrogenAntigravityModel(tier2),
29790
+ actualModel: isGeminiNeonModel(modelWithoutQuota) ? getGeminiNeonAntigravityModel(tier2) : getGeminiHydrogenAntigravityModel(tier2),
29549
29791
  thinkingLevel: tier2 ?? "high",
29550
29792
  tier: tier2 ?? "high",
29551
29793
  isThinkingModel: true
@@ -29723,7 +29965,7 @@ function resolveAntigravityModel(requestedModel) {
29723
29965
  const prefixedModel = `antigravity-${transformedModel}`;
29724
29966
  return resolveModelWithTier(prefixedModel);
29725
29967
  }
29726
- var THINKING_TIER_BUDGETS, MODEL_ALIASES, TIER_REGEX, HYDROGEN_TIER_REGEX, QUOTA_PREFIX_REGEX, GEMINI_3_PRO_REGEX, GEMINI_3_FLASH_REGEX, IMAGE_GENERATION_MODELS;
29968
+ var THINKING_TIER_BUDGETS, MODEL_ALIASES, TIER_REGEX, XHIGH_TIER_REGEX, QUOTA_PREFIX_REGEX, GEMINI_3_PRO_REGEX, GEMINI_3_FLASH_REGEX, IMAGE_GENERATION_MODELS;
29727
29969
  var init_model_resolver = __esm({
29728
29970
  "../core/dist/transform/model-resolver.js"() {
29729
29971
  "use strict";
@@ -29736,7 +29978,7 @@ var init_model_resolver = __esm({
29736
29978
  };
29737
29979
  MODEL_ALIASES = getResolverAliasMap();
29738
29980
  TIER_REGEX = /-(minimal|low|medium|high)$/;
29739
- HYDROGEN_TIER_REGEX = /-(low|medium|high|xhigh)$/i;
29981
+ XHIGH_TIER_REGEX = /-(low|medium|high|xhigh)$/i;
29740
29982
  QUOTA_PREFIX_REGEX = /^antigravity-/i;
29741
29983
  GEMINI_3_PRO_REGEX = /^gemini-3(?:\.\d+)?-pro/i;
29742
29984
  GEMINI_3_FLASH_REGEX = /^gemini-3(?:\.\d+)?-flash/i;
@@ -30569,40 +30811,6 @@ var init_vault_enrollment_authority = __esm({
30569
30811
  }
30570
30812
  });
30571
30813
 
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
30814
  // ../core/dist/version.js
30607
30815
  function parseVersion(text2) {
30608
30816
  const match = text2.match(VERSION_REGEX);
@@ -30627,7 +30835,7 @@ function getAntigravityVersionResolution() {
30627
30835
  return lastResolution ?? { version: getAntigravityVersion(), source: "fallback" };
30628
30836
  }
30629
30837
  async function initAntigravityVersion() {
30630
- const log18 = createLogger("version");
30838
+ const log19 = createLogger("version");
30631
30839
  const fallback = getAntigravityVersion();
30632
30840
  let version;
30633
30841
  let source;
@@ -30641,15 +30849,15 @@ async function initAntigravityVersion() {
30641
30849
  } else {
30642
30850
  source = "fallback";
30643
30851
  setAntigravityVersion(fallback);
30644
- log18.info("version-fetch-failed", { fallback });
30852
+ log19.info("version-fetch-failed", { fallback });
30645
30853
  lastResolution = { version: fallback, source };
30646
30854
  return lastResolution;
30647
30855
  }
30648
30856
  }
30649
30857
  if (version !== fallback) {
30650
- log18.info("version-updated", { version, source, previous: fallback });
30858
+ log19.info("version-updated", { version, source, previous: fallback });
30651
30859
  } else {
30652
- log18.debug("version-unchanged", { version, source });
30860
+ log19.debug("version-unchanged", { version, source });
30653
30861
  }
30654
30862
  setAntigravityVersion(version);
30655
30863
  lastResolution = { version, source };
@@ -30699,6 +30907,7 @@ var init_dist = __esm({
30699
30907
  init_file_lock();
30700
30908
  init_fingerprint();
30701
30909
  init_harness_identity();
30910
+ init_host_failure();
30702
30911
  init_logger();
30703
30912
  init_model_registry();
30704
30913
  init_model_types();
@@ -30763,8 +30972,11 @@ function loadBackend2() {
30763
30972
  });
30764
30973
  return backend2;
30765
30974
  }
30975
+ function isSharingIoError2(detail) {
30976
+ return detail?.reason === "io-error" && (detail.win32Code === 32 || detail.win32Code === 303);
30977
+ }
30766
30978
  function isWindowsSharingViolation2(error) {
30767
- return windowsPrivateFiles2 && error instanceof PrivateFileError2 && error.reason === "io-error" && (error.win32Code === 32 || error.win32Code === 303);
30979
+ return windowsPrivateFiles2 && error instanceof PrivateFileError2 && isSharingIoError2(error);
30768
30980
  }
30769
30981
  async function privateOperation2(path5, stage, operation) {
30770
30982
  try {
@@ -30886,12 +31098,12 @@ async function replaceWindowsFile2(from, to, options = {}) {
30886
31098
  const delays = [0, 10, 20, 40, 80, 100];
30887
31099
  let original;
30888
31100
  let attempts2 = 0;
30889
- for (const delay4 of delays) {
31101
+ for (const delay5 of delays) {
30890
31102
  const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
30891
31103
  if (now2() >= deadline)
30892
31104
  break;
30893
- if (delay4)
30894
- await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay4, Math.max(0, deadline - now2())));
31105
+ if (delay5)
31106
+ await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay5, Math.max(0, deadline - now2())));
30895
31107
  if (now2() >= deadline)
30896
31108
  break;
30897
31109
  const fenceStart = now2();
@@ -31014,7 +31226,7 @@ var init_private_files2 = __esm({
31014
31226
  // The reason stays on `.reason`: its word "unavailable" would make
31015
31227
  // OpenCode 1 retry a plain error carrying this message.
31016
31228
  `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 });
31229
+ ) : 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
31230
  this.path = path5;
31019
31231
  this.stage = stage;
31020
31232
  this.name = "PrivateFileError";
@@ -32715,14 +32927,24 @@ function emptyRosterGuidance(cause, principal) {
32715
32927
  ];
32716
32928
  }
32717
32929
  }
32718
- function openCodeEmptyVaultRosterRefusal(cause, principal = OPENCODE_VAULT_ENROLLMENT_NAME) {
32719
- return cause === "unknown" ? void 0 : emptyRosterGuidance(cause, principal).join("\n");
32930
+ function openCodeEmptyVaultRosterRefusal(cause) {
32931
+ switch (cause) {
32932
+ case "no-grant":
32933
+ 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.";
32934
+ case "grant-reaches-nothing":
32935
+ return [
32936
+ "Vault access is approved, but the read grant reaches no Antigravity login in the vault.",
32937
+ `The vault operator updates the vault's logins with: ${VAULT_RECLASSIFY_COMMAND}`,
32938
+ `Then they check them with: ${VAULT_STATUS_COMMAND}`
32939
+ ].join("\n");
32940
+ case "unknown":
32941
+ return void 0;
32942
+ }
32720
32943
  }
32721
32944
  function createOpenCodeVaultAccountPool(options) {
32722
- const { grantPrincipal: principal, ...poolOptions } = options;
32723
32945
  return createVaultAccountPool({
32724
- ...poolOptions,
32725
- emptyRosterRefusal: (cause) => openCodeEmptyVaultRosterRefusal(cause, principal?.())
32946
+ ...options,
32947
+ emptyRosterRefusal: openCodeEmptyVaultRosterRefusal
32726
32948
  });
32727
32949
  }
32728
32950
  function enrollmentGuidance(status) {
@@ -33380,10 +33602,10 @@ function errorFile(error) {
33380
33602
  ...typeof stage === "string" && stage ? { stage } : {}
33381
33603
  };
33382
33604
  }
33383
- function logCleanupFailure(location, log18, step, error) {
33605
+ function logCleanupFailure(location, log19, step, error) {
33384
33606
  logOnce(
33385
33607
  `${location.key}\0cleanup`,
33386
- () => log18.warn(
33608
+ () => log19.warn(
33387
33609
  "antigravity-auth could not finish removing its old vault files from OpenCode's config folder; it tries again at the next start",
33388
33610
  {
33389
33611
  configDir: location.configDir,
@@ -33412,13 +33634,13 @@ function prepareRuntimeLayout(options) {
33412
33634
  return run;
33413
33635
  }
33414
33636
  async function decide(location, options) {
33415
- const log18 = options.log ?? createLogger4("runtime-layout");
33637
+ const log19 = options.log ?? createLogger4("runtime-layout");
33416
33638
  const stateDir = location.stateHomeDir;
33417
33639
  const markerPath = join18(stateDir, RUNTIME_LAYOUT_MARKER_FILE);
33418
33640
  const files = layoutFiles(location, options.accountFile);
33419
33641
  const fence = options.fence ?? defaultFence(options.version);
33420
33642
  const stateHome = async () => {
33421
- await settleVault(location, options, "state-home", log18);
33643
+ await settleVault(location, options, "state-home", log19);
33422
33644
  return "state-home";
33423
33645
  };
33424
33646
  let marker = await readMarker(markerPath, stateDir, files.vault.old);
@@ -33429,7 +33651,7 @@ async function decide(location, options) {
33429
33651
  join18(stateDir, RUNTIME_LAYOUT_MANIFEST_FILE)
33430
33652
  ).catch(() => true);
33431
33653
  if (!manifestLeft) {
33432
- await settleVault(location, options, "state-home", log18);
33654
+ await settleVault(location, options, "state-home", log19);
33433
33655
  return stateHome();
33434
33656
  }
33435
33657
  }
@@ -33441,7 +33663,7 @@ async function decide(location, options) {
33441
33663
  RUNTIME_LAYOUT_LOCK_NAME,
33442
33664
  markerPath,
33443
33665
  options.layoutLockWaitMs ?? LAYOUT_LOCK_WAIT_MS,
33444
- log18
33666
+ log19
33445
33667
  );
33446
33668
  } catch (error) {
33447
33669
  marker = await readMarker(markerPath, stateDir, files.vault.old);
@@ -33461,7 +33683,7 @@ async function decide(location, options) {
33461
33683
  const legacy = async () => {
33462
33684
  try {
33463
33685
  await lock.assertOwned();
33464
- await settleVault(location, options, "legacy", log18);
33686
+ await settleVault(location, options, "legacy", log19);
33465
33687
  } catch (error) {
33466
33688
  throw new RuntimeLayoutRefusal(stateDir, errorClass(error));
33467
33689
  }
@@ -33475,20 +33697,20 @@ async function decide(location, options) {
33475
33697
  if (!marker.oldFilesRemoved && !aliased)
33476
33698
  await finishOldFiles(location, files, markerPath, marker, lock, {
33477
33699
  fence,
33478
- log: log18,
33700
+ log: log19,
33479
33701
  steps: options.steps,
33480
33702
  oldSignatureCache: options.oldSignatureCacheFile ?? legacySignatureCacheFile()
33481
33703
  });
33482
33704
  else if (marker.oldFilesRemoved) {
33483
33705
  await refuseReappearedFiles(location, files);
33484
- await removeLeftoverManifest(location, lock, options.steps, log18);
33706
+ await removeLeftoverManifest(location, lock, options.steps, log19);
33485
33707
  }
33486
33708
  return await stateHome();
33487
33709
  }
33488
33710
  if (aliased) {
33489
33711
  logOnce(
33490
33712
  `${location.key}\0aliased`,
33491
- () => log18.warn(
33713
+ () => log19.warn(
33492
33714
  "antigravity-auth keeps its vault files in OpenCode's config folder: its state folder is that same folder",
33493
33715
  { configDir: location.configDir, stateDir }
33494
33716
  )
@@ -33497,14 +33719,14 @@ async function decide(location, options) {
33497
33719
  }
33498
33720
  const gate = await fence();
33499
33721
  if (!gate.open) {
33500
- logDeferral(location, gate.blockers, log18);
33722
+ logDeferral(location, gate.blockers, log19);
33501
33723
  return await legacy();
33502
33724
  }
33503
33725
  let markerStarted = false;
33504
33726
  try {
33505
33727
  const outcome = await moveFiles(location, files, markerPath, lock, {
33506
33728
  fence,
33507
- log: log18,
33729
+ log: log19,
33508
33730
  steps: options.steps,
33509
33731
  destinationPrivate: options.destinationPrivate ?? defaultDestinationPrivate,
33510
33732
  oldSignatureCache: options.oldSignatureCacheFile ?? legacySignatureCacheFile(),
@@ -33513,13 +33735,13 @@ async function decide(location, options) {
33513
33735
  }
33514
33736
  });
33515
33737
  if (outcome.kind === "deferred") {
33516
- logDeferral(location, outcome.blockers, log18);
33738
+ logDeferral(location, outcome.blockers, log19);
33517
33739
  return await legacy();
33518
33740
  }
33519
33741
  if (outcome.kind === "refused") {
33520
33742
  logOnce(
33521
33743
  `${location.key}\0refused`,
33522
- () => log18.warn(
33744
+ () => log19.warn(
33523
33745
  outcome.reason === "destination-not-private" ? "antigravity-auth keeps its vault files in OpenCode's config folder: the vault folder in its state folder already exists and is not private to your user. It was left unchanged; remove it if it holds nothing you need, then restart OpenCode." : "antigravity-auth keeps its vault files in OpenCode's config folder: it will not move them",
33524
33746
  { reason: outcome.reason, paths: outcome.paths, stateDir }
33525
33747
  )
@@ -33527,7 +33749,7 @@ async function decide(location, options) {
33527
33749
  return await legacy();
33528
33750
  }
33529
33751
  if (outcome.moved)
33530
- log18.info(
33752
+ log19.info(
33531
33753
  "antigravity-auth moved its vault files out of OpenCode's config folder",
33532
33754
  { from: files.vault.old, to: files.vault.next }
33533
33755
  );
@@ -33538,7 +33760,7 @@ async function decide(location, options) {
33538
33760
  return await stateHome();
33539
33761
  logOnce(
33540
33762
  `${location.key}\0failed`,
33541
- () => log18.warn(
33763
+ () => log19.warn(
33542
33764
  "antigravity-auth's vault files stay in OpenCode's config folder: moving them failed; the move is tried again at the next start",
33543
33765
  {
33544
33766
  configDir: location.configDir,
@@ -33587,7 +33809,7 @@ async function prepareAccountStore(options) {
33587
33809
  if (!await localAccountStoreAuthorized()) return void 0;
33588
33810
  const decided = decidedAccountStoreAnchor(location);
33589
33811
  if (decided) return decided;
33590
- const log18 = options.log ?? createLogger4("runtime-layout");
33812
+ const log19 = options.log ?? createLogger4("runtime-layout");
33591
33813
  const runKey = `${location.stateHomeDir}\0${location.key}`;
33592
33814
  let run = processState.storeRuns.get(runKey);
33593
33815
  if (!run) {
@@ -33598,12 +33820,12 @@ async function prepareAccountStore(options) {
33598
33820
  RUNTIME_LAYOUT_LOCK_NAME,
33599
33821
  join18(location.stateHomeDir, RUNTIME_LAYOUT_MARKER_FILE),
33600
33822
  options.layoutLockWaitMs ?? LAYOUT_LOCK_WAIT_MS,
33601
- log18
33823
+ log19
33602
33824
  );
33603
33825
  try {
33604
33826
  await lock.assertOwned();
33605
33827
  if (!await localAccountStoreAuthorized()) return void 0;
33606
- return await settleAccountStore(location, options, log18);
33828
+ return await settleAccountStore(location, options, log19);
33607
33829
  } finally {
33608
33830
  await lock.release();
33609
33831
  }
@@ -33614,20 +33836,20 @@ async function prepareAccountStore(options) {
33614
33836
  }
33615
33837
  return run;
33616
33838
  }
33617
- async function settleAccountStore(location, options, log18) {
33839
+ async function settleAccountStore(location, options, log19) {
33618
33840
  const decided = decidedAccountStoreAnchor(location);
33619
33841
  if (decided) return decided;
33620
- const anchor = await decideAccountStore(location, options, log18);
33842
+ const anchor = await decideAccountStore(location, options, log19);
33621
33843
  setAccountStoreAnchor(location, anchor);
33622
33844
  return anchor;
33623
33845
  }
33624
- async function decideAccountStore(location, options, log18) {
33625
- const keepConfig = () => recordAnchor(location, options, "config", log18);
33846
+ async function decideAccountStore(location, options, log19) {
33847
+ const keepConfig = () => recordAnchor(location, options, "config", log19);
33626
33848
  if (processHasOlderGeneration()) {
33627
33849
  logOnce(
33628
33850
  "older-generation-account-store",
33629
33851
  () => showLog(
33630
- log18,
33852
+ log19,
33631
33853
  "antigravity-auth keeps the account store in OpenCode's config folder until OpenCode restarts, because an older version of the plugin ran in this process.",
33632
33854
  { accountStore: "config" }
33633
33855
  )
@@ -33641,7 +33863,7 @@ async function decideAccountStore(location, options, log18) {
33641
33863
  if (!sameSpelling(forward.legacyPath, stateAnchor)) {
33642
33864
  logOnce(
33643
33865
  `${location.key}\0store-forward-elsewhere`,
33644
- () => log18.warn(
33866
+ () => log19.warn(
33645
33867
  "the account store moved to another folder than this process resolved; check XDG_STATE_HOME",
33646
33868
  { movedTo: forward.legacyPath, expected: stateAnchor }
33647
33869
  )
@@ -33652,9 +33874,9 @@ async function decideAccountStore(location, options, log18) {
33652
33874
  options,
33653
33875
  configAnchor,
33654
33876
  stateAnchor,
33655
- log18
33877
+ log19
33656
33878
  );
33657
- return recordAnchor(location, options, "state-home", log18);
33879
+ return recordAnchor(location, options, "state-home", log19);
33658
33880
  }
33659
33881
  if (decidedRuntimeLayout(location) === "legacy") return keepConfig();
33660
33882
  const configStore = await presentAccountStore(configAnchor);
@@ -33666,9 +33888,9 @@ async function decideAccountStore(location, options, log18) {
33666
33888
  `antigravity-auth cannot start: two account stores exist, one at ${configAnchor} and one at ${stateAnchor}, and neither is marked as moved. Keep the one you want and move the other one aside, then restart OpenCode.`
33667
33889
  );
33668
33890
  }
33669
- if (stateStore) return recordAnchor(location, options, "state-home", log18);
33891
+ if (stateStore) return recordAnchor(location, options, "state-home", log19);
33670
33892
  if (configStore) {
33671
- if (!await storeMovePathResolves(stateAnchor, location, log18))
33893
+ if (!await storeMovePathResolves(stateAnchor, location, log19))
33672
33894
  return keepConfig();
33673
33895
  return moveStore(
33674
33896
  location,
@@ -33676,21 +33898,21 @@ async function decideAccountStore(location, options, log18) {
33676
33898
  configAnchor,
33677
33899
  stateAnchor,
33678
33900
  false,
33679
- log18,
33901
+ log19,
33680
33902
  false
33681
33903
  );
33682
33904
  }
33683
- if (await storeArtefacts(stateAnchor) > 0 && !await abandonUnpublishedStore(location, stateAnchor, log18))
33905
+ if (await storeArtefacts(stateAnchor) > 0 && !await abandonUnpublishedStore(location, stateAnchor, log19))
33684
33906
  return keepConfig();
33685
- if (!await storeMovePathResolves(stateAnchor, location, log18))
33907
+ if (!await storeMovePathResolves(stateAnchor, location, log19))
33686
33908
  return keepConfig();
33687
- return initializeStore(location, options, stateAnchor, log18);
33909
+ return initializeStore(location, options, stateAnchor, log19);
33688
33910
  }
33689
- function showLog(log18, message, meta) {
33690
- if (log18.log) log18.log(message, meta);
33691
- else log18.info(message, meta);
33911
+ function showLog(log19, message, meta) {
33912
+ if (log19.log) log19.log(message, meta);
33913
+ else log19.info(message, meta);
33692
33914
  }
33693
- async function recordAnchor(location, options, anchor, log18) {
33915
+ async function recordAnchor(location, options, anchor, log19) {
33694
33916
  try {
33695
33917
  await recordProcessAnchor({
33696
33918
  key: location.key,
@@ -33702,32 +33924,32 @@ async function recordAnchor(location, options, anchor, log18) {
33702
33924
  }
33703
33925
  if (anchor === "state-home")
33704
33926
  showLog(
33705
- log18,
33927
+ log19,
33706
33928
  "antigravity-auth keeps its account store in its state folder",
33707
33929
  { accountStore: anchor }
33708
33930
  );
33709
33931
  return anchor;
33710
33932
  }
33711
- async function storeMovePathResolves(stateAnchor, location, log18) {
33933
+ async function storeMovePathResolves(stateAnchor, location, log19) {
33712
33934
  if (folderResolvesToItself(
33713
33935
  join18(location.stateHomeDir, "antigravity-accounts.json")
33714
33936
  ))
33715
33937
  return true;
33716
33938
  logOnce(
33717
33939
  `${location.key}\0store-linked-path`,
33718
- () => log18.warn(ACCOUNT_STORE_LINKED_PATH_MESSAGE, {
33940
+ () => log19.warn(ACCOUNT_STORE_LINKED_PATH_MESSAGE, {
33719
33941
  accountStore: stateAnchor,
33720
33942
  stateFolder: location.stateHomeDir
33721
33943
  })
33722
33944
  );
33723
33945
  return false;
33724
33946
  }
33725
- async function storeFenceOpen(location, options, log18) {
33947
+ async function storeFenceOpen(location, options, log19) {
33726
33948
  const gate = await (options.storeFence ?? defaultStoreFence(options.version))();
33727
33949
  if (gate.open) return true;
33728
33950
  logOnce(
33729
33951
  `${location.key}\0store-version-fence`,
33730
- () => log18.info(ACCOUNT_STORE_DEFERRED_MESSAGE, {
33952
+ () => log19.info(ACCOUNT_STORE_DEFERRED_MESSAGE, {
33731
33953
  configDir: location.configDir,
33732
33954
  blockers: gate.blockers
33733
33955
  })
@@ -33754,7 +33976,7 @@ async function storeArtefacts(anchor) {
33754
33976
  (name) => name === store || name.startsWith(`${pool}.store.`) || name.startsWith(pool) && name.endsWith(".tmp")
33755
33977
  ).length;
33756
33978
  }
33757
- async function abandonUnpublishedStore(location, stateAnchor, log18) {
33979
+ async function abandonUnpublishedStore(location, stateAnchor, log19) {
33758
33980
  const store = await loadCommonAuthStoreModules();
33759
33981
  const binding = await readAccountStoreBinding(stateAnchor, store, Date.now);
33760
33982
  if (binding.status === "bound") return false;
@@ -33765,7 +33987,7 @@ async function abandonUnpublishedStore(location, stateAnchor, log18) {
33765
33987
  });
33766
33988
  await unlink12(accountStorePointerPath(stateAnchor)).catch(() => {
33767
33989
  });
33768
- log18.info(
33990
+ log19.info(
33769
33991
  "antigravity-auth set an unfinished account store aside before starting its move again",
33770
33992
  { configDir: location.configDir, archived }
33771
33993
  );
@@ -33787,9 +34009,9 @@ async function runStoreMove(input2) {
33787
34009
  return { status: "pending", reason: outcome.reason };
33788
34010
  return { status: "cancelled" };
33789
34011
  }
33790
- async function moveStore(location, options, source, target, back, log18, forwarded) {
33791
- const keepConfig = () => recordAnchor(location, options, "config", log18);
33792
- if (!await storeFenceOpen(location, options, log18)) return keepConfig();
34012
+ async function moveStore(location, options, source, target, back, log19, forwarded) {
34013
+ const keepConfig = () => recordAnchor(location, options, "config", log19);
34014
+ if (!await storeFenceOpen(location, options, log19)) return keepConfig();
33793
34015
  try {
33794
34016
  const result = await (options.relocate ?? runStoreMove)({
33795
34017
  source,
@@ -33799,7 +34021,7 @@ async function moveStore(location, options, source, target, back, log18, forward
33799
34021
  if (result.status !== "completed") {
33800
34022
  logOnce(
33801
34023
  `${location.key}\0store-move-unfinished`,
33802
- () => log18.info(ACCOUNT_STORE_DEFERRED_MESSAGE, {
34024
+ () => log19.info(ACCOUNT_STORE_DEFERRED_MESSAGE, {
33803
34025
  configDir: location.configDir,
33804
34026
  reason: result.status === "pending" ? result.reason : result.status
33805
34027
  })
@@ -33807,14 +34029,14 @@ async function moveStore(location, options, source, target, back, log18, forward
33807
34029
  return forwarded ? "state-home" : keepConfig();
33808
34030
  }
33809
34031
  showLog(
33810
- log18,
34032
+ log19,
33811
34033
  "antigravity-auth moved the account store out of OpenCode's config folder",
33812
34034
  { from: source, to: target, generation: result.id }
33813
34035
  );
33814
34036
  } catch (error) {
33815
34037
  logOnce(
33816
34038
  `${location.key}\0store-move-failed`,
33817
- () => log18.warn(
34039
+ () => log19.warn(
33818
34040
  "antigravity-auth's account store stays in OpenCode's config folder: moving it failed; the move is tried again at the next start",
33819
34041
  {
33820
34042
  configDir: location.configDir,
@@ -33825,9 +34047,9 @@ async function moveStore(location, options, source, target, back, log18, forward
33825
34047
  );
33826
34048
  return forwarded ? "state-home" : keepConfig();
33827
34049
  }
33828
- return recordAnchor(location, options, "state-home", log18);
34050
+ return recordAnchor(location, options, "state-home", log19);
33829
34051
  }
33830
- async function resumeForwardedStore(location, options, configAnchor, stateAnchor, log18) {
34052
+ async function resumeForwardedStore(location, options, configAnchor, stateAnchor, log19) {
33831
34053
  const store = await loadCommonAuthStoreModules();
33832
34054
  const binding = await readAccountStoreBinding(stateAnchor, store, Date.now);
33833
34055
  if (binding.status === "bound") return;
@@ -33838,13 +34060,13 @@ async function resumeForwardedStore(location, options, configAnchor, stateAnchor
33838
34060
  configAnchor,
33839
34061
  stateAnchor,
33840
34062
  false,
33841
- log18,
34063
+ log19,
33842
34064
  true
33843
34065
  );
33844
34066
  } catch (error) {
33845
34067
  logOnce(
33846
34068
  `${location.key}\0store-resume-failed`,
33847
- () => log18.warn(
34069
+ () => log19.warn(
33848
34070
  "antigravity-auth's account store is still moving; it could not be finished at this start",
33849
34071
  {
33850
34072
  configDir: location.configDir,
@@ -33855,9 +34077,9 @@ async function resumeForwardedStore(location, options, configAnchor, stateAnchor
33855
34077
  );
33856
34078
  }
33857
34079
  }
33858
- async function initializeStore(location, options, stateAnchor, log18) {
33859
- const keepConfig = () => recordAnchor(location, options, "config", log18);
33860
- if (!await storeFenceOpen(location, options, log18)) return keepConfig();
34080
+ async function initializeStore(location, options, stateAnchor, log19) {
34081
+ const keepConfig = () => recordAnchor(location, options, "config", log19);
34082
+ if (!await storeFenceOpen(location, options, log19)) return keepConfig();
33861
34083
  try {
33862
34084
  const store = await loadCommonAuthStoreModules();
33863
34085
  const created = await initializeFreshAccountStore(store, {
@@ -33870,7 +34092,7 @@ async function initializeStore(location, options, stateAnchor, log18) {
33870
34092
  } catch (error) {
33871
34093
  logOnce(
33872
34094
  `${location.key}\0store-init-failed`,
33873
- () => log18.warn(
34095
+ () => log19.warn(
33874
34096
  "antigravity-auth's account store stays in OpenCode's config folder: creating it in its state folder failed; it is tried again at the next start",
33875
34097
  {
33876
34098
  configDir: location.configDir,
@@ -33882,13 +34104,13 @@ async function initializeStore(location, options, stateAnchor, log18) {
33882
34104
  return keepConfig();
33883
34105
  }
33884
34106
  showLog(
33885
- log18,
34107
+ log19,
33886
34108
  "antigravity-auth created its account store in its state folder",
33887
34109
  {
33888
34110
  accountStore: stateAnchor
33889
34111
  }
33890
34112
  );
33891
- return recordAnchor(location, options, "state-home", log18);
34113
+ return recordAnchor(location, options, "state-home", log19);
33892
34114
  }
33893
34115
  async function writeStateHomeStoreForward(id, stateAnchor, configAnchor = legacyAccountFile(runtimeLayoutLocation().configDir)) {
33894
34116
  const forward = {
@@ -33903,10 +34125,10 @@ async function writeStateHomeStoreForward(id, stateAnchor, configAnchor = legacy
33903
34125
  durability: "file-only-on-windows"
33904
34126
  });
33905
34127
  }
33906
- function logDeferral(location, blockers, log18) {
34128
+ function logDeferral(location, blockers, log19) {
33907
34129
  logOnce(
33908
34130
  `${location.key}\0deferred`,
33909
- () => log18.info(RUNTIME_LAYOUT_DEFERRED_MESSAGE, {
34131
+ () => log19.info(RUNTIME_LAYOUT_DEFERRED_MESSAGE, {
33910
34132
  configDir: location.configDir,
33911
34133
  blockers
33912
34134
  })
@@ -34064,13 +34286,13 @@ async function finishOldFiles(location, files, markerPath, marker, layoutLock, i
34064
34286
  if (done) await removeOldVaultFolder(files, layoutLock, input2.steps);
34065
34287
  }
34066
34288
  }
34067
- async function removeLeftoverManifest(location, layoutLock, steps, log18) {
34289
+ async function removeLeftoverManifest(location, layoutLock, steps, log19) {
34068
34290
  try {
34069
34291
  await removeManifestOwned(location.stateHomeDir, layoutLock, steps);
34070
34292
  } catch (error) {
34071
34293
  logOnce(
34072
34294
  `${location.key}\0manifest`,
34073
- () => log18.warn(
34295
+ () => log19.warn(
34074
34296
  `antigravity-auth could not remove ${RUNTIME_LAYOUT_MANIFEST_FILE} from its state folder; it tries again at the next start`,
34075
34297
  { stateDir: location.stateHomeDir, errorClass: errorClass(error) }
34076
34298
  )
@@ -34090,7 +34312,7 @@ async function removeOldVaultFolder(files, layoutLock, steps) {
34090
34312
  } catch {
34091
34313
  }
34092
34314
  }
34093
- async function removeOldSignatureCache(location, path5, layoutLock, steps, log18) {
34315
+ async function removeOldSignatureCache(location, path5, layoutLock, steps, log19) {
34094
34316
  try {
34095
34317
  if (!await exists3(path5)) return;
34096
34318
  await beforeRemove(path5, layoutLock, steps);
@@ -34099,7 +34321,7 @@ async function removeOldSignatureCache(location, path5, layoutLock, steps, log18
34099
34321
  if (error?.code === "ENOENT") return;
34100
34322
  logOnce(
34101
34323
  `${location.key}\0signature-cache`,
34102
- () => log18.warn(
34324
+ () => log19.warn(
34103
34325
  "antigravity-auth could not remove its old signature cache from OpenCode's config folder; it is no longer used and can be deleted",
34104
34326
  { path: path5, errorClass: errorClass(error) }
34105
34327
  )
@@ -34110,7 +34332,7 @@ async function beforeRemove(path5, layoutLock, steps) {
34110
34332
  await steps?.beforeRemove?.(path5);
34111
34333
  await layoutLock.assertOwned();
34112
34334
  }
34113
- async function takeDataLocks(files, log18) {
34335
+ async function takeDataLocks(files, log19) {
34114
34336
  const locks = [];
34115
34337
  try {
34116
34338
  if (await exists3(files.vault.old))
@@ -34120,7 +34342,7 @@ async function takeDataLocks(files, log18) {
34120
34342
  lock.name,
34121
34343
  join18(files.vault.old, lock.file),
34122
34344
  lock.waitMs,
34123
- log18
34345
+ log19
34124
34346
  )
34125
34347
  );
34126
34348
  return locks;
@@ -34317,8 +34539,8 @@ function isWindowsSharingError(error, platform) {
34317
34539
  }
34318
34540
  async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile15, unlink: unlink12 }) {
34319
34541
  const started = performance.now();
34320
- for (const delay4 of SHARING_RETRY_DELAYS_MS) {
34321
- if (delay4 > 0) await new Promise((done) => setTimeout(done, delay4));
34542
+ for (const delay5 of SHARING_RETRY_DELAYS_MS) {
34543
+ if (delay5 > 0) await new Promise((done) => setTimeout(done, delay5));
34322
34544
  let same;
34323
34545
  try {
34324
34546
  same = (await io.readFile(file.old)).equals(await io.readFile(file.next));
@@ -34471,7 +34693,7 @@ async function ensureOwnerOnlyDir(path5) {
34471
34693
  await mkdir15(path5, { recursive: true, mode: 448 });
34472
34694
  await chmod5(path5, 448);
34473
34695
  }
34474
- async function takeLock(name, path5, waitMs, log18) {
34696
+ async function takeLock(name, path5, waitMs, log19) {
34475
34697
  const fs7 = await loadCommonAuthFs();
34476
34698
  const started = performance.now();
34477
34699
  let announced = false;
@@ -34496,7 +34718,7 @@ async function takeLock(name, path5, waitMs, log18) {
34496
34718
  );
34497
34719
  if (!announced && waited >= LOCK_WAIT_NOTICE_MS) {
34498
34720
  announced = true;
34499
- log18.info(
34721
+ log19.info(
34500
34722
  `antigravity-auth is waiting up to ${Math.round(waitMs / 1e3)} s for the ${name} lock at ${path5}.${lockHolderText(name)}`,
34501
34723
  { lock: name, path: path5 }
34502
34724
  );
@@ -34792,7 +35014,7 @@ async function assertLegacyPoolInUse(legacyPath) {
34792
35014
  throw new LegacyAccountPoolRetiredError(legacyPath, { cause: error });
34793
35015
  }
34794
35016
  }
34795
- function refusalMessage2(admission) {
35017
+ function accountStoreAdmissionMessage(admission) {
34796
35018
  switch (admission.status) {
34797
35019
  case "busy":
34798
35020
  return new AccountStoreBusyError().message;
@@ -34827,7 +35049,7 @@ function unboundOpening(binding) {
34827
35049
  return {
34828
35050
  status: "refused",
34829
35051
  admission: binding,
34830
- message: refusalMessage2(binding)
35052
+ message: accountStoreAdmissionMessage(binding)
34831
35053
  };
34832
35054
  }
34833
35055
  async function openAccountStore(options) {
@@ -34869,7 +35091,7 @@ async function openAccountStore(options) {
34869
35091
  return {
34870
35092
  status: "refused",
34871
35093
  admission,
34872
- message: refusalMessage2(admission)
35094
+ message: accountStoreAdmissionMessage(admission)
34873
35095
  };
34874
35096
  }
34875
35097
  }
@@ -35873,19 +36095,19 @@ function initLogger3(client) {
35873
36095
  }
35874
36096
  function createLogger4(module) {
35875
36097
  let channel3;
35876
- const log18 = (level, message, extra) => {
36098
+ const log19 = (level, message, extra) => {
35877
36099
  channel3 ??= getLegacyLogger().createLogger(module);
35878
36100
  channel3[level](message, extra);
35879
36101
  };
35880
36102
  return {
35881
- debug: (message, extra) => log18("debug", message, extra),
35882
- info: (message, extra) => log18("info", message, extra),
36103
+ debug: (message, extra) => log19("debug", message, extra),
36104
+ info: (message, extra) => log19("info", message, extra),
35883
36105
  hostInfo: (message, extra) => {
35884
36106
  channel3 ??= getLegacyLogger().createLogger(module);
35885
36107
  channel3.hostInfo?.(message, extra);
35886
36108
  },
35887
- warn: (message, extra) => log18("warn", message, extra),
35888
- error: (message, extra) => log18("error", message, extra)
36109
+ warn: (message, extra) => log19("warn", message, extra),
36110
+ error: (message, extra) => log19("error", message, extra)
35889
36111
  };
35890
36112
  }
35891
36113
  var ENV_CONSOLE_LOG2, LOG_LEVEL_FROM_OPERATOR, legacyClient, legacyLogger;
@@ -35946,7 +36168,7 @@ async function prepareVaultFolder(options) {
35946
36168
  const kept = refusals.get(key2);
35947
36169
  if (kept)
35948
36170
  return override ? { ...override, refusal: kept } : refused(accountFile, kept);
35949
- const log18 = options.log ?? createLogger4("runtime-layout");
36171
+ const log19 = options.log ?? createLogger4("runtime-layout");
35950
36172
  const version = options.version ?? await pluginPackageVersion().catch(() => "unknown");
35951
36173
  try {
35952
36174
  if (override) {
@@ -35955,11 +36177,11 @@ async function prepareVaultFolder(options) {
35955
36177
  await prepareRuntimeLayout({
35956
36178
  version,
35957
36179
  accountFile,
35958
- log: log18,
36180
+ log: log19,
35959
36181
  ...options.layoutLockWaitMs === void 0 ? {} : { layoutLockWaitMs: options.layoutLockWaitMs }
35960
36182
  });
35961
36183
  if (options.accountStore !== false)
35962
- await prepareAccountStore({ version, log: log18 });
36184
+ await prepareAccountStore({ version, log: log19 });
35963
36185
  } catch (error) {
35964
36186
  const refusal3 = error instanceof RuntimeLayoutRefusal ? error : new RuntimeLayoutRefusal(
35965
36187
  override?.vaultDir ?? runtimeLayoutLocation().stateHomeDir,
@@ -35967,7 +36189,7 @@ async function prepareVaultFolder(options) {
35967
36189
  );
35968
36190
  if (!refusals.has(key2)) {
35969
36191
  refusals.set(key2, refusal3);
35970
- log18.warn(refusal3.message, {
36192
+ log19.warn(refusal3.message, {
35971
36193
  stateDir: refusal3.stateDir,
35972
36194
  errorClass: refusal3.errorClass
35973
36195
  });
@@ -40392,7 +40614,7 @@ function getUserConfigPath() {
40392
40614
  function getProjectConfigPath(directory) {
40393
40615
  return join22(directory, ".opencode", "antigravity.json");
40394
40616
  }
40395
- function loadConfigFile(path5, log18) {
40617
+ function loadConfigFile(path5, log19) {
40396
40618
  try {
40397
40619
  if (!fs4.existsSync(path5)) {
40398
40620
  return null;
@@ -40401,7 +40623,7 @@ function loadConfigFile(path5, log18) {
40401
40623
  const rawConfig = JSON.parse(content);
40402
40624
  const result = AntigravityConfigSchema.partial().safeParse(rawConfig);
40403
40625
  if (!result.success) {
40404
- log18.warn("Config validation error", {
40626
+ log19.warn("Config validation error", {
40405
40627
  path: path5,
40406
40628
  issues: result.error.issues.map((i) => `${i.path.join(".")}: ${i.message}`).join(", ")
40407
40629
  });
@@ -40410,9 +40632,9 @@ function loadConfigFile(path5, log18) {
40410
40632
  return result.data;
40411
40633
  } catch (error) {
40412
40634
  if (error instanceof SyntaxError) {
40413
- log18.warn("Invalid JSON in config file", { path: path5, error: error.message });
40635
+ log19.warn("Invalid JSON in config file", { path: path5, error: error.message });
40414
40636
  } else {
40415
- log18.warn("Failed to load config file", { path: path5, error: String(error) });
40637
+ log19.warn("Failed to load config file", { path: path5, error: String(error) });
40416
40638
  }
40417
40639
  return null;
40418
40640
  }
@@ -40431,15 +40653,15 @@ function mergeConfigs(base, override) {
40431
40653
  function loadConfig(directory) {
40432
40654
  return loadConfigWithLogger(directory, legacyLog);
40433
40655
  }
40434
- function loadConfigWithLogger(directory, log18) {
40656
+ function loadConfigWithLogger(directory, log19) {
40435
40657
  let config = structuredClone(DEFAULT_CONFIG);
40436
40658
  const userConfigPath = getUserConfigPath();
40437
- const userConfig = loadConfigFile(userConfigPath, log18);
40659
+ const userConfig = loadConfigFile(userConfigPath, log19);
40438
40660
  if (userConfig) {
40439
40661
  config = mergeConfigs(config, userConfig);
40440
40662
  }
40441
40663
  const projectConfigPath = getProjectConfigPath(directory);
40442
- const projectConfig = loadConfigFile(projectConfigPath, log18);
40664
+ const projectConfig = loadConfigFile(projectConfigPath, log19);
40443
40665
  if (projectConfig) {
40444
40666
  config = mergeConfigs(config, projectConfig);
40445
40667
  }
@@ -42562,14 +42784,14 @@ var BackgroundVaultQuotaRefresh = class {
42562
42784
  this.abortTick();
42563
42785
  await this.inFlight;
42564
42786
  }
42565
- schedule(delay4, intervalWait = null) {
42787
+ schedule(delay5, intervalWait = null) {
42566
42788
  if (this.disposed || !this.started) return;
42567
42789
  this.intervalWait = intervalWait;
42568
42790
  this.timer = setTimeout(() => {
42569
42791
  this.timer = null;
42570
42792
  this.intervalWait = null;
42571
42793
  void this.tick();
42572
- }, delay4);
42794
+ }, delay5);
42573
42795
  this.timer.unref?.();
42574
42796
  }
42575
42797
  /** One serialized tick; also used by deterministic composition tests. */
@@ -44854,8 +45076,8 @@ function createSessionRecoveryHook(ctx, config) {
44854
45076
  if (!sessionID) return false;
44855
45077
  let assistantMsgID = info.id;
44856
45078
  let msgs;
44857
- const log18 = createLogger4("session-recovery");
44858
- log18.debug("Recovery attempt started", {
45079
+ const log19 = createLogger4("session-recovery");
45080
+ log19.debug("Recovery attempt started", {
44859
45081
  errorType,
44860
45082
  sessionID,
44861
45083
  providedMsgID: assistantMsgID ?? "none"
@@ -44875,7 +45097,7 @@ function createSessionRecoveryHook(ctx, config) {
44875
45097
  const m = msgs[i];
44876
45098
  if (m && m.info?.role === "assistant" && m.info?.id) {
44877
45099
  assistantMsgID = m.info.id;
44878
- log18.debug("Found assistant message ID from session messages", {
45100
+ log19.debug("Found assistant message ID from session messages", {
44879
45101
  msgID: assistantMsgID,
44880
45102
  msgIndex: i
44881
45103
  });
@@ -44884,7 +45106,7 @@ function createSessionRecoveryHook(ctx, config) {
44884
45106
  }
44885
45107
  }
44886
45108
  if (!assistantMsgID) {
44887
- log18.debug("No assistant message ID found, cannot recover");
45109
+ log19.debug("No assistant message ID found, cannot recover");
44888
45110
  return false;
44889
45111
  }
44890
45112
  if (processingErrors.has(assistantMsgID)) return false;
@@ -44928,7 +45150,7 @@ function createSessionRecoveryHook(ctx, config) {
44928
45150
  }
44929
45151
  return success;
44930
45152
  } catch (err) {
44931
- log18.error("Recovery failed", { error: String(err) });
45153
+ log19.error("Recovery failed", { error: String(err) });
44932
45154
  return false;
44933
45155
  } finally {
44934
45156
  processingErrors.delete(assistantMsgID);
@@ -47827,9 +48049,9 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
47827
48049
  }
47828
48050
  const [, rawModel = "", rawAction = ""] = match;
47829
48051
  const requestedModel = rawModel;
47830
- const hydrogenTier = isGeminiHydrogenModel(rawModel) ? options?.variant?.thinkingLevel : void 0;
48052
+ const geminiTier = supportsGeminiXHigh(rawModel) ? options?.variant?.thinkingLevel : void 0;
47831
48053
  const resolved = resolveAntigravityModel(
47832
- hydrogenTier ? `${rawModel.replace(/-(low|medium|high|xhigh)$/i, "")}-${hydrogenTier}` : rawModel
48054
+ geminiTier ? `${rawModel.replace(/-(low|medium|high|xhigh)$/i, "")}-${geminiTier}` : rawModel
47833
48055
  );
47834
48056
  let effectiveModel = resolved.actualModel;
47835
48057
  const streaming = rawAction === STREAM_ACTION;
@@ -48000,9 +48222,9 @@ function prepareAntigravityRequestIn(wire, input2, init, accessToken, projectId,
48000
48222
  `[ThinkingResolution] rawModel=${rawModel} resolvedModel=${effectiveModel} resolvedTier=${tierThinkingLevel ?? "none"} variantLevel=${variantConfig?.thinkingLevel ?? "none"} variantBudget=${variantConfig?.thinkingBudget ?? "none"} providerOptions.google=${JSON.stringify(requestPayload.providerOptions?.google ?? null)} generationConfig.thinkingConfig=${JSON.stringify(rawGenerationConfig?.thinkingConfig ?? null)}`
48001
48223
  );
48002
48224
  delete requestPayload.providerOptions;
48003
- if (variantConfig?.thinkingLevel && (isGemini3 || isGeminiArgonModel(effectiveModel) || isGeminiCarbonModel(effectiveModel) || isGeminiHydrogenModel(effectiveModel) || getAgyNativeModel(effectiveModel)?.supportsAdaptiveThinking)) {
48225
+ if (variantConfig?.thinkingLevel && (isGemini3 || isGeminiArgonModel(effectiveModel) || isGeminiCarbonModel(effectiveModel) || supportsGeminiXHigh(effectiveModel) || getAgyNativeModel(effectiveModel)?.supportsAdaptiveThinking)) {
48004
48226
  const variantModelBase = rawModel.replace(/-preview-customtools$/i, "").replace(/-preview$/i, "").replace(
48005
- isGeminiHydrogenModel(effectiveModel) ? /-(low|medium|high|xhigh)$/i : /-(minimal|low|medium|high)$/i,
48227
+ supportsGeminiXHigh(effectiveModel) ? /-(low|medium|high|xhigh)$/i : /-(minimal|low|medium|high)$/i,
48006
48228
  ""
48007
48229
  );
48008
48230
  const variantResolved = resolveAntigravityModel(
@@ -48648,7 +48870,7 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
48648
48870
  statusText: scrubbedStatusText,
48649
48871
  headers: plainHeaders
48650
48872
  });
48651
- throw freshError;
48873
+ throw markUpstreamFailure(freshError);
48652
48874
  }
48653
48875
  noteGeminiDumpResponse(dumpContext, response);
48654
48876
  appendGeminiDumpResponseText(dumpContext, text2);
@@ -48985,7 +49207,7 @@ var AgySessionRegistry = class {
48985
49207
  };
48986
49208
 
48987
49209
  // src/plugin/shared/advisory-repository.ts
48988
- function createAdvisoryRepositoryOwner(repository, log18) {
49210
+ function createAdvisoryRepositoryOwner(repository, log19) {
48989
49211
  const methods = /* @__PURE__ */ new Map();
48990
49212
  const advisoryMethods = /* @__PURE__ */ new Set([
48991
49213
  "updateMetadata",
@@ -49031,7 +49253,7 @@ function createAdvisoryRepositoryOwner(repository, log18) {
49031
49253
  (reason) => !failures.has(reason)
49032
49254
  );
49033
49255
  for (const reason of absorbed) failures.delete(reason);
49034
- log18.debug("post-response-local-write-refused", {
49256
+ log19.debug("post-response-local-write-refused", {
49035
49257
  count: absorbed.length
49036
49258
  });
49037
49259
  if (remaining.length > 0)
@@ -49165,7 +49387,7 @@ async function retainResponseLifetime(response, cancellation) {
49165
49387
 
49166
49388
  // src/plugin/shared/request-services.ts
49167
49389
  init_dist();
49168
- import { createHash as createHash16, randomUUID as randomUUID20 } from "node:crypto";
49390
+ import { createHash as createHash17, randomUUID as randomUUID20 } from "node:crypto";
49169
49391
 
49170
49392
  // src/common-auth-embedded/claustrum/host.js
49171
49393
  import { ClaustrumCredentialError as ClaustrumCredentialError8 } from "@cortexkit/claustrum-client";
@@ -49265,6 +49487,9 @@ function hasVaultHost2() {
49265
49487
  return process.env.CORTEXKIT_VAULT_HOST === "thalamus";
49266
49488
  }
49267
49489
 
49490
+ // src/common-auth-embedded/routing-accessor/index.js
49491
+ import { createHash as createHash16 } from "node:crypto";
49492
+
49268
49493
  // src/common-auth-embedded/routing-accessor/handle.js
49269
49494
  function routingHandle(sessionId) {
49270
49495
  const routing = Reflect.get(globalThis, /* @__PURE__ */ Symbol.for("cortexkit.routing"));
@@ -49302,6 +49527,39 @@ function isObject2(value) {
49302
49527
  function isNonEmptyString(value) {
49303
49528
  return typeof value === "string" && value.length > 0;
49304
49529
  }
49530
+ function isBoundedControlFreeString(value, maxLength) {
49531
+ return isNonEmptyString(value) && value.length <= maxLength && !/\p{Cc}/u.test(value);
49532
+ }
49533
+ function isRoutingCode(value) {
49534
+ return typeof value === "string" && /^[a-z0-9._-]{1,64}$/.test(value);
49535
+ }
49536
+ function continueExhaustion(value) {
49537
+ if (!isObject2(value) || Array.isArray(value))
49538
+ return void 0;
49539
+ const { accountId, credentialId, limitWindow, observedAtMs } = value;
49540
+ if (!isBoundedControlFreeString(accountId, 256) || !isBoundedControlFreeString(credentialId, 256) || typeof observedAtMs !== "number" || !Number.isSafeInteger(observedAtMs) || observedAtMs <= 0 || limitWindow !== "five_hour" && limitWindow !== "seven_day" && limitWindow !== "signed_out")
49541
+ return void 0;
49542
+ const exhausted = {
49543
+ account: accountId,
49544
+ credential_id: credentialId,
49545
+ limit_window: limitWindow,
49546
+ observed_at_ms: observedAtMs
49547
+ };
49548
+ if (limitWindow === "signed_out") {
49549
+ if ("pool" in value || "resetsAtMs" in value || "retryAfterS" in value)
49550
+ return void 0;
49551
+ return exhausted;
49552
+ }
49553
+ const { pool, resetsAtMs, retryAfterS } = value;
49554
+ 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))
49555
+ return void 0;
49556
+ return {
49557
+ ...exhausted,
49558
+ ...pool !== void 0 ? { pool } : {},
49559
+ ...resetsAtMs !== void 0 ? { resets_at_ms: resetsAtMs } : {},
49560
+ ...retryAfterS !== void 0 ? { retry_after_s: Math.floor(retryAfterS) } : {}
49561
+ };
49562
+ }
49305
49563
  function billingCache(value) {
49306
49564
  if (!isObject2(value) || Array.isArray(value))
49307
49565
  return;
@@ -49349,6 +49607,22 @@ function billingUsage(value) {
49349
49607
  }
49350
49608
  return Object.keys(usage).length > 0 ? usage : void 0;
49351
49609
  }
49610
+ function candidateView(candidates) {
49611
+ const accounts = [];
49612
+ for (const { accountId, credentialId } of candidates) {
49613
+ if (isNonEmptyString(accountId) && isBoundedControlFreeString(credentialId, 256)) {
49614
+ accounts.push({ account_id: accountId, credential_id: credentialId });
49615
+ }
49616
+ }
49617
+ if (accounts.length === 0)
49618
+ return void 0;
49619
+ const lines = accounts.map(({ account_id, credential_id }) => Buffer.from(`${account_id} ${credential_id}
49620
+ `, "utf8")).sort(Buffer.compare);
49621
+ const hash2 = createHash16("sha256");
49622
+ for (const line of lines)
49623
+ hash2.update(line);
49624
+ return { view_digest: hash2.digest("hex"), accounts };
49625
+ }
49352
49626
  function selectionFor(answer, candidates) {
49353
49627
  if (!isObject2(answer))
49354
49628
  return void 0;
@@ -49377,10 +49651,11 @@ function refusalFor(value) {
49377
49651
  return void 0;
49378
49652
  }
49379
49653
  const refused2 = { code: code2 };
49380
- const routingCode = value.routing_code;
49381
- if (typeof routingCode === "string" && /^[a-z0-9._-]{1,64}$/.test(routingCode)) {
49654
+ const { routing_code: routingCode, reason } = value;
49655
+ if (isRoutingCode(routingCode))
49382
49656
  refused2.routingCode = routingCode;
49383
- }
49657
+ if (isRoutingCode(reason))
49658
+ refused2.reason = reason;
49384
49659
  const retryAfterSecs = value.retry_after_secs;
49385
49660
  if (typeof retryAfterSecs === "number" && Number.isFinite(retryAfterSecs) && retryAfterSecs >= 0) {
49386
49661
  refused2.retryAfterSecs = retryAfterSecs;
@@ -49394,6 +49669,21 @@ function refusalFor(value) {
49394
49669
  async function askRouting(input2) {
49395
49670
  let timer;
49396
49671
  try {
49672
+ const request2 = {
49673
+ provider: input2.provider,
49674
+ modelId: input2.modelId
49675
+ };
49676
+ if (input2.mode === "continue") {
49677
+ const { requestId } = input2;
49678
+ if (!isBoundedControlFreeString(requestId, 128))
49679
+ return void 0;
49680
+ const exhausted = continueExhaustion(input2.exhausted);
49681
+ if (!exhausted)
49682
+ return void 0;
49683
+ request2.mode = "continue";
49684
+ request2.request_id = requestId;
49685
+ request2.exhausted = exhausted;
49686
+ }
49397
49687
  const handle = routingHandle(input2.sessionId);
49398
49688
  if (!handle)
49399
49689
  return void 0;
@@ -49406,10 +49696,6 @@ async function askRouting(input2) {
49406
49696
  timer = setTimeout(() => resolve34(void 0), deadlineMs);
49407
49697
  timer.unref();
49408
49698
  });
49409
- const request2 = {
49410
- provider: input2.provider,
49411
- modelId: input2.modelId
49412
- };
49413
49699
  const cap = input2.holdWaitMaxS;
49414
49700
  if (typeof cap === "number" && Number.isFinite(cap)) {
49415
49701
  request2.hold_wait_max_s = Math.max(0, Math.floor(cap));
@@ -49417,9 +49703,12 @@ async function askRouting(input2) {
49417
49703
  if (input2.refusals === true)
49418
49704
  request2.refusals = true;
49419
49705
  const warmCredentialId = input2.warmCredentialId;
49420
- if (isNonEmptyString(warmCredentialId) && warmCredentialId.length <= 256 && !/\p{Cc}/u.test(warmCredentialId) && input2.candidates.some((candidate) => candidate.credentialId === warmCredentialId)) {
49706
+ if (isBoundedControlFreeString(warmCredentialId, 256) && input2.candidates.some((candidate) => candidate.credentialId === warmCredentialId)) {
49421
49707
  request2.warm_credential = warmCredentialId;
49422
49708
  }
49709
+ const candidates = candidateView(input2.candidates);
49710
+ if (candidates)
49711
+ request2.candidates = candidates;
49423
49712
  const pending = accountFor.call(handle, request2, { deadlineMs });
49424
49713
  if (!isObject2(pending) || typeof pending.then !== "function")
49425
49714
  return void 0;
@@ -49446,6 +49735,19 @@ function reportRouting(input2) {
49446
49735
  let payload;
49447
49736
  if ("kind" in input2) {
49448
49737
  switch (input2.kind) {
49738
+ case "transient_backoff": {
49739
+ const { accountId, credentialId, retryAtMs, providerCode } = input2;
49740
+ if (!isNonEmptyString(sessionId) || !isNonEmptyString(accountId) || !Number.isSafeInteger(retryAtMs) || retryAtMs <= 0 || credentialId !== void 0 && !isBoundedControlFreeString(credentialId, 256) || providerCode !== void 0 && !isBoundedControlFreeString(providerCode, 128))
49741
+ return;
49742
+ payload = {
49743
+ kind: "transient_backoff",
49744
+ account_id: accountId,
49745
+ ...credentialId !== void 0 ? { credential_id: credentialId } : {},
49746
+ retry_at_ms: retryAtMs,
49747
+ ...providerCode !== void 0 ? { provider_code: providerCode } : {}
49748
+ };
49749
+ break;
49750
+ }
49449
49751
  case "wait": {
49450
49752
  const { phase, waitId, reason, nextMs, attempt, message, outcome } = input2;
49451
49753
  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 +49843,7 @@ function reportRouting(input2) {
49541
49843
  const { window, pool } = input2;
49542
49844
  if (window !== "5h" && window !== "7d")
49543
49845
  return;
49544
- if (pool !== void 0 && (typeof pool !== "string" || !/^[a-z0-9._-]{1,64}$/.test(pool)))
49846
+ if (pool !== void 0 && !isRoutingCode(pool))
49545
49847
  return;
49546
49848
  payload = {
49547
49849
  ...identity4,
@@ -50149,20 +50451,26 @@ function routingExhaustionFields(scope) {
50149
50451
  };
50150
50452
  }
50151
50453
  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())
50454
+ const observedAtMs = input2.observedAt;
50455
+ const now2 = Date.now();
50456
+ if (!hasVaultRoutingAccessor() || input2.signal?.aborted || input2.status !== 429 || input2.reason !== "QUOTA_EXHAUSTED" || observedAtMs === void 0 || !Number.isFinite(observedAtMs) || observedAtMs <= 0 || observedAtMs > now2)
50153
50457
  return;
50458
+ let proof;
50154
50459
  for (const window of input2.quota?.windows ?? []) {
50155
50460
  if (window.remainingFraction !== 0) continue;
50156
50461
  const scope = routingQuotaScope(input2.group, window.window);
50157
50462
  const resetsAt = Date.parse(window.resetTime);
50158
- if (!scope || !Number.isFinite(resetsAt) || resetsAt <= Date.now()) continue;
50463
+ if (!scope || !Number.isFinite(resetsAt) || resetsAt <= now2) continue;
50159
50464
  report({
50160
50465
  ...input2.identity,
50161
50466
  outcome: "exhausted",
50162
50467
  ...routingExhaustionFields(scope),
50163
50468
  resetsAt
50164
50469
  });
50470
+ proof ??= { ...scope, observedAtMs, resetsAtMs: resetsAt };
50471
+ if (input2.singleReport) break;
50165
50472
  }
50473
+ return proof;
50166
50474
  }
50167
50475
  var RATE_LIMIT_HEADERS = [
50168
50476
  "retry-after",
@@ -50318,17 +50626,75 @@ var VAULT_ROUTING_PURPOSE_HEADER = "x-antigravity-internal-request-purpose";
50318
50626
  function createVaultRoutingHeaders(providerId) {
50319
50627
  return async (input2, output2) => {
50320
50628
  if (input2.model.providerID !== providerId) return;
50321
- output2.headers[VAULT_ROUTING_PURPOSE_HEADER] = input2.agent === "build" || input2.agent === "plan" ? "primary" : "auxiliary";
50629
+ output2.headers[VAULT_ROUTING_PURPOSE_HEADER] = input2.agent === "title" ? "title" : input2.agent === "build" || input2.agent === "plan" ? "primary" : "auxiliary";
50322
50630
  };
50323
50631
  }
50324
- function isPrimaryVaultRequest(kind, headers) {
50325
- return kind === void 0 ? new Headers(headers).get(VAULT_ROUTING_PURPOSE_HEADER) === "primary" : kind === "primary";
50632
+ function isTitleVaultRequest(kind, headers) {
50633
+ return kind === void 0 ? new Headers(headers).get(VAULT_ROUTING_PURPOSE_HEADER) === "title" : kind === "title";
50326
50634
  }
50327
50635
 
50328
50636
  // src/plugin/shared/request-services.ts
50329
50637
  var FIRST_RETRY_DELAY_MS = 1e3;
50330
50638
  var MODEL_UNAVAILABLE_TTL_MS = 60 * 60 * 1e3;
50331
50639
  var ROUTING_ASK_DEADLINE_MS = 2e3;
50640
+ var REFUSAL_BODY_TIMEOUT_MS = 2e3;
50641
+ var REFUSAL_BODY_MAX_BYTES = 64 * 1024;
50642
+ async function readRefusalBody(response, deadline) {
50643
+ const reader = response.body?.getReader();
50644
+ if (!reader) return { response, text: "" };
50645
+ const buffer = new Uint8Array(REFUSAL_BODY_MAX_BYTES);
50646
+ const stopAt = performance.now() + REFUSAL_BODY_TIMEOUT_MS;
50647
+ let size = 0;
50648
+ let finished = false;
50649
+ let timer;
50650
+ try {
50651
+ finished = await deadline.wait(
50652
+ () => Promise.race([
50653
+ (async () => {
50654
+ try {
50655
+ while (true) {
50656
+ const chunk = await reader.read();
50657
+ if (performance.now() >= stopAt) return false;
50658
+ if (chunk.done) return true;
50659
+ if (size + chunk.value.byteLength > buffer.byteLength)
50660
+ return false;
50661
+ buffer.set(chunk.value, size);
50662
+ size += chunk.value.byteLength;
50663
+ }
50664
+ } catch {
50665
+ return false;
50666
+ }
50667
+ })(),
50668
+ new Promise((resolve34) => {
50669
+ timer = setTimeout(() => resolve34(false), REFUSAL_BODY_TIMEOUT_MS);
50670
+ })
50671
+ ])
50672
+ );
50673
+ } finally {
50674
+ clearTimeout(timer);
50675
+ if (!finished) void reader.cancel().catch(() => {
50676
+ });
50677
+ reader.releaseLock();
50678
+ }
50679
+ const body = finished ? buffer.subarray(0, size) : null;
50680
+ const headers = new Headers(response.headers);
50681
+ if (!finished) {
50682
+ headers.delete("content-length");
50683
+ headers.delete("content-encoding");
50684
+ }
50685
+ return {
50686
+ response: preserveResponseMetadata2(
50687
+ new Response(body, {
50688
+ status: response.status,
50689
+ statusText: response.statusText,
50690
+ headers
50691
+ }),
50692
+ response
50693
+ ),
50694
+ text: body ? new TextDecoder().decode(body) : void 0
50695
+ };
50696
+ }
50697
+ var routingIdentityKey = ({ accountId, credentialId }) => JSON.stringify([accountId, credentialId]);
50332
50698
  function routingRefusalRetryAfterSeconds(refused2, now2) {
50333
50699
  const { retryAfterSecs, resetsAtMs } = refused2;
50334
50700
  if (typeof retryAfterSecs === "number" && Number.isFinite(retryAfterSecs) && retryAfterSecs > 0) {
@@ -50479,7 +50845,7 @@ async function withRoutingWaitReports(cancellation, run) {
50479
50845
  finish(cancellation.aborted ? "cancelled" : "abandoned");
50480
50846
  }
50481
50847
  }
50482
- function createLocalQuotaRefresh(accountManager, quotaManager, log18) {
50848
+ function createLocalQuotaRefresh(accountManager, quotaManager, log19) {
50483
50849
  return async function refreshQuotaAfterSuccess(account, intervalMinutes, signal) {
50484
50850
  if (intervalMinutes <= 0) return;
50485
50851
  const accountIndex = accountManager.getAccounts().indexOf(account);
@@ -50510,7 +50876,7 @@ function createLocalQuotaRefresh(accountManager, quotaManager, log18) {
50510
50876
  accountManager.requestSaveToDisk();
50511
50877
  }
50512
50878
  } catch (err) {
50513
- log18.debug(
50879
+ log19.debug(
50514
50880
  `quota-refresh-failed ${singleAccount ? quotaManager.hashedLogLabel("account", singleAccount) : `idx-${accountIndex}`}`,
50515
50881
  { error: String(err) }
50516
50882
  );
@@ -50529,7 +50895,7 @@ function createRequestExecutor(deps) {
50529
50895
  wire,
50530
50896
  debug,
50531
50897
  dump,
50532
- logger: log18,
50898
+ logger: log19,
50533
50899
  trackers,
50534
50900
  classifyAccessError,
50535
50901
  notify,
@@ -50562,7 +50928,7 @@ function createRequestExecutor(deps) {
50562
50928
  return JSON.stringify([
50563
50929
  "pool-file",
50564
50930
  account.email?.toLowerCase(),
50565
- createHash16("sha256").update(parseRefreshParts(refresh).refreshToken).digest("hex")
50931
+ createHash17("sha256").update(parseRefreshParts(refresh).refreshToken).digest("hex")
50566
50932
  ]);
50567
50933
  };
50568
50934
  const tierOf2 = (account) => JSON.stringify([account.capturedTierId, account.capturedPaidTierId]);
@@ -50580,7 +50946,7 @@ function createRequestExecutor(deps) {
50580
50946
  const entries = unavailableModels.get(key2);
50581
50947
  const entry = entries?.get(model);
50582
50948
  if (!entries || !entry) return;
50583
- log18.debug("model-unavailable-memory-drop", {
50949
+ log19.debug("model-unavailable-memory-drop", {
50584
50950
  account: entry.label,
50585
50951
  model,
50586
50952
  cause
@@ -50620,7 +50986,7 @@ function createRequestExecutor(deps) {
50620
50986
  ...entry,
50621
50987
  recordedAt: modelAvailabilityNow()
50622
50988
  });
50623
- log18.debug("model-unavailable-memory-record", {
50989
+ log19.debug("model-unavailable-memory-record", {
50624
50990
  account: entry.label,
50625
50991
  model
50626
50992
  });
@@ -50636,7 +51002,7 @@ function createRequestExecutor(deps) {
50636
51002
  const reportVault401 = (admission, status) => {
50637
51003
  if (!admission || status !== 401) return;
50638
51004
  void Promise.resolve().then(() => admission.report401(status)).catch((error) => {
50639
- log18.debug("send-admission-401-report-failed", { error: String(error) });
51005
+ log19.debug("send-admission-401-report-failed", { error: String(error) });
50640
51006
  });
50641
51007
  };
50642
51008
  const reportRouting2 = (sessionId, entry) => {
@@ -50644,7 +51010,7 @@ function createRequestExecutor(deps) {
50644
51010
  try {
50645
51011
  onRouting(sessionId, entry);
50646
51012
  } catch (error) {
50647
- log18.debug("routing-report-failed", { sessionId, error: String(error) });
51013
+ log19.debug("routing-report-failed", { sessionId, error: String(error) });
50648
51014
  }
50649
51015
  };
50650
51016
  async function execute(input2, init, options, selectedCredentials, selectedProjectIds, deadline, waitPolicy, waits) {
@@ -50721,17 +51087,16 @@ function createRequestExecutor(deps) {
50721
51087
  ...sendOptions,
50722
51088
  signal: deadline.signal
50723
51089
  };
50724
- if (!onSenderRejection) return sender(url, sendInit, optionsWithSignal);
50725
51090
  let pending;
50726
51091
  try {
50727
51092
  pending = sender(url, sendInit, optionsWithSignal);
50728
51093
  } catch (error) {
50729
- onSenderRejection(error);
50730
- throw error;
51094
+ onSenderRejection?.(error);
51095
+ throw markUpstreamFailure(error);
50731
51096
  }
50732
51097
  return pending.catch((error) => {
50733
- onSenderRejection(error);
50734
- throw error;
51098
+ onSenderRejection?.(error);
51099
+ throw markUpstreamFailure(error);
50735
51100
  });
50736
51101
  });
50737
51102
  const requestSessionIdentity = options.session ?? extractOpenCodeSessionIdentity(init?.headers);
@@ -50829,7 +51194,7 @@ function createRequestExecutor(deps) {
50829
51194
  const quietMode = config.quiet_mode;
50830
51195
  const toastScope = config.toast_scope;
50831
51196
  const showToast = async (message, variant2) => {
50832
- log18.debug("toast", {
51197
+ log19.debug("toast", {
50833
51198
  message,
50834
51199
  variant: variant2,
50835
51200
  isChildSession: isChildRequest,
@@ -50838,7 +51203,7 @@ function createRequestExecutor(deps) {
50838
51203
  if (quietMode) return;
50839
51204
  if (abortSignal?.aborted) return;
50840
51205
  if (toastScope === "root_only" && isChildRequest) {
50841
- log18.debug("toast-suppressed-child-session", {
51206
+ log19.debug("toast-suppressed-child-session", {
50842
51207
  message,
50843
51208
  variant: variant2,
50844
51209
  parentID: requestSessionIdentity.parentSessionId
@@ -50866,11 +51231,80 @@ function createRequestExecutor(deps) {
50866
51231
  let allAccountsBlockedAt;
50867
51232
  const modelUnavailableIndexes = /* @__PURE__ */ new Set();
50868
51233
  let routingPlacementConsidered = false;
51234
+ let routedCandidate;
51235
+ let continueRouting;
51236
+ const refusedRoutes = /* @__PURE__ */ new Map();
51237
+ let routingTitle = false;
51238
+ let routingWaitMs = 0;
51239
+ const failedRoutedPick = () => createNativeGoogleErrorResponse({
51240
+ status: 412,
51241
+ reason: "routing_refused"
51242
+ });
51243
+ const routingWaitRemainingMs = () => Math.min(
51244
+ deadline.remainingMs(),
51245
+ maxWaitMs > 0 ? Math.max(0, maxWaitMs - routingWaitMs) : Infinity
51246
+ );
51247
+ const routingRefusalResponse = (refused2) => {
51248
+ const { code: code2, routingCode, reason } = refused2;
51249
+ log19.warn("routing-refused", {
51250
+ code: code2,
51251
+ ...routingCode === void 0 ? {} : { routingCode },
51252
+ ...reason === void 0 ? {} : { reason }
51253
+ });
51254
+ const retryAfterSeconds = routingRefusalRetryAfterSeconds(
51255
+ refused2,
51256
+ Date.now()
51257
+ );
51258
+ return createNativeGoogleErrorResponse({
51259
+ status: 412,
51260
+ reason: "routing_refused",
51261
+ ...retryAfterSeconds === void 0 ? {} : { retryAfterSeconds }
51262
+ });
51263
+ };
51264
+ const waitOnRoutedAccount = async (ms, reason, attempt) => {
51265
+ if (ms >= deadline.remainingMs() || maxWaitMs > 0 && routingWaitMs + ms > maxWaitMs)
51266
+ return false;
51267
+ routingWaitMs += ms;
51268
+ if (ms > 0) await routingSleep(ms, reason, attempt);
51269
+ checkAborted();
51270
+ return true;
51271
+ };
51272
+ const unconfirmedRefusal = () => new Response(
51273
+ JSON.stringify({
51274
+ error: {
51275
+ code: 412,
51276
+ status: "FAILED_PRECONDITION",
51277
+ message: UNCONFIRMED_RATE_LIMIT_MESSAGE
51278
+ }
51279
+ }),
51280
+ { status: 412, headers: { "Content-Type": "application/json" } }
51281
+ );
51282
+ const retryAfterRoutedBackoff = async (identity4, retryAtMs, response) => {
51283
+ checkAborted();
51284
+ reportRouting({ ...identity4, kind: "transient_backoff", retryAtMs });
51285
+ void response.body?.cancel().catch(() => {
51286
+ });
51287
+ if (unconfirmedRetries >= MAX_UNCONFIRMED_RATE_LIMIT_RETRIES)
51288
+ return unconfirmedRefusal();
51289
+ unconfirmedRetries++;
51290
+ if (!await waitOnRoutedAccount(
51291
+ Math.max(0, retryAtMs - Date.now()),
51292
+ "rate_limited",
51293
+ unconfirmedRetries
51294
+ ))
51295
+ return unconfirmedRefusal();
51296
+ };
50869
51297
  while (true) {
50870
51298
  await assertAdmission();
50871
51299
  checkAborted();
51300
+ const choice = routedCandidate;
51301
+ routedCandidate = void 0;
51302
+ const exhausted = continueRouting;
51303
+ continueRouting = void 0;
51304
+ if (exhausted) refusedRoutes.set(routingIdentityKey(exhausted), exhausted);
50872
51305
  const accountCount = accountManager.getAccountCount();
50873
51306
  if (accountCount === 0) {
51307
+ if (choice) return failedRoutedPick();
50874
51308
  return createNoAccountResponse(
50875
51309
  "No Antigravity accounts available. Run `opencode auth login`.",
50876
51310
  model ?? "unknown"
@@ -50881,7 +51315,7 @@ function createRequestExecutor(deps) {
50881
51315
  config.quota_refresh_interval_minutes
50882
51316
  );
50883
51317
  const allowlistExcluded = modelAccessExcluded(model);
50884
- if (allowlistExcluded) {
51318
+ if (allowlistExcluded && !exhausted && !choice) {
50885
51319
  const serviceable = accountManager.getAccounts().filter(
50886
51320
  (entry) => entry.enabled !== false && !entry.accountIneligible && !entry.verificationRequired
50887
51321
  );
@@ -50889,7 +51323,7 @@ function createRequestExecutor(deps) {
50889
51323
  pushDebug(
50890
51324
  `model-access: all ${serviceable.length} serviceable account(s) excluded`
50891
51325
  );
50892
- log18.warn("model-access-all-excluded", {
51326
+ log19.warn("model-access-all-excluded", {
50893
51327
  family,
50894
51328
  model,
50895
51329
  accounts: serviceable.length
@@ -50902,9 +51336,38 @@ function createRequestExecutor(deps) {
50902
51336
  }
50903
51337
  }
50904
51338
  const permittedAccounts = allowlistExcluded ? accountManager.getAccounts().filter((entry) => !allowlistExcluded.has(entry.index)) : accountManager.getAccounts();
51339
+ const modelUnavailableForPass = () => /* @__PURE__ */ new Set([...modelUnavailableIndexes, ...rememberedIndexes(model)]);
51340
+ let routingUnavailableIndexes;
51341
+ const vaultCredentials = credentials.domain === "vault" ? credentials : void 0;
51342
+ const routingPresent = vaultCredentials !== void 0 && hasVaultRoutingAccessor();
51343
+ routingTitle ||= routingPresent && isTitleVaultRequest(kind, init?.headers);
51344
+ let account = null;
51345
+ if (routingPresent && accountSessionIdentity && vaultCredentials?.routingCandidate) {
51346
+ const candidateFor = vaultCredentials.routingCandidate;
51347
+ const row = choice ? accountManager.getAccounts().find((entry) => {
51348
+ const current = candidateFor(entry);
51349
+ return current.credentialId === choice.credentialId && current.accountId === choice.accountId;
51350
+ }) : !routingPlacementConsidered ? accountManager.getRoutedAccountForFamily(
51351
+ family,
51352
+ accountSessionIdentity
51353
+ ) : null;
51354
+ if (row && !allowlistExcluded?.has(row.index)) {
51355
+ routingUnavailableIndexes = modelUnavailableForPass();
51356
+ if (!routingUnavailableIndexes.has(row.index))
51357
+ account = accountManager.useRoutedAccount(
51358
+ row,
51359
+ family,
51360
+ model ?? void 0,
51361
+ accountSessionIdentity,
51362
+ !routingTitle
51363
+ );
51364
+ }
51365
+ }
51366
+ const routedPlacement = account !== null;
51367
+ if (choice && !routedPlacement) return failedRoutedPick();
50905
51368
  const operatorKillswitch = operatorSettings?.get().killswitch;
50906
51369
  const floorKeying = operatorSettings?.floorKeying?.();
50907
- const eligibleIndexes = operatorKillswitch?.enabled ? new Set(
51370
+ const eligibleIndexes = !routedPlacement && operatorKillswitch?.enabled ? new Set(
50908
51371
  permittedAccounts.filter((entry) => {
50909
51372
  const decision = evaluateKillswitchForAccount(
50910
51373
  entry,
@@ -50922,7 +51385,7 @@ function createRequestExecutor(deps) {
50922
51385
  return decision.allowed;
50923
51386
  }).map((entry) => entry.index)
50924
51387
  ) : null;
50925
- if (eligibleIndexes !== null && eligibleIndexes.size === 0 && permittedAccounts.length > 0) {
51388
+ if (!exhausted && eligibleIndexes !== null && eligibleIndexes.size === 0 && permittedAccounts.length > 0) {
50926
51389
  try {
50927
51390
  throwIfAllKilled({
50928
51391
  family,
@@ -50940,7 +51403,7 @@ function createRequestExecutor(deps) {
50940
51403
  });
50941
51404
  } catch (error) {
50942
51405
  if (error instanceof AntigravityKillswitchError) {
50943
- log18.warn("killswitch-all-excluded", {
51406
+ log19.warn("killswitch-all-excluded", {
50944
51407
  family,
50945
51408
  model,
50946
51409
  threshold: error.thresholdPercent,
@@ -50957,11 +51420,8 @@ function createRequestExecutor(deps) {
50957
51420
  const killedIndexes = eligibleIndexes === null ? void 0 : new Set(
50958
51421
  accountManager.getAccounts().map((entry) => entry.index).filter((index) => !eligibleIndexes.has(index))
50959
51422
  );
50960
- const unavailableIndexes = /* @__PURE__ */ new Set([
50961
- ...modelUnavailableIndexes,
50962
- ...rememberedIndexes(model)
50963
- ]);
50964
- if (unavailableIndexes.size > 0) {
51423
+ const unavailableIndexes = routingUnavailableIndexes ?? modelUnavailableForPass();
51424
+ if (!exhausted && !routedPlacement && unavailableIndexes.size > 0) {
50965
51425
  const candidates = accountManager.getAccounts().filter(
50966
51426
  (entry) => entry.enabled !== false && !entry.accountIneligible && !entry.verificationRequired && !allowlistExcluded?.has(entry.index) && (eligibleIndexes === null || eligibleIndexes.has(entry.index))
50967
51427
  );
@@ -50969,7 +51429,7 @@ function createRequestExecutor(deps) {
50969
51429
  pushDebug(
50970
51430
  `model-unavailable: all ${candidates.length} eligible account(s) skipped`
50971
51431
  );
50972
- log18.warn("model-unavailable-all-accounts", {
51432
+ log19.warn("model-unavailable-all-accounts", {
50973
51433
  family,
50974
51434
  model,
50975
51435
  accounts: candidates.length
@@ -50985,12 +51445,20 @@ function createRequestExecutor(deps) {
50985
51445
  ...unavailableIndexes,
50986
51446
  ...allowlistExcluded ?? []
50987
51447
  ]);
50988
- const routingPresent = credentials.domain === "vault" && hasVaultRoutingAccessor();
50989
- const firstPlacement = routingPresent && !routingPlacementConsidered && accountSessionIdentity && !accountManager.getCurrentAccountForFamily(
51448
+ const firstPlacement = routingPresent && !routedPlacement && !routingPlacementConsidered && accountSessionIdentity && !accountManager.getCurrentAccountForFamily(
50990
51449
  family,
50991
51450
  accountSessionIdentity
50992
51451
  );
50993
- let account = accountManager.getCurrentOrNextForFamily(
51452
+ const isHardEligible = (row) => row.enabled !== false && !row.accountIneligible && !row.verificationRequired && !allowlistExcluded?.has(row.index) && !unavailableIndexes.has(row.index);
51453
+ const isRoutingCandidate = (row) => isHardEligible(row) && !killedIndexes?.has(row.index) && !accountManager.isAccountOverSoftQuota(
51454
+ row,
51455
+ family,
51456
+ config.soft_quota_threshold_percent,
51457
+ softQuotaCacheTtlMs,
51458
+ model,
51459
+ excludedIndexes
51460
+ );
51461
+ const selectLocally = () => accountManager.getCurrentOrNextForFamily(
50994
51462
  family,
50995
51463
  model,
50996
51464
  config.account_selection_strategy,
@@ -50998,73 +51466,77 @@ function createRequestExecutor(deps) {
50998
51466
  config.soft_quota_threshold_percent,
50999
51467
  softQuotaCacheTtlMs,
51000
51468
  accountSessionIdentity,
51001
- excludedIndexes
51469
+ excludedIndexes,
51470
+ !routingTitle
51002
51471
  );
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
- })
51472
+ if (!exhausted) account ??= selectLocally();
51473
+ if (account) routingPlacementConsidered = true;
51474
+ if ((firstPlacement || exhausted) && routingPresent && accountSessionIdentity && vaultCredentials?.routingCandidate && model) {
51475
+ const roster = accountManager.getAccounts();
51476
+ const currentKey = exhausted && routingIdentityKey(exhausted);
51477
+ const holdCandidate = exhausted?.limitWindow !== "signed_out" && currentKey;
51478
+ const candidates = roster.flatMap((row) => {
51479
+ const eligible = isRoutingCandidate(row);
51480
+ if (!eligible && (!holdCandidate || !isHardEligible(row))) return [];
51481
+ const candidate = { ...vaultCredentials.routingCandidate(row) };
51482
+ const key2 = routingIdentityKey(candidate);
51483
+ if (key2 === holdCandidate && isHardEligible(row)) return [candidate];
51484
+ const refusal3 = refusedRoutes.get(key2);
51485
+ if (refusal3 && (refusal3.limitWindow === "signed_out" || (refusal3.resetsAtMs ?? Infinity) > Date.now()))
51486
+ return [];
51487
+ return eligible ? [candidate] : [];
51488
+ });
51489
+ if (candidates.length > 0 || exhausted) {
51490
+ routingPlacementConsidered = true;
51491
+ const canHold = !!holdCandidate && candidates.some(
51492
+ (candidate) => routingIdentityKey(candidate) === holdCandidate
51493
+ );
51494
+ const answer = await deadline.wait(() => {
51495
+ const input3 = {
51496
+ sessionId: accountSessionIdentity.id,
51497
+ provider: "antigravity",
51498
+ modelId: model,
51499
+ candidates,
51500
+ deadlineMs: Math.min(
51501
+ ROUTING_ASK_DEADLINE_MS,
51502
+ deadline.remainingMs()
51503
+ ),
51504
+ refusals: true
51505
+ };
51506
+ return askRouting(
51507
+ exhausted ? {
51508
+ ...input3,
51509
+ mode: "continue",
51510
+ requestId: randomUUID20(),
51511
+ exhausted,
51512
+ holdWaitMaxS: canHold ? Math.floor(routingWaitRemainingMs() / 1e3) : 0
51513
+ } : input3
51032
51514
  );
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
- );
51515
+ });
51516
+ checkAborted();
51517
+ if (answer && "refused" in answer)
51518
+ return routingRefusalResponse(answer.refused);
51519
+ if (exhausted && answer?.hold) {
51520
+ if (!canHold || routingIdentityKey(answer.candidate) !== holdCandidate)
51521
+ return failedRoutedPick();
51522
+ const delay5 = answer.hold.retry_after_ms;
51523
+ if (!await waitOnRoutedAccount(delay5, "account_limit"))
51044
51524
  return createNativeGoogleErrorResponse({
51045
51525
  status: 412,
51046
- reason: "routing_refused",
51047
- ...retryAfterSeconds === void 0 ? {} : { retryAfterSeconds }
51526
+ reason: "pool_unavailable",
51527
+ resetAfterMs: delay5
51048
51528
  });
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
- }
51529
+ } else if (answer && exhausted && routingIdentityKey(answer.candidate) === holdCandidate) {
51530
+ return failedRoutedPick();
51531
+ }
51532
+ const currentRoster = accountManager.getAccounts();
51533
+ if (answer || exhausted || currentRoster.length !== roster.length || currentRoster.some((row, index) => row !== roster[index])) {
51534
+ routedCandidate = answer?.candidate;
51535
+ continue;
51065
51536
  }
51066
51537
  }
51067
51538
  }
51539
+ if (exhausted) account ??= selectLocally();
51068
51540
  if (account && allowlistExcluded?.has(account.index)) {
51069
51541
  pushDebug(`model-access-excluded idx=${account.index}`);
51070
51542
  account = null;
@@ -51224,7 +51696,8 @@ function createRequestExecutor(deps) {
51224
51696
  );
51225
51697
  }
51226
51698
  previousAccountIndex = account.index;
51227
- accountManager.recordSessionUsage(account.index, accountSessionIdentity);
51699
+ if (!routingTitle)
51700
+ accountManager.recordSessionUsage(account.index, accountSessionIdentity);
51228
51701
  if (debug.isDebugEnabled()) {
51229
51702
  debug.logAccountContext("Selected", {
51230
51703
  index: account.index,
@@ -51279,7 +51752,7 @@ function createRequestExecutor(deps) {
51279
51752
  await deadline.wait(() => credentials.saveToDisk());
51280
51753
  } catch (error) {
51281
51754
  checkAborted();
51282
- log18.error("Failed to persist project context", {
51755
+ log19.error("Failed to persist project context", {
51283
51756
  error: String(error)
51284
51757
  });
51285
51758
  }
@@ -51336,7 +51809,7 @@ function createRequestExecutor(deps) {
51336
51809
  await deadline.wait(() => credentials.saveToDisk());
51337
51810
  } catch (error) {
51338
51811
  checkAborted();
51339
- log18.error("Failed to persist refreshed auth", {
51812
+ log19.error("Failed to persist refreshed auth", {
51340
51813
  error: String(error)
51341
51814
  });
51342
51815
  }
@@ -51345,14 +51818,14 @@ function createRequestExecutor(deps) {
51345
51818
  if (credentials.isInvalidGrant(error)) {
51346
51819
  const removed = credentials.removeAccount(account);
51347
51820
  if (removed) {
51348
- log18.warn(
51821
+ log19.warn(
51349
51822
  "Removed revoked account from pool - reauthenticate via `opencode auth login`"
51350
51823
  );
51351
51824
  try {
51352
51825
  await deadline.wait(() => credentials.saveToDiskReplace());
51353
51826
  } catch (persistError) {
51354
51827
  checkAborted();
51355
- log18.error("Failed to persist revoked account removal", {
51828
+ log19.error("Failed to persist revoked account removal", {
51356
51829
  error: String(persistError)
51357
51830
  });
51358
51831
  }
@@ -51362,7 +51835,7 @@ function createRequestExecutor(deps) {
51362
51835
  await deadline.wait(() => credentials.clearStoredAuth());
51363
51836
  } catch (storeError) {
51364
51837
  checkAborted();
51365
- log18.error(
51838
+ log19.error(
51366
51839
  "Failed to clear stored Antigravity OAuth credentials",
51367
51840
  {
51368
51841
  error: String(storeError)
@@ -51428,11 +51901,12 @@ function createRequestExecutor(deps) {
51428
51901
  }
51429
51902
  }
51430
51903
  const selected = account;
51904
+ const expectedRoutedCredential = routedPlacement ? choice ?? vaultCredentials?.routingCandidate?.(selected) : void 0;
51431
51905
  const sendPhysical = async (url, sendInit, admission, sendModel, requestKind, onMainTransportFailure) => {
51432
51906
  const source = credentials.domain === "local" ? "local" : hasVaultHost2() ? "hosted" : "vault";
51433
51907
  const message = `request-send source=${source} model=${sendModel} account=Account ${account.index + 1}`;
51434
- if (source === "local") log18.info(message);
51435
- else (log18.hostInfo ?? log18.info)(message);
51908
+ if (source === "local") log19.info(message);
51909
+ else (log19.hostInfo ?? log19.info)(message);
51436
51910
  const attempt = ++physicalSendCount;
51437
51911
  const sessionId = requestSessionIdentity.sessionId;
51438
51912
  const billing = admission && sessionId && hasVaultRoutingAccessor() ? new VaultBillingAttempt(
@@ -51616,7 +52090,7 @@ function createRequestExecutor(deps) {
51616
52090
  `fingerprint: deviceId=${account.fingerprint.deviceId.slice(0, 8)}...`
51617
52091
  );
51618
52092
  }
51619
- if (accountManager.isRateLimited(account, family, model)) {
52093
+ if (!routedPlacement && accountManager.isRateLimited(account, family, model)) {
51620
52094
  shouldSwitchAccount = true;
51621
52095
  }
51622
52096
  let totalCapacityRetries = 0;
@@ -51641,12 +52115,17 @@ function createRequestExecutor(deps) {
51641
52115
  let sendAccessToken;
51642
52116
  let sendProjectId;
51643
52117
  if (credentials.domain === "vault") {
51644
- sendAdmission = rotatedAdmission ?? await deadline.wait(
51645
- () => credentials.admit({
51646
- account,
51647
- signal: abortSignal
51648
- })
51649
- );
52118
+ try {
52119
+ sendAdmission = rotatedAdmission ?? await deadline.wait(
52120
+ () => credentials.admit({ account, signal: abortSignal })
52121
+ );
52122
+ } catch (error) {
52123
+ checkAborted();
52124
+ if (routedPlacement) return failedRoutedPick();
52125
+ throw error;
52126
+ }
52127
+ if (expectedRoutedCredential && (sendAdmission.credentialId !== expectedRoutedCredential.credentialId || sendAdmission.accountIdentity !== expectedRoutedCredential.accountId))
52128
+ return failedRoutedPick();
51650
52129
  rotatedAdmission = void 0;
51651
52130
  sendAccessToken = sendAdmission.accessToken;
51652
52131
  sendProjectId = sendAdmission.projectId;
@@ -51747,7 +52226,7 @@ function createRequestExecutor(deps) {
51747
52226
  `dispatching request via ${prepared.headerStyle} transport`
51748
52227
  );
51749
52228
  physicalAttemptStarted = true;
51750
- const response = await sendPhysical(
52229
+ let response = await sendPhysical(
51751
52230
  toUrlString(prepared.request),
51752
52231
  prepared.init,
51753
52232
  sendAdmission,
@@ -51755,6 +52234,12 @@ function createRequestExecutor(deps) {
51755
52234
  kind ?? "primary",
51756
52235
  retainMainTransportFailure
51757
52236
  );
52237
+ const receivedAtMs = Date.now();
52238
+ let boundedRefusal;
52239
+ if (routingPresent && (response.status === 429 || response.status === 403 || response.status === 404)) {
52240
+ boundedRefusal = await readRefusalBody(response, deadline);
52241
+ response = boundedRefusal.response;
52242
+ }
51758
52243
  if (response.ok) deadline.acceptHeaders();
51759
52244
  apiRequestCount++;
51760
52245
  accountManager.recordRequest(account.index, family);
@@ -51800,12 +52285,19 @@ function createRequestExecutor(deps) {
51800
52285
  );
51801
52286
  } catch (error) {
51802
52287
  checkAborted();
51803
- log18.debug("send-admission-401-report-failed", {
52288
+ log19.debug("send-admission-401-report-failed", {
51804
52289
  error: String(error)
51805
52290
  });
51806
52291
  }
51807
52292
  }
51808
52293
  const sessionKey = requestSessionIdentity.sessionId;
52294
+ const unreadableLimit = response.status === 429 && boundedRefusal !== void 0 && boundedRefusal.text === void 0;
52295
+ const routingIdentity = (routedPlacement || unreadableLimit) && sendAdmission && sessionKey && hasVaultRoutingAccessor() ? {
52296
+ sessionId: sessionKey,
52297
+ accountId: sendAdmission.accountIdentity,
52298
+ credentialId: sendAdmission.credentialId
52299
+ } : void 0;
52300
+ const routedIdentity = routedPlacement ? routingIdentity : void 0;
51809
52301
  if (sessionKey) {
51810
52302
  const routingEntry = {
51811
52303
  accountId: `acct-${account.index}`,
@@ -51825,9 +52317,7 @@ function createRequestExecutor(deps) {
51825
52317
  const _maxBackoffMs = (config.max_backoff_seconds ?? 60) * 1e3;
51826
52318
  const bodyInfo = await (async () => {
51827
52319
  try {
51828
- const text2 = await deadline.wait(
51829
- () => response.clone().text()
51830
- );
52320
+ const text2 = boundedRefusal ? boundedRefusal.text ?? "" : await deadline.wait(() => response.clone().text());
51831
52321
  try {
51832
52322
  return JSON.parse(text2);
51833
52323
  } catch {
@@ -51849,28 +52339,45 @@ function createRequestExecutor(deps) {
51849
52339
  reasonInfo.message,
51850
52340
  response.status
51851
52341
  );
52342
+ const retryAtMs = Math.min(
52343
+ Number.MAX_SAFE_INTEGER,
52344
+ // Use the short unconfirmed cooldown when the response doesn't
52345
+ // contain a retry time recognized by the executor.
52346
+ receivedAtMs + (reasonInfo.retryDelayMs ?? unconfirmedRateLimitDelayMs(
52347
+ response.headers.get("retry-after"),
52348
+ receivedAtMs
52349
+ ))
52350
+ );
52351
+ const routed429 = response.status === 429 ? routedIdentity : void 0;
51852
52352
  if (response.status === 429 && rateLimitReason === "UNKNOWN") {
51853
52353
  await logResponseBody2(debugContext, response, 429);
51854
52354
  const outgoing = JSON.parse(String(prepared.init.body));
51855
52355
  const recognised = systemInstructionHasHarnessIdentity(
51856
52356
  outgoing.request?.systemInstruction
51857
52357
  );
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
- );
52358
+ if (recognised) {
52359
+ void response.body?.cancel().catch(() => {
52360
+ });
52361
+ return unconfirmedRefusal();
52362
+ }
52363
+ if (routed429) {
52364
+ const refusal3 = await retryAfterRoutedBackoff(
52365
+ routed429,
52366
+ retryAtMs,
52367
+ response
52368
+ );
52369
+ if (refusal3) return refusal3;
52370
+ i -= 1;
52371
+ continue;
52372
+ }
52373
+ if (routingIdentity)
52374
+ reportRouting({
52375
+ ...routingIdentity,
52376
+ kind: "transient_backoff",
52377
+ retryAtMs
52378
+ });
51871
52379
  void response.body?.cancel().catch(() => {
51872
52380
  });
51873
- if (recognised) return terminal();
51874
52381
  const delayMs = unconfirmedRateLimitDelayMs(
51875
52382
  response.headers.get("retry-after")
51876
52383
  );
@@ -51905,7 +52412,7 @@ function createRequestExecutor(deps) {
51905
52412
  break;
51906
52413
  }
51907
52414
  if (unconfirmedRetries >= MAX_UNCONFIRMED_RATE_LIMIT_RETRIES)
51908
- return terminal();
52415
+ return unconfirmedRefusal();
51909
52416
  unconfirmedRetries++;
51910
52417
  const ready = accountManager.getAccounts().some((entry) => {
51911
52418
  const resets2 = entry.rateLimitResetTimes;
@@ -51925,13 +52432,14 @@ function createRequestExecutor(deps) {
51925
52432
  i -= 1;
51926
52433
  continue;
51927
52434
  }
52435
+ let exhaustion;
51928
52436
  if (credentials.domain === "vault" && sendAdmission && sessionKey && hasVaultRoutingAccessor()) {
51929
52437
  const group = resolveQuotaGroup(
51930
52438
  family,
51931
52439
  model,
51932
52440
  account.cachedQuota
51933
52441
  );
51934
- reportVaultExhaustion({
52442
+ exhaustion = reportVaultExhaustion({
51935
52443
  identity: {
51936
52444
  sessionId: sessionKey,
51937
52445
  accountId: sendAdmission.accountIdentity,
@@ -51942,12 +52450,33 @@ function createRequestExecutor(deps) {
51942
52450
  group,
51943
52451
  quota: account.cachedQuota?.[group],
51944
52452
  observedAt: account.cachedQuotaUpdatedAt,
51945
- signal: abortSignal
52453
+ signal: abortSignal,
52454
+ singleReport: !!routed429
51946
52455
  });
51947
52456
  }
52457
+ if (routed429 && rateLimitReason === "QUOTA_EXHAUSTED" && !exhaustion) {
52458
+ const refusal3 = await retryAfterRoutedBackoff(
52459
+ routed429,
52460
+ retryAtMs,
52461
+ response
52462
+ );
52463
+ if (refusal3) return refusal3;
52464
+ i -= 1;
52465
+ continue;
52466
+ }
51948
52467
  if (rateLimitReason === "MODEL_CAPACITY_EXHAUSTED" || rateLimitReason === "SERVER_ERROR") {
51949
52468
  totalCapacityRetries++;
51950
52469
  if (isCapacityRetryBudgetExhausted(totalCapacityRetries)) {
52470
+ if (routed429) {
52471
+ const refusal3 = await retryAfterRoutedBackoff(
52472
+ routed429,
52473
+ retryAtMs,
52474
+ response
52475
+ );
52476
+ if (refusal3) return refusal3;
52477
+ i -= 1;
52478
+ continue;
52479
+ }
51951
52480
  pushDebug(
51952
52481
  `Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted, switching account`
51953
52482
  );
@@ -52062,6 +52591,16 @@ function createRequestExecutor(deps) {
52062
52591
  serverRetryMs,
52063
52592
  config.failure_ttl_seconds * 1e3
52064
52593
  );
52594
+ if (routed429) {
52595
+ const refusal3 = await retryAfterRoutedBackoff(
52596
+ routed429,
52597
+ retryAtMs,
52598
+ response
52599
+ );
52600
+ if (refusal3) return refusal3;
52601
+ i -= 1;
52602
+ continue;
52603
+ }
52065
52604
  shouldSwitchAccount = true;
52066
52605
  break;
52067
52606
  }
@@ -52077,6 +52616,16 @@ function createRequestExecutor(deps) {
52077
52616
  config.failure_ttl_seconds * 1e3
52078
52617
  );
52079
52618
  accountManager.requestSaveToDisk();
52619
+ if (routed429 && !exhaustion) {
52620
+ const refusal3 = await retryAfterRoutedBackoff(
52621
+ routed429,
52622
+ retryAtMs,
52623
+ response
52624
+ );
52625
+ if (refusal3) return refusal3;
52626
+ i -= 1;
52627
+ continue;
52628
+ }
52080
52629
  const switchAccountDelayMs = config.switch_account_delay_ms ?? 500;
52081
52630
  if (accountCount > 1) {
52082
52631
  const quotaMsg = reasonInfo.quotaResetTime ? ` (quota resets ${reasonInfo.quotaResetTime})` : ``;
@@ -52102,11 +52651,15 @@ function createRequestExecutor(deps) {
52102
52651
  );
52103
52652
  }
52104
52653
  retainHttpFailure(response);
52654
+ if (routed429 && exhaustion) {
52655
+ const { accountId, credentialId } = routed429;
52656
+ continueRouting = { accountId, credentialId, ...exhaustion };
52657
+ }
52105
52658
  shouldSwitchAccount = true;
52106
52659
  break;
52107
52660
  }
52108
52661
  if (response.status === 404 && currentEndpoint === ANTIGRAVITY_ENDPOINT_DAILY) {
52109
- const notFoundBody = await deadline.wait(
52662
+ const notFoundBody = boundedRefusal ? boundedRefusal.text ?? "" : await deadline.wait(
52110
52663
  () => response.clone().text().catch(() => "")
52111
52664
  );
52112
52665
  const unavailable2 = parseModelUnavailableError(notFoundBody);
@@ -52121,7 +52674,7 @@ function createRequestExecutor(deps) {
52121
52674
  debug.logAntigravityDebugResponse(debugContext, response, {
52122
52675
  note
52123
52676
  });
52124
- log18.info("model-unavailable", {
52677
+ log19.info("model-unavailable", {
52125
52678
  accountIndex: account.index,
52126
52679
  family,
52127
52680
  model,
@@ -52141,11 +52694,20 @@ function createRequestExecutor(deps) {
52141
52694
  retryState.resetRateLimitState(account.index, quotaKey);
52142
52695
  retryState.resetAccountFailureState(account.index);
52143
52696
  if (response.status === 403) {
52144
- const errorBodyText = await deadline.wait(
52697
+ const errorBodyText = boundedRefusal ? boundedRefusal.text : await deadline.wait(
52145
52698
  () => response.clone().text().catch(() => "")
52146
52699
  );
52147
- const extracted = classifyAccessError(errorBodyText);
52148
- if (extracted.accountIneligible) {
52700
+ const extracted = errorBodyText === void 0 ? void 0 : classifyAccessError(errorBodyText);
52701
+ if (routedIdentity && (extracted?.accountIneligible || extracted?.validationRequired)) {
52702
+ const { accountId, credentialId } = routedIdentity;
52703
+ continueRouting = {
52704
+ accountId,
52705
+ credentialId,
52706
+ limitWindow: "signed_out",
52707
+ observedAtMs: receivedAtMs
52708
+ };
52709
+ }
52710
+ if (extracted?.accountIneligible) {
52149
52711
  const ineligibleReason = extracted.message ?? "Google marked this account as ineligible for Antigravity.";
52150
52712
  accountManager.markAccountIneligible(
52151
52713
  account.index,
@@ -52167,7 +52729,7 @@ function createRequestExecutor(deps) {
52167
52729
  shouldSwitchAccount = true;
52168
52730
  break;
52169
52731
  }
52170
- if (extracted.validationRequired) {
52732
+ if (extracted?.validationRequired) {
52171
52733
  const verificationReason = extracted.message ?? "Google requires account verification.";
52172
52734
  const cooldownMs = 10 * 60 * 1e3;
52173
52735
  accountManager.markAccountVerificationRequired(
@@ -52215,7 +52777,7 @@ function createRequestExecutor(deps) {
52215
52777
  if (!advisoryClosing)
52216
52778
  accountManager.markAccountUsed(account.index);
52217
52779
  const proactiveThreshold = config.proactive_rotation_threshold_percent ?? 20;
52218
- if (!advisoryClosing && proactiveThreshold > 0 && accountManager.shouldProactivelyRotate(
52780
+ if (!advisoryClosing && !routingPresent && proactiveThreshold > 0 && accountManager.shouldProactivelyRotate(
52219
52781
  family,
52220
52782
  model,
52221
52783
  proactiveThreshold,
@@ -52254,7 +52816,11 @@ function createRequestExecutor(deps) {
52254
52816
  await logResponseBody2(debugContext, response, response.status);
52255
52817
  if (response.status === 400) {
52256
52818
  const cloned = response.clone();
52257
- const bodyText = await deadline.wait(() => cloned.text());
52819
+ const bodyText = await deadline.wait(
52820
+ () => cloned.text().catch((error) => {
52821
+ throw markUpstreamFailure(error);
52822
+ })
52823
+ );
52258
52824
  if (bodyText.includes("Prompt is too long") || bodyText.includes("prompt_too_long")) {
52259
52825
  await showToast(
52260
52826
  "Context too long - use /compact to reduce size",
@@ -52269,7 +52835,11 @@ function createRequestExecutor(deps) {
52269
52835
  const maxAttempts = config.empty_response_max_attempts ?? 4;
52270
52836
  const retryDelayMs = config.empty_response_retry_delay_ms ?? 2e3;
52271
52837
  const clonedForCheck = response.clone();
52272
- const bodyText = await deadline.wait(() => clonedForCheck.text());
52838
+ const bodyText = await deadline.wait(
52839
+ () => clonedForCheck.text().catch((error) => {
52840
+ throw markUpstreamFailure(error);
52841
+ })
52842
+ );
52273
52843
  if (isEmptyResponseBody(bodyText)) {
52274
52844
  const emptyAttemptKey = `${prepared.sessionId ?? "none"}:${prepared.effectiveModel ?? "unknown"}`;
52275
52845
  const currentAttempts = retryState.recordEmptyResponseAttempt(emptyAttemptKey);
@@ -52428,7 +52998,7 @@ function createRequestExecutor(deps) {
52428
52998
  const originalError = recoveryError.originalError || {
52429
52999
  error: { message: "Thinking recovery triggered" }
52430
53000
  };
52431
- log18.debug("thinking-recovery-failed", { error: originalError });
53001
+ log19.debug("thinking-recovery-failed", { error: originalError });
52432
53002
  const recoveryMessage = "Antigravity could not repair the conversation's thinking blocks. Start a new session.";
52433
53003
  return new Response(
52434
53004
  JSON.stringify({
@@ -52508,7 +53078,9 @@ function createRequestExecutor(deps) {
52508
53078
  function dispose() {
52509
53079
  disposePromise ??= (async () => {
52510
53080
  retired = true;
52511
- shutdown.abort(new Error("The Antigravity request executor is disposed"));
53081
+ shutdown.abort(
53082
+ new HostRefusalError("The Antigravity request executor is disposed")
53083
+ );
52512
53084
  await drain();
52513
53085
  })();
52514
53086
  return disposePromise;
@@ -52517,11 +53089,11 @@ function createRequestExecutor(deps) {
52517
53089
  execute(input2, init, requestOptions) {
52518
53090
  if (shutdown.signal.aborted)
52519
53091
  return Promise.reject(
52520
- new Error("The Antigravity request executor is disposed")
53092
+ new HostRefusalError("The Antigravity request executor is disposed")
52521
53093
  );
52522
53094
  if (retired)
52523
53095
  return Promise.reject(
52524
- new Error("The Antigravity request executor is retired")
53096
+ new HostRefusalError("The Antigravity request executor is retired")
52525
53097
  );
52526
53098
  const requestedSignal = init?.signal ?? (input2 instanceof Request ? input2.signal : void 0);
52527
53099
  const cancellation = createRequestCancellation(
@@ -52531,15 +53103,23 @@ function createRequestExecutor(deps) {
52531
53103
  cancellation.signal,
52532
53104
  deps.preResponseClock
52533
53105
  );
52534
- log18.debug("pre-response-start", { limitMs: PRE_RESPONSE_DEADLINE_MS });
53106
+ log19.debug("pre-response-start", { limitMs: PRE_RESPONSE_DEADLINE_MS });
52535
53107
  const handoff = createAfterHandoff(
52536
53108
  advisoryWork,
52537
53109
  requestedSignal ? [requestedSignal, shutdown.signal] : [shutdown.signal],
52538
- () => log18.debug("post-response-advisory-work-failed")
53110
+ () => log19.debug("post-response-advisory-work-failed")
52539
53111
  );
52540
53112
  const waitPolicy = {};
52541
53113
  const selectedCredentials = /* @__PURE__ */ new Set();
52542
53114
  const selectedProjectIds = /* @__PURE__ */ new Set();
53115
+ const redactFailure = (error) => {
53116
+ const redacted = redactCredentialError(
53117
+ error,
53118
+ [...selectedCredentials],
53119
+ [...selectedProjectIds]
53120
+ );
53121
+ return isUpstreamFailure(error) ? markUpstreamFailure(redacted) : redacted;
53122
+ };
52543
53123
  const pending = withRoutingWaitReports(
52544
53124
  cancellation.signal,
52545
53125
  (waits) => deadline.wait(
@@ -52557,7 +53137,7 @@ function createRequestExecutor(deps) {
52557
53137
  ).catch((error) => {
52558
53138
  cancellation.signal.throwIfAborted();
52559
53139
  if (error instanceof PreResponseTimeoutError) {
52560
- log18.debug("pre-response-timeout", { reason: error.reason });
53140
+ log19.debug("pre-response-timeout", { reason: error.reason });
52561
53141
  return waitPolicy.refusal?.() ?? preResponseTimeoutResponse();
52562
53142
  }
52563
53143
  throw error;
@@ -52600,21 +53180,13 @@ function createRequestExecutor(deps) {
52600
53180
  handoff.cancel();
52601
53181
  deadline.dispose();
52602
53182
  cancellation.release();
52603
- throw redactCredentialError(
52604
- error,
52605
- [...selectedCredentials],
52606
- [...selectedProjectIds]
52607
- );
53183
+ throw redactFailure(error);
52608
53184
  }
52609
53185
  ).catch((error) => {
52610
53186
  handoff.cancel();
52611
53187
  deadline.dispose();
52612
53188
  cancellation.release();
52613
- throw redactCredentialError(
52614
- error,
52615
- [...selectedCredentials],
52616
- [...selectedProjectIds]
52617
- );
53189
+ throw redactFailure(error);
52618
53190
  });
52619
53191
  inFlight.add(pending);
52620
53192
  void pending.then(
@@ -52960,7 +53532,7 @@ async function defaultFence2() {
52960
53532
  return (await versionFenceOpen({ currentVersion })).open;
52961
53533
  }
52962
53534
  function createSettingsRuntime(options) {
52963
- const { file, legacyUserFile, log: log18 } = options;
53535
+ const { file, legacyUserFile, log: log19 } = options;
52964
53536
  const open14 = options.open ?? openSettings;
52965
53537
  const store = options.protection ?? createProtectionStore2();
52966
53538
  const reportPath = options.moveReportPath ?? defaultMoveReportPath();
@@ -52975,7 +53547,7 @@ function createSettingsRuntime(options) {
52975
53547
  const enqueue = (step) => {
52976
53548
  const run = queue2.then(step);
52977
53549
  queue2 = run.catch(
52978
- (error) => log18.warn("Settings refresh failed", {
53550
+ (error) => log19.warn("Settings refresh failed", {
52979
53551
  error: error instanceof Error ? error.name : "unknown"
52980
53552
  })
52981
53553
  );
@@ -53008,7 +53580,7 @@ function createSettingsRuntime(options) {
53008
53580
  await store.save(file, next);
53009
53581
  persisted = next;
53010
53582
  } catch (error) {
53011
- log18.warn("Could not save the last applied protection settings", {
53583
+ log19.warn("Could not save the last applied protection settings", {
53012
53584
  error: error instanceof Error ? error.name : "unknown"
53013
53585
  });
53014
53586
  }
@@ -53078,7 +53650,7 @@ function createSettingsRuntime(options) {
53078
53650
  if (mode === "shared" || disposed) return;
53079
53651
  handle = open14(ANTIGRAVITY_SETTINGS, {
53080
53652
  file,
53081
- log: log18,
53653
+ log: log19,
53082
53654
  separateInstall: false,
53083
53655
  createMissing: true,
53084
53656
  legacyProject: (project3) => ({
@@ -53097,12 +53669,12 @@ function createSettingsRuntime(options) {
53097
53669
  void enqueue(refreshAll);
53098
53670
  });
53099
53671
  };
53100
- const scheduleAttempt = (delay4) => {
53672
+ const scheduleAttempt = (delay5) => {
53101
53673
  if (disposed) return;
53102
53674
  retryTimer = setTimeout(() => {
53103
53675
  retryTimer = void 0;
53104
53676
  void enqueue(attemptMove);
53105
- }, delay4);
53677
+ }, delay5);
53106
53678
  retryTimer.unref?.();
53107
53679
  };
53108
53680
  const attemptMove = async () => {
@@ -53116,7 +53688,7 @@ function createSettingsRuntime(options) {
53116
53688
  legacyUserFile,
53117
53689
  floorKeys: options.floorKeys ?? (async () => null),
53118
53690
  fence: options.fence ?? defaultFence2,
53119
- log: log18,
53691
+ log: log19,
53120
53692
  ...options.move ? { move: options.move } : {}
53121
53693
  });
53122
53694
  } catch (cause) {
@@ -53135,7 +53707,7 @@ function createSettingsRuntime(options) {
53135
53707
  unmapped: result.unmapped
53136
53708
  });
53137
53709
  } catch (error) {
53138
- log18.warn("Could not save the settings move report", {
53710
+ log19.warn("Could not save the settings move report", {
53139
53711
  error: error instanceof Error ? error.name : "unknown"
53140
53712
  });
53141
53713
  }
@@ -53148,14 +53720,14 @@ function createSettingsRuntime(options) {
53148
53720
  return;
53149
53721
  case "fence-closed":
53150
53722
  if (!reportedFence)
53151
- log18.info(
53723
+ log19.info(
53152
53724
  "Settings stay in antigravity.json while an older antigravity-auth runs"
53153
53725
  );
53154
53726
  reportedFence = true;
53155
53727
  break;
53156
53728
  case "failed":
53157
53729
  if (!reportedFailure)
53158
- log18.warn("The settings move failed; it is retried", {
53730
+ log19.warn("The settings move failed; it is retried", {
53159
53731
  error: result.cause instanceof Error ? result.cause.name : "unknown"
53160
53732
  });
53161
53733
  reportedFailure = true;
@@ -53281,7 +53853,7 @@ function createSettingsRuntime(options) {
53281
53853
  (item) => item.file.kind === "user" && item.file.path === file || projectFiles.has(item.file.path)
53282
53854
  );
53283
53855
  };
53284
- const diagnostics = async (entry) => {
53856
+ const diagnostics2 = async (entry) => {
53285
53857
  if (options.separateInstall) return [];
53286
53858
  if (mode === "legacy") {
53287
53859
  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 +53933,7 @@ function createSettingsRuntime(options) {
53361
53933
  accountModels: () => mode === "shared" ? protection?.accountModels : void 0,
53362
53934
  updateAccountModels,
53363
53935
  limitsNotices: limits,
53364
- diagnosticsNotices: () => diagnostics(entry),
53936
+ diagnosticsNotices: () => diagnostics2(entry),
53365
53937
  moveReport: {
53366
53938
  present: async () => mode === "shared" && moveReport !== void 0,
53367
53939
  async dismiss() {
@@ -53457,9 +54029,9 @@ async function openCodeSettingsPaths(project3) {
53457
54029
 
53458
54030
  // src/plugin/background-quota-refresh.ts
53459
54031
  init_file_lock();
53460
- import { createHash as createHash17 } from "node:crypto";
54032
+ import { createHash as createHash18 } from "node:crypto";
53461
54033
  function quotaAccountIdentity2(refreshToken) {
53462
- return createHash17("sha256").update(refreshToken).digest("hex").slice(0, 16);
54034
+ return createHash18("sha256").update(refreshToken).digest("hex").slice(0, 16);
53463
54035
  }
53464
54036
  var MIN_INTERVAL_MS = 6e4;
53465
54037
  var STARTUP_JITTER_MS = 3e4;
@@ -54090,7 +54662,7 @@ async function buildLocationRuntime(options, scope) {
54090
54662
  sink: options.logSink,
54091
54663
  sinkEnabled: () => config?.config.debug_tui === true
54092
54664
  });
54093
- const log18 = logger3.createLogger("runtime");
54665
+ const log19 = logger3.createLogger("runtime");
54094
54666
  const settingsLease = (options.settingsRuntimes ?? processSettingsRuntimes).acquire({
54095
54667
  ...await openCodeSettingsPaths(options.directory),
54096
54668
  log: logger3.createLogger("settings"),
@@ -54229,7 +54801,7 @@ async function buildLocationRuntime(options, scope) {
54229
54801
  queue2.start();
54230
54802
  });
54231
54803
  accountChange = next.catch((error) => {
54232
- log18.warn("account view replacement failed", {
54804
+ log19.warn("account view replacement failed", {
54233
54805
  error: error instanceof Error ? error.message : String(error)
54234
54806
  });
54235
54807
  });
@@ -54855,8 +55427,15 @@ function tokenExchange(overrides) {
54855
55427
  }
54856
55428
  function storeRefusal(status) {
54857
55429
  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\`.`
55430
+ if (status.status === "error") {
55431
+ const error = new Error(
55432
+ `The Antigravity account store cannot be opened: ${status.reason}`
55433
+ );
55434
+ error.name = "AccountStoreAdmissionError";
55435
+ return error;
55436
+ }
55437
+ return new HostRefusalError(
55438
+ 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
55439
  );
54861
55440
  }
54862
55441
  async function openLocationRepository(directory, bindings, overrides, login) {
@@ -54896,7 +55475,7 @@ async function assertServingAdmission(location, now2) {
54896
55475
  );
54897
55476
  if (admission.status === "active") return;
54898
55477
  if (admission.status === "pending" && admission.phase === "activate")
54899
- throw new Error(
55478
+ throw new HostRefusalError(
54900
55479
  "An Antigravity account operation is still finishing; reopen the session once it completes."
54901
55480
  );
54902
55481
  throw storeRefusal(admission);
@@ -55385,8 +55964,7 @@ async function createGaVaultLocationServices(input2) {
55385
55964
  onError: (error) => vaultLogger.debug("vault-state-write-dropped", {
55386
55965
  error: error instanceof Error ? error.name : "unknown"
55387
55966
  })
55388
- },
55389
- grantPrincipal: () => custody.grantPrincipal?.()
55967
+ }
55390
55968
  });
55391
55969
  pipeline = await createGaVaultRequestPipeline({
55392
55970
  ...input2.assertAdmission ? { assertAdmission: input2.assertAdmission } : {},
@@ -55510,6 +56088,14 @@ function createGaLocationServicesFactory(bindings) {
55510
56088
  const nextReadSeq = () => ++readSeq;
55511
56089
  const registry = createGaSelectorRegistry(bindings.createSelector);
55512
56090
  let unavailableReason = VAULT_ACCOUNT_REMEDY;
56091
+ const sourceRefusal = () => {
56092
+ if (unavailableReason === VAULT_ACCOUNT_REMEDY)
56093
+ return new HostRefusalError(VAULT_ACCOUNT_REMEDY);
56094
+ const layout = currentVaultFolder(
56095
+ bindings.resolveAccountFile(directory)
56096
+ ).refusal;
56097
+ return layout?.message === unavailableReason ? layout : new Error(unavailableReason);
56098
+ };
55513
56099
  const authority = async () => {
55514
56100
  if (!custody) return "local";
55515
56101
  const mode = await custody.readMode();
@@ -55520,7 +56106,7 @@ function createGaLocationServicesFactory(bindings) {
55520
56106
  if (closing) throw new Error("The location services are disposed");
55521
56107
  const selected = await authority();
55522
56108
  if (closing) throw new Error("The location services are disposed");
55523
- if (selected !== "local") throw new Error(unavailableReason);
56109
+ if (selected !== "local") throw sourceRefusal();
55524
56110
  };
55525
56111
  let refreshVaultBinding;
55526
56112
  const refreshSelectedSource = async () => {
@@ -55745,7 +56331,7 @@ function createGaLocationServicesFactory(bindings) {
55745
56331
  });
55746
56332
  const recovery = {
55747
56333
  execute: async () => {
55748
- throw new Error(unavailableReason);
56334
+ throw sourceRefusal();
55749
56335
  },
55750
56336
  state: {
55751
56337
  read: async ({ signal }) => {
@@ -55975,8 +56561,7 @@ ${GA_POOL_PASTE_PROMPT}, or wait for the browser to finish.`;
55975
56561
  },
55976
56562
  assertAdmission: async () => {
55977
56563
  const selected = await authority();
55978
- if (closing || selected !== "vault")
55979
- throw new Error(unavailableReason);
56564
+ if (closing || selected !== "vault") throw sourceRefusal();
55980
56565
  }
55981
56566
  });
55982
56567
  try {
@@ -56001,7 +56586,7 @@ ${GA_POOL_PASTE_PROMPT}, or wait for the browser to finish.`;
56001
56586
  if (closing) throw new Error("The location services are disposed");
56002
56587
  if (selected === "local") return local();
56003
56588
  if (selected === "unreadable") {
56004
- if (purpose === "execute") throw new Error(unavailableReason);
56589
+ if (purpose === "execute") throw sourceRefusal();
56005
56590
  return recovery;
56006
56591
  }
56007
56592
  try {
@@ -56172,9 +56757,30 @@ var createGaLocationServices = (input2) => {
56172
56757
  return createGaLocationServicesForHost({ readHostSlot })(input2);
56173
56758
  };
56174
56759
 
56760
+ // src/plugin/shared/opencode-retry-hints.ts
56761
+ var RETRY_PATTERNS = [
56762
+ /429|500|502|503|504|524/i,
56763
+ /rate increased too quickly|rate limit|rate-limit|rate_limit|too many requests/i,
56764
+ /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,
56765
+ /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,
56766
+ /^timeout$|\b(?:request|response|connection|network|stream|read) (?:timeout|timed out|time out)\b/i,
56767
+ /try your request again|retry your request|resource exhausted|resource_exhausted/i,
56768
+ /\btry again (?:later|in\b)|\b(?:currently|temporarily) at capacity\b/i,
56769
+ // Non-API errors also have a branch that checks these substrings.
56770
+ /too_many_requests|exhausted|unavailable/i
56771
+ ];
56772
+ function openCodeRetryHint(text2) {
56773
+ for (const pattern of RETRY_PATTERNS) {
56774
+ const match = pattern.exec(text2);
56775
+ if (match) return match[0];
56776
+ }
56777
+ return void 0;
56778
+ }
56779
+
56175
56780
  // src/ga/server/index.ts
56176
56781
  init_storage();
56177
56782
  init_process_heartbeat();
56783
+ init_runtime_layout();
56178
56784
  init_vault_folder();
56179
56785
 
56180
56786
  // src/ga/proxy-guard.ts
@@ -57715,7 +58321,7 @@ function isGaGoogleContentRequest(request2) {
57715
58321
  return false;
57716
58322
  }
57717
58323
  }
57718
- function gaPreHeaderFailureResponse(error) {
58324
+ function gaPreHeaderFailureResponse(error, report = (message) => stderrLogSink({ service: "bridge", level: "warn", message })) {
57719
58325
  const err = error;
57720
58326
  const rawStatusCode = typeof err?.statusCode === "number" && Number.isSafeInteger(err.statusCode) ? err.statusCode : void 0;
57721
58327
  const rawStatus = typeof err?.status === "number" && Number.isSafeInteger(err.status) ? err.status : void 0;
@@ -57761,9 +58367,11 @@ function gaPreHeaderFailureResponse(error) {
57761
58367
  }
57762
58368
  }
57763
58369
  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;
58370
+ let message = gaHostFailure(error, report).message;
58371
+ if (isUpstreamFailure(error)) {
58372
+ const redacted = redactProjectIdText(rawMessage);
58373
+ message = isQuotaError(status, rawMessage, err?.details) ? normalizeResetDuration(redacted) : redacted;
58374
+ }
57767
58375
  const headers = new Headers({ "content-type": "application/json" });
57768
58376
  const metadata = resolveRetryMetadata({
57769
58377
  details: err?.details,
@@ -57882,14 +58490,20 @@ async function startGaLoopbackBridge(options) {
57882
58490
  try {
57883
58491
  upstream = await options.execute(entry.job, {
57884
58492
  signal: controller.signal,
57885
- send: options.send,
58493
+ send: async (...args) => {
58494
+ try {
58495
+ return await options.send(...args);
58496
+ } catch (error) {
58497
+ throw markUpstreamFailure(error);
58498
+ }
58499
+ },
57886
58500
  onResponseHandoff: (callback) => {
57887
58501
  acknowledge = callback;
57888
58502
  }
57889
58503
  });
57890
58504
  } catch (error) {
57891
58505
  acknowledge = void 0;
57892
- upstream = gaPreHeaderFailureResponse(error);
58506
+ upstream = gaPreHeaderFailureResponse(error, report);
57893
58507
  }
57894
58508
  await pipeResponse(
57895
58509
  upstream,
@@ -58497,17 +59111,14 @@ async function rewriteGaHttpRequest(event, input2) {
58497
59111
  if (!owned) return;
58498
59112
  const original = event.request;
58499
59113
  if (!isGaGoogleContentRequest(original)) {
58500
- throw new Error(GA_NON_CONTENT_REQUEST_MESSAGE);
59114
+ throw new HostRefusalError(GA_NON_CONTENT_REQUEST_MESSAGE);
58501
59115
  }
58502
59116
  if (!isCanonicalGoogleOrigin(original.url)) {
58503
- throw new Error(GA_CUSTOM_GOOGLE_ORIGIN_MESSAGE);
59117
+ throw new HostRefusalError(GA_CUSTOM_GOOGLE_ORIGIN_MESSAGE);
58504
59118
  }
58505
59119
  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}`
59120
+ throw new HostRefusalError(
59121
+ offCatalogModelRefusal(event.model.id, input2.isRegisteredModel)
58511
59122
  );
58512
59123
  }
58513
59124
  const job = {
@@ -58521,6 +59132,15 @@ async function rewriteGaHttpRequest(event, input2) {
58521
59132
  };
58522
59133
  event.request = input2.bridge.rewrite(original, job, input2.env);
58523
59134
  }
59135
+ function offCatalogModelRefusal(modelID, isRegisteredModel) {
59136
+ const safeID = (id) => /^[A-Za-z0-9._/-]{1,128}$/.test(id) && !openCodeRetryHint(id);
59137
+ if (!safeID(modelID)) {
59138
+ return "This request cannot use Antigravity. Choose a google/antigravity- model.";
59139
+ }
59140
+ const twin = modelID.startsWith("antigravity-") ? null : `antigravity-${modelID}`;
59141
+ const suggestion = twin && safeID(twin) && isRegisteredModel(twin) ? `Use google/${twin}.` : "Choose a google/antigravity- model.";
59142
+ return `This request cannot use Antigravity: google/${modelID} is not an Antigravity model. ${suggestion}`;
59143
+ }
58524
59144
  function adaptGaHttpResponse(event, bridge) {
58525
59145
  const adapted = bridge.adaptResponse(event.request, event.response);
58526
59146
  if (adapted) event.response = adapted;
@@ -58579,6 +59199,11 @@ function stderrLogSink(record5) {
58579
59199
  } catch {
58580
59200
  }
58581
59201
  }
59202
+ function gaHostFailure(error, report) {
59203
+ if (error instanceof RuntimeLayoutRefusal || error instanceof LoopbackProxyGuardError || error instanceof GaSetupContextError)
59204
+ return error;
59205
+ return hostFailure(error, report);
59206
+ }
58582
59207
  function headerValue(request2, names) {
58583
59208
  for (const name of names) {
58584
59209
  const value = request2.headers.get(name);
@@ -58587,6 +59212,16 @@ function headerValue(request2, names) {
58587
59212
  return null;
58588
59213
  }
58589
59214
  async function setupGaActivation(context, factory, overrides = {}) {
59215
+ return setupGaActivationRuntime(context, factory, overrides).catch(
59216
+ (error) => {
59217
+ throw gaHostFailure(
59218
+ error,
59219
+ (message) => stderrLogSink({ service: "setup", level: "error", message })
59220
+ );
59221
+ }
59222
+ );
59223
+ }
59224
+ async function setupGaActivationRuntime(context, factory, overrides) {
58590
59225
  if (classifyGaSetupContext(context) === "legacy") return void 0;
58591
59226
  const directory = context.location.directory;
58592
59227
  const send = createGaRawSender(overrides);
@@ -58748,6 +59383,13 @@ async function setupGaActivation(context, factory, overrides = {}) {
58748
59383
  isRegisteredModel,
58749
59384
  env: process.env,
58750
59385
  ownership
59386
+ }).catch((error) => {
59387
+ if (event.request.signal.aborted && error === event.request.signal.reason)
59388
+ throw error;
59389
+ throw gaHostFailure(
59390
+ error,
59391
+ (message) => runtime.logger.createLogger("request").warn(message)
59392
+ );
58751
59393
  }),
58752
59394
  { providerID: GA_PROVIDER_ID }
58753
59395
  );
@@ -58775,7 +59417,8 @@ function createGaAntigravityPlugin(overrides = {}) {
58775
59417
 
58776
59418
  // src/plugin/index.ts
58777
59419
  init_dist();
58778
- import { createHash as createHash23, randomUUID as randomUUID26 } from "node:crypto";
59420
+ init_runtime_layout();
59421
+ import { createHash as createHash24, randomUUID as randomUUID26 } from "node:crypto";
58779
59422
  import { join as join47, resolve as resolve33 } from "node:path";
58780
59423
 
58781
59424
  // src/cli.ts
@@ -59078,7 +59721,7 @@ async function select2(terminal, items, options) {
59078
59721
  }
59079
59722
 
59080
59723
  // src/common-auth-embedded/claustrum/enrollment.js
59081
- import { createHash as createHash18, randomBytes as randomBytes6, randomUUID as randomUUID23 } from "node:crypto";
59724
+ import { createHash as createHash19, randomBytes as randomBytes6, randomUUID as randomUUID23 } from "node:crypto";
59082
59725
  import { constants as fsConstants2 } from "node:fs";
59083
59726
  import { chmod as chmod6, mkdir as mkdir18, open as open11, readFile as readFile20, realpath as realpath6, rename as rename13, stat as stat17, unlink as unlink14 } from "node:fs/promises";
59084
59727
  import { basename as basename13, dirname as dirname29, extname as extname2, isAbsolute as isAbsolute4, join as join34, resolve as resolve27 } from "node:path";
@@ -60721,7 +61364,7 @@ var ClaustrumEnrollmentManager2 = class {
60721
61364
  }
60722
61365
  if (!state2.requestId) {
60723
61366
  try {
60724
- const requestSecretHash = createHash18("sha256").update(Buffer.from(state2.requestSecret, "hex")).digest("hex");
61367
+ const requestSecretHash = createHash19("sha256").update(Buffer.from(state2.requestSecret, "hex")).digest("hex");
60725
61368
  const proposal = {
60726
61369
  name: state2.proposedName,
60727
61370
  requestSecretHash
@@ -61368,13 +62011,15 @@ async function detectHosts(plugin2, io = {}) {
61368
62011
  }
61369
62012
 
61370
62013
  // src/common-auth-embedded/setup/enroll.js
61371
- import { setTimeout as delay } from "node:timers/promises";
62014
+ import { setTimeout as delay2 } from "node:timers/promises";
61372
62015
  import { writeEnrollmentTokenFile as writeEnrollmentTokenFile3 } from "@cortexkit/claustrum-client";
61373
62016
 
61374
62017
  // src/common-auth-embedded/setup/process-fence.js
62018
+ init_logger3();
61375
62019
  import { statSync as statSync7 } from "node:fs";
61376
62020
  import { win32 as win325 } from "node:path";
61377
62021
  var WINDOWS_CIM_TIMEOUT_MS = 45e3;
62022
+ var log13 = createLogger3("setup-process-fence");
61378
62023
  var WINDOWS_ARM_POWERSHELL_TIMEOUT_MS = 9e4;
61379
62024
  function isFile(file) {
61380
62025
  try {
@@ -61534,14 +62179,23 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
61534
62179
  options.onStep?.({ ...inspection });
61535
62180
  }
61536
62181
  };
61537
- const inspectCim = (args) => {
62182
+ const inspectCim = async (args) => {
61538
62183
  const pwsh = win325.resolve(windowsEnv(env3, "ProgramFiles") ?? "C:\\Program Files", "PowerShell", "7", "pwsh.exe");
61539
62184
  const program = (options.isFile ?? isFile)(pwsh) ? "pwsh" : "powershell";
61540
62185
  const arm64 = (windowsEnv(env3, "PROCESSOR_ARCHITEW6432") ?? windowsEnv(env3, "PROCESSOR_ARCHITECTURE"))?.toUpperCase() === "ARM64";
61541
62186
  const slow = program === "powershell" && arm64;
61542
62187
  if (slow)
61543
62188
  options.onProgress?.("Checking that OpenCode and Pi are not running. Without PowerShell 7 this can take up to a minute on Windows ARM; installing PowerShell 7 makes it fast.");
61544
- return inspect("CIM", program === "pwsh" ? pwsh : win325.resolve(system32, "WindowsPowerShell", "v1.0", "powershell.exe"), args, slow ? WINDOWS_ARM_POWERSHELL_TIMEOUT_MS : WINDOWS_CIM_TIMEOUT_MS, program);
62189
+ const file = program === "pwsh" ? pwsh : win325.resolve(system32, "WindowsPowerShell", "v1.0", "powershell.exe");
62190
+ const timeoutMs = slow ? WINDOWS_ARM_POWERSHELL_TIMEOUT_MS : WINDOWS_CIM_TIMEOUT_MS;
62191
+ const started = performance.now();
62192
+ const result = await inspect("CIM", file, args, timeoutMs, program);
62193
+ const remaining = Math.floor(timeoutMs - (performance.now() - started));
62194
+ if ((result.exitCode === 3221225477 || result.exitCode === -1073741819) && !result.timedOut && !result.signal && !result.spawnError && remaining > 0) {
62195
+ log13.warn("Windows process query crashed with an access violation; retrying once");
62196
+ return inspect("CIM", file, args, remaining, program);
62197
+ }
62198
+ return result;
61545
62199
  };
61546
62200
  try {
61547
62201
  if (windows2 && options.hostImagesOnly) {
@@ -61734,7 +62388,7 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
61734
62388
  throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.", { reason: "connection-failed" });
61735
62389
  });
61736
62390
  const now2 = io.now ?? (() => performance.now());
61737
- const wait2 = io.wait ?? delay;
62391
+ const wait2 = io.wait ?? delay2;
61738
62392
  try {
61739
62393
  const manager = new ClaustrumEnrollmentManager2({
61740
62394
  proposedName: name,
@@ -61968,7 +62622,7 @@ async function selectSetupHosts(terminal, found) {
61968
62622
 
61969
62623
  // src/common-auth-embedded/setup/register.js
61970
62624
  import { rename as rename15 } from "node:fs/promises";
61971
- import { setTimeout as delay3 } from "node:timers/promises";
62625
+ import { setTimeout as delay4 } from "node:timers/promises";
61972
62626
  import { domainToUnicode } from "node:url";
61973
62627
  import { applyEdits as applyEdits2, createScanner as createScanner2, findNodeAtLocation as findNodeAtLocation2, modify as modify2, parse as parse2, parseTree as parseTree2 } from "jsonc-parser";
61974
62628
 
@@ -61976,7 +62630,7 @@ import { applyEdits as applyEdits2, createScanner as createScanner2, findNodeAtL
61976
62630
  import { randomUUID as randomUUID24 } from "node:crypto";
61977
62631
  import { mkdir as mkdir19, open as open12, rename as rename14, stat as stat19, unlink as unlink15 } from "node:fs/promises";
61978
62632
  import { basename as basename14, dirname as dirname30, join as join36 } from "node:path";
61979
- import { setTimeout as delay2 } from "node:timers/promises";
62633
+ import { setTimeout as delay3 } from "node:timers/promises";
61980
62634
  async function writeHostConfigAtomic(file, content, options = {}) {
61981
62635
  const windows2 = (options.platform ?? process.platform) === "win32";
61982
62636
  const parent = dirname30(file);
@@ -62015,7 +62669,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
62015
62669
  const remaining = 2e3 - (now2() - started);
62016
62670
  if (!windows2 || !["EPERM", "EBUSY", "EACCES"].includes(code2 ?? "") || remaining <= 0 || attempt >= 40)
62017
62671
  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)));
62672
+ await (options.wait ?? delay3)(Math.min(remaining, 25 * 2 ** Math.min(attempt, 2)));
62019
62673
  }
62020
62674
  }
62021
62675
  } finally {
@@ -62186,7 +62840,7 @@ async function registerOpenCode(writes, beforeWrite) {
62186
62840
  // Only the rename publishes host-readable config; recheck on every retry.
62187
62841
  beforeRename: guard ? () => guard.check({ reuse: true }) : void 0,
62188
62842
  rename: guard ? (from, to) => guard.step(() => rename15(from, to)) : void 0,
62189
- wait: guard ? (ms) => guard.step(() => delay3(ms)) : void 0
62843
+ wait: guard ? (ms) => guard.step(() => delay4(ms)) : void 0
62190
62844
  });
62191
62845
  }
62192
62846
  }
@@ -64044,7 +64698,7 @@ function isTuiConnected(sessionId) {
64044
64698
  }
64045
64699
 
64046
64700
  // src/rpc/rpc-dir.ts
64047
- import { createHash as createHash19 } from "node:crypto";
64701
+ import { createHash as createHash20 } from "node:crypto";
64048
64702
  import { homedir as homedir14, tmpdir as tmpdir6 } from "node:os";
64049
64703
  import { isAbsolute as isAbsolute5, join as join42, resolve as resolve30 } from "node:path";
64050
64704
  var RPC_DIR_ENV = "ANTIGRAVITY_AUTH_RPC_DIR";
@@ -64053,7 +64707,7 @@ function getRpcDir(projectDirectory) {
64053
64707
  if (override) {
64054
64708
  return isAbsolute5(override) ? override : resolve30(projectDirectory, override);
64055
64709
  }
64056
- const projectHash = createHash19("sha256").update(resolve30(projectDirectory)).digest("hex").slice(0, 16);
64710
+ const projectHash = createHash20("sha256").update(resolve30(projectDirectory)).digest("hex").slice(0, 16);
64057
64711
  const stateHome = process.env.XDG_STATE_HOME ?? join42(homedir14(), ".local", "state");
64058
64712
  return join42(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
64059
64713
  }
@@ -64065,7 +64719,7 @@ function isSessionId(value) {
64065
64719
 
64066
64720
  // src/common-auth-embedded/rpc/port-file.js
64067
64721
  init_private_files2();
64068
- import { createHash as createHash20, randomUUID as randomUUID25 } from "node:crypto";
64722
+ import { createHash as createHash21, randomUUID as randomUUID25 } from "node:crypto";
64069
64723
  import { chmod as chmod7, mkdir as mkdir20, open as open13, readdir as readdir7, rename as rename16, rmdir as rmdir3, stat as stat20, unlink as unlink16 } from "node:fs/promises";
64070
64724
  import { uptime as uptime2 } from "node:os";
64071
64725
  import { join as join43, resolve as resolve31 } from "node:path";
@@ -64114,8 +64768,8 @@ function isUsablePortFileEntry(value, name) {
64114
64768
  const { pid, port, token } = value;
64115
64769
  return isProbeablePid(pid) && filenamePid(name) === pid && typeof port === "number" && Number.isInteger(port) && port >= 1 && port <= 65535 && typeof token === "string" && token.length > 0;
64116
64770
  }
64117
- async function removeCorruptPortFile(portFile, log18) {
64118
- log18?.debug("rpc corrupt port file", { pid: process.pid, portFile });
64771
+ async function removeCorruptPortFile(portFile, log19) {
64772
+ log19?.debug("rpc corrupt port file", { pid: process.pid, portFile });
64119
64773
  await unlink16(portFile).catch(() => {
64120
64774
  });
64121
64775
  }
@@ -64169,7 +64823,7 @@ async function writePortFile(dir, entry, options = {}) {
64169
64823
  }
64170
64824
  }
64171
64825
  }
64172
- async function sweepRpcState(root, activeDir, isManagedDir, log18, options = {}) {
64826
+ async function sweepRpcState(root, activeDir, isManagedDir, log19, options = {}) {
64173
64827
  const cutoff = staleBefore(options);
64174
64828
  let projectDirs;
64175
64829
  try {
@@ -64185,14 +64839,14 @@ async function sweepRpcState(root, activeDir, isManagedDir, log18, options = {})
64185
64839
  continue;
64186
64840
  }
64187
64841
  const dir = join43(root, projectDir.name);
64188
- if (!await sweepRpcDirectory(dir, log18, options, cutoff))
64842
+ if (!await sweepRpcDirectory(dir, log19, options, cutoff))
64189
64843
  continue;
64190
64844
  if (resolve31(dir) !== active2)
64191
64845
  await rmdir3(dir).catch(() => {
64192
64846
  });
64193
64847
  }
64194
64848
  }
64195
- async function sweepRpcDirectory(dir, log18, options = {}, cutoff = staleBefore(options)) {
64849
+ async function sweepRpcDirectory(dir, log19, options = {}, cutoff = staleBefore(options)) {
64196
64850
  let names;
64197
64851
  try {
64198
64852
  names = await readdir7(dir);
@@ -64220,11 +64874,11 @@ async function sweepRpcDirectory(dir, log18, options = {}, cutoff = staleBefore(
64220
64874
  try {
64221
64875
  parsed = JSON.parse(raw);
64222
64876
  } catch {
64223
- await removeCorruptPortFile(portFile, log18);
64877
+ await removeCorruptPortFile(portFile, log19);
64224
64878
  continue;
64225
64879
  }
64226
64880
  if (!isUsablePortFileEntry(parsed, name)) {
64227
- await removeCorruptPortFile(portFile, log18);
64881
+ await removeCorruptPortFile(portFile, log19);
64228
64882
  continue;
64229
64883
  }
64230
64884
  const entry = parsed;
@@ -64255,7 +64909,7 @@ var key = /* @__PURE__ */ Symbol.for("common-auth.rpc.startup-sweep");
64255
64909
  globals[key] ??= {};
64256
64910
  var state = globals[key];
64257
64911
  var now = Date.now;
64258
- async function sweepRpcStateOnStart(root, activeDir, isManagedDir, log18) {
64912
+ async function sweepRpcStateOnStart(root, activeDir, isManagedDir, log19) {
64259
64913
  const time = now();
64260
64914
  if (state.lastSweepAt !== void 0 && time - state.lastSweepAt < 6e4) {
64261
64915
  const active2 = resolve32(activeDir);
@@ -64264,11 +64918,11 @@ async function sweepRpcStateOnStart(root, activeDir, isManagedDir, log18) {
64264
64918
  throw error;
64265
64919
  return void 0;
64266
64920
  }))?.isDirectory())
64267
- await sweepRpcDirectory(active2, log18);
64921
+ await sweepRpcDirectory(active2, log19);
64268
64922
  return;
64269
64923
  }
64270
64924
  state.lastSweepAt = time;
64271
- await sweepRpcState(root, activeDir, isManagedDir, log18);
64925
+ await sweepRpcState(root, activeDir, isManagedDir, log19);
64272
64926
  }
64273
64927
 
64274
64928
  // src/common-auth-embedded/rpc/rpc-server.js
@@ -64344,7 +64998,7 @@ function tokenOk(header, token) {
64344
64998
  async function startRpcServer(options) {
64345
64999
  if (typeof options.drain === "function" === (typeof options.drainAsync === "function"))
64346
65000
  throw new TypeError("exactly one of drain or drainAsync must be provided");
64347
- const log18 = options.log ?? { warn() {
65001
+ const log19 = options.log ?? { warn() {
64348
65002
  }, debug() {
64349
65003
  } };
64350
65004
  const token = randomBytes7(32).toString("hex");
@@ -64445,7 +65099,7 @@ async function startRpcServer(options) {
64445
65099
  return json(400, { error: "session required" });
64446
65100
  if (sessionId === void 0 && !warnedMissingNotificationSession) {
64447
65101
  warnedMissingNotificationSession = true;
64448
- log18.warn("rpc notification drain missing session id", {
65102
+ log19.warn("rpc notification drain missing session id", {
64449
65103
  pid: process.pid
64450
65104
  });
64451
65105
  }
@@ -64454,7 +65108,7 @@ async function startRpcServer(options) {
64454
65108
  try {
64455
65109
  messages = await options.drainAsync(lastReceivedId, sessionId);
64456
65110
  } catch (error) {
64457
- log18.warn("rpc notification drain failed", {
65111
+ log19.warn("rpc notification drain failed", {
64458
65112
  pid: process.pid,
64459
65113
  error: error instanceof Error ? error.message : String(error)
64460
65114
  });
@@ -64473,20 +65127,20 @@ async function startRpcServer(options) {
64473
65127
  return json(404, { error: "unknown method" });
64474
65128
  } catch (error) {
64475
65129
  if (error instanceof RpcRequestError) {
64476
- log18.debug("rpc request refused", {
65130
+ log19.debug("rpc request refused", {
64477
65131
  pid: process.pid,
64478
65132
  status: error.status
64479
65133
  });
64480
65134
  return json(error.status, { error: error.message });
64481
65135
  }
64482
65136
  if (error instanceof ApplyDeadlineError) {
64483
- log18.warn("rpc apply deadline exceeded", {
65137
+ log19.warn("rpc apply deadline exceeded", {
64484
65138
  pid: process.pid,
64485
65139
  deadlineMs: options.applyDeadlineMs
64486
65140
  });
64487
65141
  return json(504, { error: "handler deadline exceeded" });
64488
65142
  }
64489
- log18.warn("rpc request failed", {
65143
+ log19.warn("rpc request failed", {
64490
65144
  pid: process.pid,
64491
65145
  error: error instanceof Error ? error.message : String(error)
64492
65146
  });
@@ -64506,9 +65160,9 @@ async function startRpcServer(options) {
64506
65160
  server.unref();
64507
65161
  if (options.sweepRoot) {
64508
65162
  try {
64509
- await sweepRpcStateOnStart(options.sweepRoot, options.dir, options.isManagedDir, log18);
65163
+ await sweepRpcStateOnStart(options.sweepRoot, options.dir, options.isManagedDir, log19);
64510
65164
  } catch (error) {
64511
- log18.warn("rpc state sweep failed", {
65165
+ log19.warn("rpc state sweep failed", {
64512
65166
  pid: process.pid,
64513
65167
  error: error instanceof Error ? error.message : String(error)
64514
65168
  });
@@ -64516,7 +65170,7 @@ async function startRpcServer(options) {
64516
65170
  }
64517
65171
  try {
64518
65172
  await writePortFile(options.dir, { port, token, pid: process.pid }, { secureDir: options.secureDir });
64519
- log18.debug("rpc server pid", {
65173
+ log19.debug("rpc server pid", {
64520
65174
  pid: process.pid,
64521
65175
  rpcPort: port
64522
65176
  });
@@ -64865,11 +65519,15 @@ init_dist();
64865
65519
  // src/plugin/config/models.ts
64866
65520
  function getOpencode1ModelDefinitions() {
64867
65521
  const models = { ...OPENCODE_MODEL_DEFINITIONS };
64868
- const hydrogen = models["antigravity-gemini-4-hydrogen"];
64869
- if (hydrogen) {
64870
- const variants = { ...hydrogen.variants };
65522
+ for (const id of [
65523
+ "antigravity-gemini-4-hydrogen",
65524
+ "antigravity-gemini-4-neon"
65525
+ ]) {
65526
+ const model = models[id];
65527
+ if (!model) continue;
65528
+ const variants = { ...model.variants };
64871
65529
  delete variants.xhigh;
64872
- models[hydrogen.id] = { ...hydrogen, variants };
65530
+ models[id] = { ...model, variants };
64873
65531
  }
64874
65532
  return models;
64875
65533
  }
@@ -65912,10 +66570,10 @@ function toV1AuthCallbackResult(result) {
65912
66570
  };
65913
66571
  }
65914
66572
  var MAX_OAUTH_ACCOUNTS = 10;
65915
- var log13 = createLogger4("oauth-methods");
65916
- async function reportPersistenceFailure(error, client, log18) {
66573
+ var log14 = createLogger4("oauth-methods");
66574
+ async function reportPersistenceFailure(error, client, log19) {
65917
66575
  const message = error instanceof AccountStorageUnreadableError ? `Account storage at ${error.details.path} is unreadable (${error.details.reason}: ${error.details.detail}).${error.details.backupPath ? ` A backup was written to ${error.details.backupPath}. Repair or remove the existing file before retrying.` : " A backup could not be written; repair or remove the existing file before retrying."}` : error instanceof Error ? error.message : String(error);
65918
- log18.error("OAuth login persistence failed; aborting login", {
66576
+ log19.error("OAuth login persistence failed; aborting login", {
65919
66577
  error: message
65920
66578
  });
65921
66579
  try {
@@ -66752,7 +67410,7 @@ ${verifyUrl}
66752
67410
  }
66753
67411
  });
66754
67412
  } catch (storeError) {
66755
- log13.error(
67413
+ log14.error(
66756
67414
  "Failed to update stored Antigravity OAuth credentials",
66757
67415
  { error: String(storeError) }
66758
67416
  );
@@ -66777,7 +67435,7 @@ ${verifyUrl}
66777
67435
  }
66778
67436
  });
66779
67437
  } catch (storeError) {
66780
- log13.error(
67438
+ log14.error(
66781
67439
  "Failed to clear stored Antigravity OAuth credentials",
66782
67440
  { error: String(storeError) }
66783
67441
  );
@@ -66818,7 +67476,7 @@ Re-authenticating ${refreshEmail || "account"}...
66818
67476
  }
66819
67477
  });
66820
67478
  } catch (storeError) {
66821
- log13.error(
67479
+ log14.error(
66822
67480
  "Failed to clear stored Antigravity OAuth credentials",
66823
67481
  { error: String(storeError) }
66824
67482
  );
@@ -67157,7 +67815,7 @@ ${authorization2.url}
67157
67815
  return await reportPersistenceFailure(
67158
67816
  persistError,
67159
67817
  client,
67160
- log13
67818
+ log14
67161
67819
  );
67162
67820
  }
67163
67821
  const newTotal = existingCount + 1;
@@ -67201,7 +67859,7 @@ ${authorization2.url}
67201
67859
  try {
67202
67860
  await persistAccountPool2([result], false);
67203
67861
  } catch (persistError) {
67204
- return await reportPersistenceFailure(persistError, client, log13);
67862
+ return await reportPersistenceFailure(persistError, client, log14);
67205
67863
  }
67206
67864
  const newTotal = existingCount + 1;
67207
67865
  const toastMessage = existingCount > 0 ? `Added account${result.email ? ` (${result.email})` : ""} - ${newTotal} total` : `Authenticated${result.email ? ` (${result.email})` : ""}`;
@@ -67358,13 +68016,37 @@ function createAccountCommandOAuthService(options) {
67358
68016
 
67359
68017
  // src/plugin/auth-loader.ts
67360
68018
  init_dist();
67361
- import { createHash as createHash21 } from "node:crypto";
68019
+ init_runtime_layout();
68020
+ import { createHash as createHash22 } from "node:crypto";
67362
68021
  init_debug();
67363
68022
  init_logger4();
67364
68023
  init_storage();
67365
- var log14 = createLogger4("auth-loader");
68024
+ var log15 = createLogger4("auth-loader");
68025
+ var failureLog = createLogger("auth-loader");
68026
+ function loaderFailure(error) {
68027
+ if (error instanceof RuntimeLayoutRefusal) return error;
68028
+ return hostFailure(error, (diagnostic) => failureLog.error(diagnostic));
68029
+ }
68030
+ function openingFailure(opening) {
68031
+ if (opening.status === "recovery-required") {
68032
+ return new HostRefusalError(
68033
+ "An account clear or pool replacement was interrupted; it must be finished before the accounts are used."
68034
+ );
68035
+ }
68036
+ if (opening.status === "refused") {
68037
+ const { admission } = opening;
68038
+ if (admission.status === "busy") return new AccountStoreBusyError();
68039
+ if (admission.status === "pending" || admission.status === "inactive") {
68040
+ return new HostRefusalError(accountStoreAdmissionMessage(admission));
68041
+ }
68042
+ failureLog.error("Refusing to start: the account store cannot serve", {
68043
+ message: opening.message
68044
+ });
68045
+ }
68046
+ return new HostRefusalError(HOST_STORE_READ_FAILURE);
68047
+ }
67366
68048
  function refreshTokenIdentity(refreshToken) {
67367
- return createHash21("sha256").update(refreshToken).digest("hex").slice(0, 16);
68049
+ return createHash22("sha256").update(refreshToken).digest("hex").slice(0, 16);
67368
68050
  }
67369
68051
  async function initializeDefaultFreshStore() {
67370
68052
  return initializeFreshAccountStoreFor(await loadCommonAuthStoreModules());
@@ -67449,7 +68131,7 @@ function createAuthLoader({
67449
68131
  let closed2 = false;
67450
68132
  const isClosed = () => closed2 || lifecycle.isClosing();
67451
68133
  const assertOpen = () => {
67452
- if (isClosed()) throw new Error("The account loader is disposed");
68134
+ if (isClosed()) throw new HostRefusalError("The account loader is disposed");
67453
68135
  };
67454
68136
  let fetchRuntime = null;
67455
68137
  let localUnavailable = false;
@@ -67475,7 +68157,7 @@ function createAuthLoader({
67475
68157
  const installRuntime = async (accountManager, getAuth, source) => {
67476
68158
  if (isClosed()) {
67477
68159
  await accountManager.dispose();
67478
- throw new Error("The account loader is disposed");
68160
+ throw new HostRefusalError("The account loader is disposed");
67479
68161
  }
67480
68162
  currentRequestSource = "local";
67481
68163
  localUnavailable = false;
@@ -67499,17 +68181,19 @@ function createAuthLoader({
67499
68181
  const opening2 = await openStore();
67500
68182
  if (isClosed()) {
67501
68183
  await accountManager.dispose();
67502
- throw new Error("The account loader is disposed");
68184
+ throw new HostRefusalError("The account loader is disposed");
67503
68185
  }
67504
68186
  if (opening2.status !== "ready") {
67505
- throw new Error("the account store closed while it was in use");
68187
+ throw new HostRefusalError(
68188
+ "the account store closed while it was in use"
68189
+ );
67506
68190
  }
67507
68191
  const credentials = createLocalAccountCredentials(accountManager, {
67508
68192
  repository: opening2.repository
67509
68193
  });
67510
68194
  refreshQueue = deps.createStoreRefreshQueue(
67511
68195
  {
67512
- logger: log14,
68196
+ logger: log15,
67513
68197
  refreshToken: (_auth, account) => credentials.refresh(account)
67514
68198
  },
67515
68199
  queueConfig
@@ -67521,7 +68205,7 @@ function createAuthLoader({
67521
68205
  if (isClosed() || opening !== void 0 && opening.status !== "ready") {
67522
68206
  await refreshQueue?.dispose();
67523
68207
  await accountManager.dispose();
67524
- throw new Error(
68208
+ throw new HostRefusalError(
67525
68209
  isClosed() ? "The account loader is disposed" : "the account store closed while it was in use"
67526
68210
  );
67527
68211
  }
@@ -67553,7 +68237,7 @@ function createAuthLoader({
67553
68237
  await accountManager.dispose();
67554
68238
  throw error;
67555
68239
  }
67556
- if (!published) throw new Error("The account loader is disposed");
68240
+ if (!published) throw new HostRefusalError("The account loader is disposed");
67557
68241
  assertOpen();
67558
68242
  refreshQueue?.start();
67559
68243
  if (publishSidebar) await publishSidebar();
@@ -67592,11 +68276,11 @@ function createAuthLoader({
67592
68276
  assertOpen();
67593
68277
  const claustrum = await loadCommonAuthClaustrum();
67594
68278
  assertOpen();
67595
- claustrum.assertHostSlotMatchesMode({
67596
- mode: "local",
67597
- auth,
67598
- provider: providerId
67599
- });
68279
+ if (claustrum.classifyHostSlot(auth, providerId) === "placeholder") {
68280
+ throw new HostRefusalError(
68281
+ "The host holds the vault placeholder; sign in to use local accounts."
68282
+ );
68283
+ }
67600
68284
  return auth;
67601
68285
  }
67602
68286
  async function runLoader(getAuth, provider2) {
@@ -67617,7 +68301,7 @@ function createAuthLoader({
67617
68301
  }
67618
68302
  if (opening.status === "ready") {
67619
68303
  if (!isOAuthAuth(auth) && !readAuthority2) {
67620
- log14.warn(
68304
+ log15.warn(
67621
68305
  "The host holds no Antigravity sign-in; the account store is left untouched"
67622
68306
  );
67623
68307
  return {};
@@ -67629,33 +68313,30 @@ function createAuthLoader({
67629
68313
  return finishLoad(provider2);
67630
68314
  }
67631
68315
  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
- });
68316
+ const refusal3 = openingFailure(opening);
67636
68317
  try {
67637
68318
  await client.tui.showToast({
67638
- body: { message, variant: "error", duration: 3e4 }
68319
+ body: {
68320
+ message: refusal3.message,
68321
+ variant: "error",
68322
+ duration: 3e4
68323
+ }
67639
68324
  });
67640
68325
  } catch {
67641
68326
  }
67642
- throw new Error(message);
68327
+ throw refusal3;
67643
68328
  }
67644
68329
  if (!isOAuthAuth(auth)) {
67645
68330
  let storedAccounts;
67646
68331
  try {
67647
68332
  storedAccounts = await deps.loadAccounts();
67648
68333
  } catch (error) {
68334
+ const refusal3 = loaderFailure(error);
67649
68335
  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
68336
  try {
67656
68337
  await client.tui.showToast({
67657
68338
  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}.` : ""}`,
68339
+ message: refusal3.message,
67659
68340
  variant: "error",
67660
68341
  duration: 3e4
67661
68342
  }
@@ -67663,7 +68344,7 @@ function createAuthLoader({
67663
68344
  } catch {
67664
68345
  }
67665
68346
  }
67666
- throw error;
68347
+ throw refusal3;
67667
68348
  }
67668
68349
  assertOpen();
67669
68350
  const drift = detectAuthStorageDrift(auth, storedAccounts);
@@ -67679,12 +68360,12 @@ function createAuthLoader({
67679
68360
  expires: auth.expires ?? 0
67680
68361
  }
67681
68362
  });
67682
- log14.info("Restored Antigravity OAuth auth from account storage", {
68363
+ log15.info("Restored Antigravity OAuth auth from account storage", {
67683
68364
  reason: drift.reason,
67684
68365
  email: drift.account.email
67685
68366
  });
67686
68367
  } catch (error) {
67687
- log14.warn(
68368
+ log15.warn(
67688
68369
  "Failed to restore Antigravity OAuth auth from account storage",
67689
68370
  { error: String(error) }
67690
68371
  );
@@ -67732,44 +68413,54 @@ function createAuthLoader({
67732
68413
  // matches the host's `LoaderResult.fetch` signature exactly
67733
68414
  // (no `this` binding) so behavior is preserved.
67734
68415
  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;
68416
+ try {
67747
68417
  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;
68418
+ const authority = await readAuthority2?.() ?? "local";
68419
+ assertOpen();
68420
+ if (authority === "unreadable")
68421
+ throw new HostRefusalError(unavailableMessage);
68422
+ if (authority === "vault" || authority === "host") {
68423
+ currentRequestSource = "vault";
68424
+ if (!createVaultFetch)
68425
+ throw new HostRefusalError(unavailableMessage);
68426
+ vaultFetchRuntime ??= createVaultFetch().catch((error) => {
68427
+ vaultFetchRuntime = null;
68428
+ throw error;
67759
68429
  });
67760
- localRequestReload = started;
68430
+ const vaultRuntime = await vaultFetchRuntime;
68431
+ assertOpen();
68432
+ return vaultRuntime.fetch(input2, init, onResponseHandoff);
67761
68433
  }
67762
- await localRequestReload;
67763
- assertOpen();
67764
- if (await readAuthority2() !== "local")
67765
- throw new Error(unavailableMessage);
67766
- assertOpen();
68434
+ if (localUnavailable) {
68435
+ return fetchWithoutLocalAccounts(input2, init, fetchImpl);
68436
+ }
68437
+ if (readAuthority2 && (localRequestReload || currentRequestSource !== "local" || !fetchRuntime)) {
68438
+ if (!latestGetAuth)
68439
+ throw new HostRefusalError(
68440
+ "The host sign-in reader could not be read."
68441
+ );
68442
+ if (!localRequestReload) {
68443
+ const started = reload(latestGetAuth).finally(() => {
68444
+ if (localRequestReload === started) localRequestReload = null;
68445
+ });
68446
+ localRequestReload = started;
68447
+ }
68448
+ await localRequestReload;
68449
+ assertOpen();
68450
+ if (await readAuthority2() !== "local")
68451
+ throw new HostRefusalError(unavailableMessage);
68452
+ assertOpen();
68453
+ }
68454
+ if (localUnavailable)
68455
+ return fetchWithoutLocalAccounts(input2, init, fetchImpl);
68456
+ if (currentRequestSource !== "local" || !fetchRuntime)
68457
+ throw new HostRefusalError(
68458
+ "The local account runtime is not ready."
68459
+ );
68460
+ return fetchRuntime.fetch(input2, init, onResponseHandoff);
68461
+ } catch (error) {
68462
+ throw loaderFailure(error);
67767
68463
  }
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
68464
  })
67774
68465
  };
67775
68466
  }
@@ -67800,7 +68491,9 @@ function createAuthLoader({
67800
68491
  await installRuntime(nextManager, getAuth, "pool-file");
67801
68492
  };
67802
68493
  async function authLoaderCallable(getAuth, provider2) {
67803
- return runLoader(getAuth, provider2);
68494
+ return runLoader(getAuth, provider2).catch((error) => {
68495
+ throw loaderFailure(error);
68496
+ });
67804
68497
  }
67805
68498
  async function reload(getAuth) {
67806
68499
  assertOpen();
@@ -68116,7 +68809,7 @@ function registerAntigravityCommands(config) {
68116
68809
  }
68117
68810
 
68118
68811
  // src/plugin/command-data.ts
68119
- import { createHash as createHash22 } from "node:crypto";
68812
+ import { createHash as createHash23 } from "node:crypto";
68120
68813
  var QUOTA_GROUP_LABELS = {
68121
68814
  gemini: "Gemini",
68122
68815
  "non-gemini": "Non-Gemini",
@@ -68174,7 +68867,7 @@ function toCommandAccountRow(entry) {
68174
68867
  };
68175
68868
  }
68176
68869
  function quotaAccountIdentity3(refreshToken) {
68177
- return createHash22("sha256").update(refreshToken).digest("hex").slice(0, 16);
68870
+ return createHash23("sha256").update(refreshToken).digest("hex").slice(0, 16);
68178
68871
  }
68179
68872
  function projectCommandAccountRows(storage) {
68180
68873
  if (!storage) return [];
@@ -68357,7 +69050,13 @@ init_dist();
68357
69050
  init_debug();
68358
69051
  init_logger4();
68359
69052
  init_vault_request_credentials();
68360
- var log15 = createLogger4("fetch-interceptor");
69053
+ var log16 = createLogger4("fetch-interceptor");
69054
+ var failureLog2 = createLogger("fetch-interceptor");
69055
+ function fetchFailure(error, input2, init) {
69056
+ const signal = init?.signal ?? (input2 instanceof Request ? input2.signal : void 0);
69057
+ if (signal?.aborted && error === signal.reason) return error;
69058
+ return hostFailure(error, (diagnostic) => failureLog2.error(diagnostic));
69059
+ }
68361
69060
  var defaultAgyTransport = (url, init, options) => fetchWithAgyCliTransport(url, init, options);
68362
69061
  var defaultFetchImpl = (input2, init) => globalThis.fetch(input2, init);
68363
69062
  function poolFileCredentials(accountManager, client, providerId) {
@@ -68411,14 +69110,14 @@ function openCode1EngineCollaborators(common) {
68411
69110
  // the engine calls.
68412
69111
  debug: debug_exports,
68413
69112
  dump: { dumpRequest: dumpGeminiRequest },
68414
- logger: log15,
69113
+ logger: log16,
68415
69114
  classifyAccessError: extractAccountAccessErrorDetails,
68416
69115
  notify: (message, variant) => client.tui.showToast({ body: { message, variant } }),
68417
69116
  onRouting: common.onRouting ?? ((sessionId, entry) => {
68418
69117
  void upsertSidebarActiveRouting(sessionId, entry, {
68419
69118
  authoritative: true
68420
69119
  }).catch((error) => {
68421
- log15.debug("sidebar-routing-upsert-failed", {
69120
+ log16.debug("sidebar-routing-upsert-failed", {
68422
69121
  sessionId,
68423
69122
  error: String(error)
68424
69123
  });
@@ -68444,7 +69143,7 @@ function createFetchInterceptor(context) {
68444
69143
  const refreshQuotaAfterSuccess = createLocalQuotaRefresh(
68445
69144
  accountManager,
68446
69145
  quotaManager,
68447
- log15
69146
+ log16
68448
69147
  );
68449
69148
  const executor = createRequestExecutor({
68450
69149
  assertAdmission: context.assertAdmission,
@@ -68492,14 +69191,20 @@ function createFetchInterceptor(context) {
68492
69191
  let retirePromise;
68493
69192
  const entering = /* @__PURE__ */ new Set();
68494
69193
  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);
69194
+ try {
69195
+ await context.assertAdmission?.();
69196
+ if (disposed)
69197
+ throw new HostRefusalError("The local request runtime is disposed");
69198
+ if (accountSource.kind === "pool-file") {
69199
+ const latestAuth = await getAuth();
69200
+ if (disposed)
69201
+ throw new HostRefusalError("The local request runtime is disposed");
69202
+ if (!isOAuthAuth(latestAuth)) return upstreamFetch(input2, init);
69203
+ }
69204
+ return await executor.execute(input2, init, { onResponseHandoff });
69205
+ } catch (error) {
69206
+ throw fetchFailure(error, input2, init);
68501
69207
  }
68502
- return executor.execute(input2, init, { onResponseHandoff });
68503
69208
  }
68504
69209
  async function fetch(input2, init, onResponseHandoff) {
68505
69210
  if (disposed) {
@@ -68566,7 +69271,9 @@ function createVaultFetchInterceptor(context) {
68566
69271
  async function fetch(input2, init) {
68567
69272
  if (!isGenerativeLanguageRequest(input2)) return upstreamFetch(input2, init);
68568
69273
  if (disposed) throw new Error("The vault request runtime is disposed");
68569
- return executor.execute(input2, init);
69274
+ return executor.execute(input2, init).catch((error) => {
69275
+ throw fetchFailure(error, input2, init);
69276
+ });
68570
69277
  }
68571
69278
  function dispose() {
68572
69279
  disposed = true;
@@ -68591,7 +69298,7 @@ init_logger4();
68591
69298
 
68592
69299
  // src/plugin/search.ts
68593
69300
  init_logger4();
68594
- var log16 = createLogger4("search");
69301
+ var log17 = createLogger4("search");
68595
69302
  function formatSearchResult(result) {
68596
69303
  const lines = [];
68597
69304
  lines.push("## Search Results\n");
@@ -68719,7 +69426,7 @@ ${urlList}`;
68719
69426
  requestType: "agent"
68720
69427
  };
68721
69428
  const url = `${ANTIGRAVITY_ENDPOINT}/v1internal:generateContent`;
68722
- log16.debug("Executing search", {
69429
+ log17.debug("Executing search", {
68723
69430
  query,
68724
69431
  urlCount: urls?.length ?? 0,
68725
69432
  thinking
@@ -68742,7 +69449,7 @@ ${urlList}`;
68742
69449
  );
68743
69450
  if (!response.ok) {
68744
69451
  const errorText3 = await response.text();
68745
- log16.debug("Search API error", {
69452
+ log17.debug("Search API error", {
68746
69453
  status: response.status,
68747
69454
  error: errorText3
68748
69455
  });
@@ -68755,14 +69462,14 @@ ${errorText3}
68755
69462
  Please try again with a different query.`;
68756
69463
  }
68757
69464
  const data = await response.json();
68758
- log16.debug("Search response received", { hasResponse: !!data.response });
69465
+ log17.debug("Search response received", { hasResponse: !!data.response });
68759
69466
  const result = parseSearchResponse(data);
68760
69467
  const formatted = formatSearchResult(result);
68761
- log16.debug("Search response formatted", { resultLength: formatted.length });
69468
+ log17.debug("Search response formatted", { resultLength: formatted.length });
68762
69469
  return formatted;
68763
69470
  } catch (error) {
68764
69471
  const message = error instanceof Error ? error.message : String(error);
68765
- log16.debug("Search execution error", { error: message });
69472
+ log17.debug("Search execution error", { error: message });
68766
69473
  return `## Search Error
68767
69474
 
68768
69475
  Failed to execute search: ${message}. Please try again with a different query.`;
@@ -68770,7 +69477,7 @@ Failed to execute search: ${message}. Please try again with a different query.`;
68770
69477
  }
68771
69478
 
68772
69479
  // src/plugin/google-search-tool.ts
68773
- var log17 = createLogger4("plugin");
69480
+ var log18 = createLogger4("plugin");
68774
69481
  function createGoogleSearchTool({
68775
69482
  getAuth,
68776
69483
  client,
@@ -68792,7 +69499,7 @@ function createGoogleSearchTool({
68792
69499
  if (mayStartLocalWork && !await mayStartLocalWork()) {
68793
69500
  return "Google Search is not available through local credentials while vault custody is active or unreadable.";
68794
69501
  }
68795
- log17.debug("Google Search tool called", {
69502
+ log18.debug("Google Search tool called", {
68796
69503
  query: args.query,
68797
69504
  urlCount: args.urls?.length ?? 0
68798
69505
  });
@@ -69042,12 +69749,12 @@ init_storage();
69042
69749
  init_vault_custody();
69043
69750
  var logger2 = createLogger4("plugin");
69044
69751
  function quotaAccountIdentity4(refreshToken) {
69045
- return createHash23("sha256").update(refreshToken).digest("hex").slice(0, 16);
69752
+ return createHash24("sha256").update(refreshToken).digest("hex").slice(0, 16);
69046
69753
  }
69047
69754
  function registerQuotaManagerProducer(lifecycle, quotaManager) {
69048
69755
  lifecycle.register({ dispose: () => quotaManager.dispose() }, "producer");
69049
69756
  }
69050
- var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
69757
+ var createAntigravityPluginRuntime = (providerId, options = {}) => async (input2) => {
69051
69758
  const dependencies = resolvePluginDependencies(
69052
69759
  options.dependencies
69053
69760
  );
@@ -69159,8 +69866,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
69159
69866
  source,
69160
69867
  pool: createOpenCodeVaultAccountPool({
69161
69868
  source,
69162
- durable: { source, readState: () => vaultCustody.readState() },
69163
- grantPrincipal: () => vaultCustody.grantPrincipal()
69869
+ durable: { source, readState: () => vaultCustody.readState() }
69164
69870
  })
69165
69871
  };
69166
69872
  return vaultPool;
@@ -69636,7 +70342,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
69636
70342
  return createVaultFetchInterceptor({
69637
70343
  assertAdmission: async () => {
69638
70344
  if (!["host", "vault"].includes(await readAuthority2()))
69639
- throw new Error(unavailableMessage);
70345
+ throw new HostRefusalError(unavailableMessage);
69640
70346
  },
69641
70347
  client,
69642
70348
  config,
@@ -69662,7 +70368,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
69662
70368
  createFetch: ({ accountManager, getAuth, source }) => createFetchInterceptor({
69663
70369
  assertAdmission: async () => {
69664
70370
  if (await readAuthority2() !== "local")
69665
- throw new Error(unavailableMessage);
70371
+ throw new HostRefusalError(unavailableMessage);
69666
70372
  },
69667
70373
  client,
69668
70374
  directory,
@@ -69825,6 +70531,13 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
69825
70531
  }
69826
70532
  };
69827
70533
  };
70534
+ var createAntigravityPlugin = (providerId, options = {}) => {
70535
+ const load = createAntigravityPluginRuntime(providerId, options);
70536
+ return (input2) => load(input2).catch((error) => {
70537
+ if (error instanceof RuntimeLayoutRefusal) throw error;
70538
+ throw hostFailure(error, (diagnostic) => logger2.error(diagnostic));
70539
+ });
70540
+ };
69828
70541
  var AntigravityCLIOAuthPlugin = createAntigravityPlugin(
69829
70542
  ANTIGRAVITY_PROVIDER_ID
69830
70543
  );