@cortexkit/opencode-antigravity-auth 3.0.25 → 3.0.27

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 (66) hide show
  1. package/dist/cli.js +61 -8
  2. package/dist/cli.js.map +2 -2
  3. package/dist/cli.meta.json +7 -7
  4. package/dist/index.js +731 -209
  5. package/dist/index.js.map +3 -3
  6. package/dist/index.meta.json +22 -22
  7. package/dist/server.js +952 -335
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/ga/server/index.d.ts +3 -1
  11. package/dist/src/ga/server/index.d.ts.map +1 -1
  12. package/dist/src/ga/server/index.js +89 -6
  13. package/dist/src/ga/server/index.js.map +1 -1
  14. package/dist/src/ga/server/pool-login.d.ts.map +1 -1
  15. package/dist/src/ga/server/pool-login.js +19 -3
  16. package/dist/src/ga/server/pool-login.js.map +1 -1
  17. package/dist/src/plugin/background-vault-quota-refresh.js +1 -1
  18. package/dist/src/plugin/background-vault-quota-refresh.js.map +1 -1
  19. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  20. package/dist/src/plugin/fetch-interceptor.js +4 -2
  21. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  22. package/dist/src/plugin/ga-location-services.d.ts +1 -1
  23. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  24. package/dist/src/plugin/ga-location-services.js +30 -21
  25. package/dist/src/plugin/ga-location-services.js.map +1 -1
  26. package/dist/src/plugin/index.js +2 -2
  27. package/dist/src/plugin/index.js.map +1 -1
  28. package/dist/src/plugin/request-helpers.d.ts +139 -0
  29. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  30. package/dist/src/plugin/request-helpers.js +512 -0
  31. package/dist/src/plugin/request-helpers.js.map +1 -1
  32. package/dist/src/plugin/request.d.ts.map +1 -1
  33. package/dist/src/plugin/request.js +219 -63
  34. package/dist/src/plugin/request.js.map +1 -1
  35. package/dist/src/plugin/shared/request-services.d.ts +1 -1
  36. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  37. package/dist/src/plugin/shared/request-services.js +36 -127
  38. package/dist/src/plugin/shared/request-services.js.map +1 -1
  39. package/dist/src/plugin/shared/vault-menu.d.ts +1 -1
  40. package/dist/src/plugin/shared/vault-menu.d.ts.map +1 -1
  41. package/dist/src/plugin/shared/vault-menu.js +4 -2
  42. package/dist/src/plugin/shared/vault-menu.js.map +1 -1
  43. package/dist/src/plugin/shared/vault-request-credentials.d.ts +11 -4
  44. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  45. package/dist/src/plugin/shared/vault-request-credentials.js +67 -16
  46. package/dist/src/plugin/shared/vault-request-credentials.js.map +1 -1
  47. package/dist/src/plugin/storage.d.ts.map +1 -1
  48. package/dist/src/plugin/storage.js +3 -1
  49. package/dist/src/plugin/storage.js.map +1 -1
  50. package/dist/types/src/ga/server/index.d.ts +3 -1
  51. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  52. package/dist/types/src/ga/server/pool-login.d.ts.map +1 -1
  53. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  54. package/dist/types/src/plugin/ga-location-services.d.ts +1 -1
  55. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  56. package/dist/types/src/plugin/request-helpers.d.ts +139 -0
  57. package/dist/types/src/plugin/request-helpers.d.ts.map +1 -1
  58. package/dist/types/src/plugin/request.d.ts.map +1 -1
  59. package/dist/types/src/plugin/shared/request-services.d.ts +1 -1
  60. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  61. package/dist/types/src/plugin/shared/vault-menu.d.ts +1 -1
  62. package/dist/types/src/plugin/shared/vault-menu.d.ts.map +1 -1
  63. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +11 -4
  64. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  65. package/dist/types/src/plugin/storage.d.ts.map +1 -1
  66. package/package.json +2 -2
package/dist/server.js CHANGED
@@ -1801,6 +1801,8 @@ function openMigrationStore(modules, paths, now, onStep) {
1801
1801
  }
1802
1802
  async function rowsOf(store) {
1803
1803
  const read = await store.read();
1804
+ if (read.status === "error" && read.kind === "snapshot-contended")
1805
+ throw new AccountStoreBusyError();
1804
1806
  if (read.status !== "ready")
1805
1807
  throw new AccountMigrationError("successor is not a ready public store");
1806
1808
  return read.rows;
@@ -2009,8 +2011,46 @@ function receipt(journal) {
2009
2011
  restartRequired: journal.sourceKind !== "absent" || journal.operation === "rollback"
2010
2012
  };
2011
2013
  }
2014
+ async function readAdmissionState(path5) {
2015
+ try {
2016
+ const bytes = await secureRead(path5);
2017
+ return { bytes, stamp: digest(bytes) };
2018
+ } catch (error) {
2019
+ if (errno(error) === "ENOENT")
2020
+ return { bytes: void 0, stamp: void 0 };
2021
+ throw error;
2022
+ }
2023
+ }
2012
2024
  async function currentSuccessor(store, paths, journal) {
2013
- const config = object(jsonBytes(await secureRead(paths.configPath)), "active config");
2025
+ for (let attempt = 0; attempt < ADMISSION_SNAPSHOT_ATTEMPTS; attempt++) {
2026
+ const configBytes = await secureRead(paths.configPath);
2027
+ let state;
2028
+ let snapshot2;
2029
+ let failure2;
2030
+ try {
2031
+ state = await readAdmissionState(paths.statePath);
2032
+ snapshot2 = {
2033
+ stateBytes: state.bytes,
2034
+ rows: await rowsOf(store),
2035
+ settings: await settingsOf(store)
2036
+ };
2037
+ } catch (error) {
2038
+ failure2 = { error };
2039
+ }
2040
+ const checkedConfigBytes = await secureRead(paths.configPath);
2041
+ const checkedState = await readAdmissionState(paths.statePath);
2042
+ if (digest(configBytes) !== digest(checkedConfigBytes) || state !== void 0 && state.stamp !== checkedState.stamp)
2043
+ continue;
2044
+ if (failure2)
2045
+ throw failure2.error;
2046
+ if (!snapshot2)
2047
+ throw new AccountMigrationError("active snapshot missing");
2048
+ return validateCurrentSuccessor(journal, configBytes, snapshot2.stateBytes, snapshot2.rows, snapshot2.settings);
2049
+ }
2050
+ throw new AccountStoreBusyError();
2051
+ }
2052
+ function validateCurrentSuccessor(journal, configBytes, stateBytes, rows, settings) {
2053
+ const config = object(jsonBytes(configBytes), "active config");
2014
2054
  if (config.version !== 1 || !Array.isArray(config.accounts))
2015
2055
  throw new AccountMigrationError("active config lacks its native roster");
2016
2056
  const pool = object(config.commonAuthPool, "active native pool");
@@ -2027,15 +2067,14 @@ async function currentSuccessor(store, paths, journal) {
2027
2067
  if (new Set(nativeIds).size !== nativeIds.length || Object.keys(entries).length !== nativeIds.length || Object.keys(entries).some((id) => !nativeIds.includes(id)))
2028
2068
  throw new AccountMigrationError("active native entry/roster presence differs");
2029
2069
  let stateAccounts = {};
2030
- if (await exists(paths.statePath)) {
2031
- const state = object(jsonBytes(await secureRead(paths.statePath)), "active state");
2070
+ if (stateBytes !== void 0) {
2071
+ const state = object(jsonBytes(stateBytes), "active state");
2032
2072
  if (state.version !== 1)
2033
2073
  throw new AccountMigrationError("active native state schema differs");
2034
2074
  stateAccounts = object(state.accounts, "active state accounts");
2035
2075
  }
2036
2076
  if (Object.keys(stateAccounts).length !== nativeIds.length || Object.keys(stateAccounts).some((id) => !nativeIds.includes(id)))
2037
2077
  throw new AccountMigrationError("active state contains orphan or missing credentials");
2038
- const rows = await rowsOf(store);
2039
2078
  if (!isDeepStrictEqual(rows.map((row) => row.id), nativeIds))
2040
2079
  throw new AccountMigrationError("public and native active roster order differs");
2041
2080
  rows.forEach((row) => {
@@ -2044,10 +2083,10 @@ async function currentSuccessor(store, paths, journal) {
2044
2083
  if (entry.credentialEpoch !== rowRef(row).credentialEpoch || Object.hasOwn(entry, "quota") !== (row.quota !== void 0) || row.quota !== void 0 && !isDeepStrictEqual(entry.quota, row.quota))
2045
2084
  throw new AccountMigrationError("active native epoch or quota presence differs from public row");
2046
2085
  });
2047
- const settings = await settingsOf(store);
2048
2086
  if (!isDeepStrictEqual(decodeAccountStoreGeneration(settings[ACCOUNT_STORE_GENERATION_SETTINGS_KEY]), generationJson(journal)))
2049
2087
  throw new AccountMigrationError("active generation setting differs from journal");
2050
2088
  decodeRoutingSettings(settings[ROUTING_SETTINGS_KEY]);
2089
+ return settings;
2051
2090
  }
2052
2091
  function openAdmissionStore(modules, paths, now) {
2053
2092
  return modules.store.openPoolStore({
@@ -2175,11 +2214,13 @@ async function readAccountStoreAdmission(legacyPath, modules, now, expectedGener
2175
2214
  if (!journal)
2176
2215
  throw new AccountMigrationError("active serving journal missing");
2177
2216
  const store = openAdmissionStore(modules, binding.paths, now);
2178
- await currentSuccessor(store, binding.paths, journal);
2179
- if ((await settingsOf(store))[MANAGEMENT_SETTINGS_KEY] !== void 0)
2217
+ const settings = await currentSuccessor(store, binding.paths, journal);
2218
+ if (settings[MANAGEMENT_SETTINGS_KEY] !== void 0)
2180
2219
  return { status: "pending" };
2181
2220
  return { status: "active", receipt: binding.receipt, paths: binding.paths };
2182
2221
  } catch (error) {
2222
+ if (error instanceof AccountStoreBusyError)
2223
+ return { status: "busy", retryable: true };
2183
2224
  return {
2184
2225
  status: "error",
2185
2226
  reason: error instanceof AccountMigrationError ? error.reason : "current credential serving validation failed"
@@ -3730,6 +3771,8 @@ async function initializePrivateEmptyGeneration(modules, paths, parentLease, man
3730
3771
  await expectedFreshArtifacts(paths, journal);
3731
3772
  await currentSuccessor(store, paths, journal);
3732
3773
  const admission = await readAccountStoreAdmission(paths.legacyPath, modules, options.now, journal.id);
3774
+ if (admission.status === "busy")
3775
+ throw new AccountStoreBusyError();
3733
3776
  if (admission.status !== "active" || !isDeepStrictEqual(admission.receipt, receipt(journal)))
3734
3777
  throw new AccountMigrationError("published empty generation is not admitted");
3735
3778
  await boundary?.("pointer:after-sync-before-stage-cleanup");
@@ -3865,7 +3908,7 @@ async function cleanupPointerStage(legacyPath, pointer, lease) {
3865
3908
  await unlink2(stage);
3866
3909
  return true;
3867
3910
  }
3868
- var AccountMigrationError, QUOTA_FIELDS, ACCOUNT_MIGRATION_PHASES, ACCOUNT_MIGRATION_MANAGEMENT_STEPS, ACCOUNT_STORE_GENERATION_SETTINGS_KEY, UUID, SHA256;
3911
+ var AccountMigrationError, QUOTA_FIELDS, ACCOUNT_MIGRATION_PHASES, ACCOUNT_MIGRATION_MANAGEMENT_STEPS, ACCOUNT_STORE_GENERATION_SETTINGS_KEY, UUID, SHA256, ADMISSION_SNAPSHOT_ATTEMPTS, AccountStoreBusyError;
3869
3912
  var init_account_migration = __esm({
3870
3913
  "../core/dist/account-migration.js"() {
3871
3914
  "use strict";
@@ -3897,6 +3940,14 @@ var init_account_migration = __esm({
3897
3940
  ACCOUNT_STORE_GENERATION_SETTINGS_KEY = "antigravityGeneration";
3898
3941
  UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
3899
3942
  SHA256 = /^[0-9a-f]{64}$/;
3943
+ ADMISSION_SNAPSHOT_ATTEMPTS = 3;
3944
+ AccountStoreBusyError = class extends Error {
3945
+ retryable = true;
3946
+ constructor() {
3947
+ super("The Antigravity account store is busy. Try again in a moment.");
3948
+ this.name = "AccountStoreBusyError";
3949
+ }
3950
+ };
3900
3951
  }
3901
3952
  });
3902
3953
 
@@ -29880,6 +29931,11 @@ function createVaultAccountPool(options) {
29880
29931
  };
29881
29932
  let firstRead = null;
29882
29933
  const clock2 = options.now ?? Date.now;
29934
+ const schedule2 = options.schedule ?? ((callback, delayMs) => {
29935
+ const timer = setTimeout(callback, delayMs);
29936
+ timer.unref?.();
29937
+ return () => clearTimeout(timer);
29938
+ });
29883
29939
  let readGeneration = 0;
29884
29940
  let firstReadStartedAt = null;
29885
29941
  const readOnce = () => {
@@ -29894,7 +29950,11 @@ function createVaultAccountPool(options) {
29894
29950
  firstRead = (async () => {
29895
29951
  await source.refresh();
29896
29952
  const rows = await rowsFromSource();
29897
- if (current()) selector.resetAccounts(rows);
29953
+ if (current())
29954
+ selector.replaceAccounts(rows, {
29955
+ keyOf: vaultAccountRowKey,
29956
+ refresh: refreshVaultAccountRow
29957
+ });
29898
29958
  })().then(
29899
29959
  () => {
29900
29960
  if (current()) firstReadStartedAt = null;
@@ -29909,39 +29969,64 @@ function createVaultAccountPool(options) {
29909
29969
  );
29910
29970
  return firstRead;
29911
29971
  };
29912
- const waitForFirstRoster = async () => {
29913
- let timer;
29972
+ const waitForRead = async (read, signal, remaining) => {
29973
+ let cancelTimer2;
29974
+ let detachAbort;
29914
29975
  try {
29915
- await Promise.race([
29916
- readOnce(),
29917
- new Promise((_, reject) => {
29918
- timer = setTimeout(
29919
- () => reject(
29920
- new Error(
29921
- "The vault roster is not available yet. Check vault access and try the request again."
29922
- )
29923
- ),
29924
- 2e3
29925
- );
29926
- timer.unref?.();
29976
+ return await Promise.race([
29977
+ read.then(() => true),
29978
+ new Promise((resolve28, reject) => {
29979
+ const abort = () => reject(signal?.reason);
29980
+ signal?.addEventListener("abort", abort, { once: true });
29981
+ detachAbort = () => signal?.removeEventListener("abort", abort);
29982
+ if (remaining !== void 0)
29983
+ cancelTimer2 = schedule2(() => resolve28(false), remaining);
29984
+ if (signal?.aborted) abort();
29927
29985
  })
29928
29986
  ]);
29929
29987
  } finally {
29930
- clearTimeout(timer);
29988
+ cancelTimer2?.();
29989
+ detachAbort?.();
29990
+ }
29991
+ };
29992
+ const waitForFirstRoster = async (signal) => {
29993
+ for (let attempt = 0; attempt < 2; attempt++) {
29994
+ signal?.throwIfAborted();
29995
+ const read = readOnce();
29996
+ const remaining = firstReadStartedAt === null ? VAULT_REFRESH_STALL_MS : Math.max(0, VAULT_REFRESH_STALL_MS - (clock2() - firstReadStartedAt));
29997
+ if (await waitForRead(read, signal, remaining)) return;
29931
29998
  }
29999
+ throw new Error(
30000
+ "The vault roster is not available yet. Check vault access and try the request again."
30001
+ );
29932
30002
  };
29933
30003
  return {
29934
30004
  selector,
29935
30005
  credentials,
29936
30006
  state,
29937
- async sync() {
30007
+ async sync(signal) {
29938
30008
  const pending = firstRead;
29939
- await waitForFirstRoster();
30009
+ await waitForFirstRoster(signal);
29940
30010
  if (pending !== null) await replace();
29941
30011
  },
29942
- async refresh() {
29943
- await waitForFirstRoster();
29944
- await source.refresh();
30012
+ syncCached: replace,
30013
+ async syncForDisplay(signal) {
30014
+ try {
30015
+ signal?.throwIfAborted();
30016
+ const read = readOnce();
30017
+ const remaining = firstReadStartedAt === null ? 0 : Math.max(
30018
+ 0,
30019
+ VAULT_DISPLAY_ROSTER_WAIT_MS - (clock2() - firstReadStartedAt)
30020
+ );
30021
+ await waitForRead(read, signal, remaining);
30022
+ } catch {
30023
+ }
30024
+ await replace();
30025
+ },
30026
+ async refresh(signal) {
30027
+ const discovering = firstRead === null || firstReadStartedAt !== null;
30028
+ await waitForFirstRoster(signal);
30029
+ if (!discovering) await waitForRead(source.refresh(), signal);
29945
30030
  await replace();
29946
30031
  },
29947
30032
  flush: async () => {
@@ -30041,7 +30126,7 @@ async function checkVaultQuota(input2) {
30041
30126
  }
30042
30127
  return { checked, notChecked: rows.length - checked };
30043
30128
  }
30044
- var VaultSendGrant, VAULT_REFRESH_STALL_MS;
30129
+ var VaultSendGrant, VAULT_REFRESH_STALL_MS, VAULT_DISPLAY_ROSTER_WAIT_MS;
30045
30130
  var init_vault_request_credentials = __esm({
30046
30131
  "src/plugin/shared/vault-request-credentials.ts"() {
30047
30132
  "use strict";
@@ -30067,6 +30152,7 @@ var init_vault_request_credentials = __esm({
30067
30152
  }
30068
30153
  };
30069
30154
  VAULT_REFRESH_STALL_MS = 3e4;
30155
+ VAULT_DISPLAY_ROSTER_WAIT_MS = 2e3;
30070
30156
  }
30071
30157
  });
30072
30158
 
@@ -32745,6 +32831,8 @@ async function assertLegacyPoolInUse(legacyPath) {
32745
32831
  }
32746
32832
  function refusalMessage2(admission) {
32747
32833
  switch (admission.status) {
32834
+ case "busy":
32835
+ return new AccountStoreBusyError().message;
32748
32836
  case "pending":
32749
32837
  return admission.operation === "rollback" ? `An account-store rollback is pending; rerun \`${ROLLBACK_COMMAND}\`.` : `An account-store migration is pending; stop every Antigravity process and rerun \`${MIGRATE_COMMAND}\`.`;
32750
32838
  case "inactive":
@@ -37848,7 +37936,7 @@ var BackgroundVaultQuotaRefresh = class {
37848
37936
  outcome.stage = "roster";
37849
37937
  const { source, pool } = await this.options.currentVaultPool();
37850
37938
  await this.assertActive(controller);
37851
- await pool.sync();
37939
+ await pool.sync(controller.signal);
37852
37940
  await this.assertActive(controller);
37853
37941
  outcome.stage = "state";
37854
37942
  const state = await this.options.readProviderState();
@@ -41607,6 +41695,358 @@ function createNativeGoogleErrorResponse(options) {
41607
41695
  headers
41608
41696
  });
41609
41697
  }
41698
+ function extractAntigravityError(body) {
41699
+ if (!body || typeof body !== "object") return null;
41700
+ let target = body;
41701
+ if (Array.isArray(body)) {
41702
+ if (body.length === 0 || !body[0] || typeof body[0] !== "object" || Array.isArray(body[0])) {
41703
+ return null;
41704
+ }
41705
+ target = body[0];
41706
+ }
41707
+ const candidate = target.error;
41708
+ if (candidate && typeof candidate === "object" && !Array.isArray(candidate)) {
41709
+ return candidate;
41710
+ }
41711
+ return null;
41712
+ }
41713
+ var MAX_FINITE_WAIT_MS = BigInt(Math.ceil(Number.MAX_VALUE));
41714
+ var MAX_FINITE_WAIT_SECONDS = (MAX_FINITE_WAIT_MS + 999n) / 1000n;
41715
+ var MAX_FINITE_FORWARDING_MS = MAX_FINITE_WAIT_SECONDS * 1000n;
41716
+ var RFC_HTTP_DATE_REGEX = /^(?:Mon|Tue|Wed|Thu|Fri|Sat|Sun), \d{2} (?:Jan|Feb|Mar|Apr|May|Jun|Jul|Aug|Sep|Oct|Nov|Dec) \d{4} \d{2}:\d{2}:\d{2} GMT$/;
41717
+ function validateRetryAfterSecondsBigInt(raw) {
41718
+ if (raw === null || raw === void 0) return null;
41719
+ if (typeof raw === "bigint") {
41720
+ return raw >= 0n && raw <= MAX_FINITE_WAIT_SECONDS ? raw : null;
41721
+ }
41722
+ if (typeof raw === "number") {
41723
+ if (!Number.isFinite(raw) || raw < 0 || !Number.isInteger(raw)) {
41724
+ return null;
41725
+ }
41726
+ const b = BigInt(raw);
41727
+ return b <= MAX_FINITE_WAIT_SECONDS ? b : null;
41728
+ }
41729
+ if (typeof raw !== "string") return null;
41730
+ const trimmed = raw.trim();
41731
+ if (trimmed.length === 0) return null;
41732
+ if (/^\d+$/.test(trimmed)) {
41733
+ if (trimmed.length > 309) return null;
41734
+ const val = BigInt(trimmed);
41735
+ return val >= 0n && val <= MAX_FINITE_WAIT_SECONDS ? val : null;
41736
+ }
41737
+ if (RFC_HTTP_DATE_REGEX.test(trimmed)) {
41738
+ const parsedDate = Date.parse(trimmed);
41739
+ if (!Number.isNaN(parsedDate)) {
41740
+ const roundtrip = new Date(parsedDate).toUTCString();
41741
+ if (roundtrip === trimmed) {
41742
+ const diffSec = Math.ceil((parsedDate - Date.now()) / 1e3);
41743
+ if (diffSec >= 0 && Number.isSafeInteger(diffSec)) {
41744
+ return BigInt(diffSec);
41745
+ }
41746
+ }
41747
+ }
41748
+ }
41749
+ return null;
41750
+ }
41751
+ function validateRetryAfterMsBigInt(raw) {
41752
+ if (raw === null || raw === void 0) return null;
41753
+ if (typeof raw === "bigint") {
41754
+ return raw >= 0n && raw <= MAX_FINITE_FORWARDING_MS ? raw : null;
41755
+ }
41756
+ if (typeof raw === "number") {
41757
+ if (!Number.isFinite(raw) || raw < 0 || !Number.isInteger(raw)) {
41758
+ return null;
41759
+ }
41760
+ const b = BigInt(raw);
41761
+ return b <= MAX_FINITE_FORWARDING_MS ? b : null;
41762
+ }
41763
+ if (typeof raw !== "string") return null;
41764
+ const trimmed = raw.trim();
41765
+ if (trimmed.length === 0 || !/^\d+$/.test(trimmed)) return null;
41766
+ if (trimmed.length > 309) return null;
41767
+ const val = BigInt(trimmed);
41768
+ return val >= 0n && val <= MAX_FINITE_FORWARDING_MS ? val : null;
41769
+ }
41770
+ function deriveRetryHeaderPairFromMs(ms) {
41771
+ if (typeof ms !== "bigint" || ms < 0n || ms > MAX_FINITE_FORWARDING_MS) {
41772
+ throw new RangeError(
41773
+ `deriveRetryHeaderPairFromMs: ms must be a non-negative BigInt <= MAX_FINITE_FORWARDING_MS (got ${String(ms)})`
41774
+ );
41775
+ }
41776
+ const sec = (ms + 999n) / 1000n;
41777
+ return {
41778
+ "retry-after": sec.toString(),
41779
+ "retry-after-ms": ms.toString()
41780
+ };
41781
+ }
41782
+ function deriveRetryHeaderPairFromSeconds(sec) {
41783
+ if (typeof sec !== "bigint" || sec < 0n || sec > MAX_FINITE_WAIT_SECONDS) {
41784
+ throw new RangeError(
41785
+ `deriveRetryHeaderPairFromSeconds: sec must be a non-negative BigInt <= MAX_FINITE_WAIT_SECONDS (got ${String(sec)})`
41786
+ );
41787
+ }
41788
+ const ms = sec * 1000n;
41789
+ return {
41790
+ "retry-after": sec.toString(),
41791
+ "retry-after-ms": ms.toString()
41792
+ };
41793
+ }
41794
+ function collectForwardedHeaders(sourceHeaders) {
41795
+ if (!sourceHeaders) return {};
41796
+ const getHeader2 = (name) => {
41797
+ if (typeof sourceHeaders.get === "function") {
41798
+ return sourceHeaders.get(name);
41799
+ }
41800
+ const record3 = sourceHeaders;
41801
+ for (const [key, value] of Object.entries(record3)) {
41802
+ if (key.toLowerCase() === name) return value;
41803
+ }
41804
+ return void 0;
41805
+ };
41806
+ const rawRetryAfterMs = getHeader2("retry-after-ms");
41807
+ const validMs = validateRetryAfterMsBigInt(rawRetryAfterMs);
41808
+ if (validMs !== null) {
41809
+ return deriveRetryHeaderPairFromMs(validMs);
41810
+ }
41811
+ const rawRetryAfter = getHeader2("retry-after");
41812
+ const validSec = validateRetryAfterSecondsBigInt(rawRetryAfter);
41813
+ if (validSec !== null) {
41814
+ return deriveRetryHeaderPairFromSeconds(validSec);
41815
+ }
41816
+ return {};
41817
+ }
41818
+ function isQuotaError(status, message, details) {
41819
+ if (status === 429) return true;
41820
+ const lower = (message ?? "").toLowerCase();
41821
+ if (hasQuotaResetClause(lower)) return true;
41822
+ return hasStructuredQuotaReason(details);
41823
+ }
41824
+ var QUOTA_REASON_CODES = /* @__PURE__ */ new Set([
41825
+ "QUOTA_EXHAUSTED",
41826
+ "RATE_LIMIT_EXCEEDED",
41827
+ "RESOURCE_EXHAUSTED"
41828
+ ]);
41829
+ function hasQuotaResetClause(lowerMessage) {
41830
+ if (lowerMessage.length === 0) return false;
41831
+ if (extractResetDurationFromText(lowerMessage) === null) return false;
41832
+ return lowerMessage.includes("quota") || lowerMessage.includes("rate limit") || lowerMessage.includes("rate_limit") || lowerMessage.includes("resource_exhausted");
41833
+ }
41834
+ function hasStructuredQuotaReason(details) {
41835
+ if (!Array.isArray(details)) return false;
41836
+ return details.some((detail) => {
41837
+ if (!detail || typeof detail !== "object") return false;
41838
+ const record3 = detail;
41839
+ const type = record3["@type"];
41840
+ if (typeof type === "string" && type.includes("google.rpc.QuotaFailure"))
41841
+ return true;
41842
+ const reason = record3.reason;
41843
+ if (typeof reason === "string" && QUOTA_REASON_CODES.has(reason))
41844
+ return true;
41845
+ const nested = record3.details;
41846
+ return Array.isArray(nested) ? hasStructuredQuotaReason(nested) : false;
41847
+ });
41848
+ }
41849
+ var RESET_CLAUSE_REGEX = /\b(?:quota\s+)?resets?\s+(?:in|after)\s+(?=\d+(?:\.\d+)?[ \t]*(?:ms|[dhms]))((?:(?:\d+(?:\.\d+)?[ \t]*d)[ \t]*)?(?:(?:\d+(?:\.\d+)?[ \t]*h)[ \t]*)?(?:(?:\d+(?:\.\d+)?[ \t]*m(?!s))[ \t]*)?(?:(?:\d+(?:\.\d+)?[ \t]*s)[ \t]*)?(?:(?:\d+(?:\.\d+)?[ \t]*ms))?)(?![a-zA-Z0-9_-])/gi;
41850
+ function extractResetDurationFromText(text2) {
41851
+ if (typeof text2 !== "string" || text2.length === 0) return null;
41852
+ const regex = new RegExp(RESET_CLAUSE_REGEX.source, "i");
41853
+ const match = text2.match(regex);
41854
+ if (!match?.[1]) return null;
41855
+ const raw = match[1].trim().replace(/[.,;:]+$/, "");
41856
+ return raw.length > 0 ? raw : null;
41857
+ }
41858
+ function normalizeResetDuration(text2) {
41859
+ if (typeof text2 !== "string" || text2.length === 0) return text2;
41860
+ return text2.replace(RESET_CLAUSE_REGEX, (_match, rawDuration) => {
41861
+ if (!rawDuration) return _match;
41862
+ const duration = String(rawDuration).match(/^(.*?)([ \t]*)$/);
41863
+ if (!duration) return _match;
41864
+ const spaced = (duration[1] ?? "").replace(
41865
+ /(\d+(?:\.\d+)?)[ \t]*(ms|[dhms])(?=\d)/gi,
41866
+ "$1$2 "
41867
+ );
41868
+ return `quota resets in ${spaced}${duration[2] ?? ""}`;
41869
+ });
41870
+ }
41871
+ var DURATION_REGEX = /^(?:(\d+(?:\.\d+)?|\.\d+)[ \t]*d)?(?:[ \t]*(\d+(?:\.\d+)?|\.\d+)[ \t]*h)?(?:[ \t]*(\d+(?:\.\d+)?|\.\d+)[ \t]*m(?!s))?(?:[ \t]*(\d+(?:\.\d+)?|\.\d+)[ \t]*s)?(?:[ \t]*(\d+(?:\.\d+)?|\.\d+)[ \t]*ms)?$/i;
41872
+ function parseDecimalComponent(str, multMs) {
41873
+ const parts = str.split(".");
41874
+ const intStr = parts[0] ?? "";
41875
+ const fracStr = parts[1] ?? "";
41876
+ const effectiveIntStr = intStr.replace(/^0+/, "");
41877
+ if (effectiveIntStr.length > 15) return null;
41878
+ if (str.length > 60) return null;
41879
+ const intPart = intStr.length > 0 ? BigInt(intStr) : 0n;
41880
+ return { intPart, fracStr, mult: multMs };
41881
+ }
41882
+ function parseDurationToMsBigInt(duration, options) {
41883
+ if (typeof duration !== "string") return null;
41884
+ const trimmed = duration.trim();
41885
+ if (trimmed.length === 0) return null;
41886
+ let dStr;
41887
+ let hStr;
41888
+ let mStr;
41889
+ let sStr;
41890
+ let msStr;
41891
+ const match = trimmed.match(DURATION_REGEX);
41892
+ if (match) {
41893
+ ;
41894
+ [, dStr, hStr, mStr, sStr, msStr] = match;
41895
+ }
41896
+ if (dStr === void 0 && hStr === void 0 && mStr === void 0 && sStr === void 0 && msStr === void 0) {
41897
+ if (options?.allowBareSeconds && /^(?:\d+(?:\.\d+)?|\.\d+)$/.test(trimmed)) {
41898
+ sStr = trimmed;
41899
+ } else {
41900
+ return null;
41901
+ }
41902
+ }
41903
+ const rawComponents = [];
41904
+ if (dStr !== void 0) rawComponents.push({ str: dStr, mult: 86400000n });
41905
+ if (hStr !== void 0) rawComponents.push({ str: hStr, mult: 3600000n });
41906
+ if (mStr !== void 0) rawComponents.push({ str: mStr, mult: 60000n });
41907
+ if (sStr !== void 0) rawComponents.push({ str: sStr, mult: 1000n });
41908
+ if (msStr !== void 0) rawComponents.push({ str: msStr, mult: 1n });
41909
+ if (rawComponents.length === 0) return null;
41910
+ let maxFracDigits = 0;
41911
+ const parsedComponents = [];
41912
+ for (const rc of rawComponents) {
41913
+ const parsed = parseDecimalComponent(rc.str, rc.mult);
41914
+ if (!parsed) return null;
41915
+ if (parsed.fracStr.length > maxFracDigits) {
41916
+ maxFracDigits = parsed.fracStr.length;
41917
+ }
41918
+ parsedComponents.push(parsed);
41919
+ }
41920
+ const commonDenominator = 10n ** BigInt(maxFracDigits);
41921
+ let totalScaledNumerator = 0n;
41922
+ for (const c of parsedComponents) {
41923
+ const fracLen = BigInt(c.fracStr.length);
41924
+ const fracVal = c.fracStr.length > 0 ? BigInt(c.fracStr) : 0n;
41925
+ const scaleFactor = 10n ** (BigInt(maxFracDigits) - fracLen);
41926
+ const numerator = (c.intPart * commonDenominator + fracVal * scaleFactor) * c.mult;
41927
+ totalScaledNumerator += numerator;
41928
+ }
41929
+ if (totalScaledNumerator === 0n) {
41930
+ return options?.allowZero ? 0n : null;
41931
+ }
41932
+ const quotient = totalScaledNumerator / commonDenominator;
41933
+ const remainder = totalScaledNumerator % commonDenominator;
41934
+ let rounded = remainder * 2n >= commonDenominator ? quotient + 1n : quotient;
41935
+ if (rounded === 0n) {
41936
+ rounded = 1n;
41937
+ }
41938
+ if (rounded > MAX_FINITE_FORWARDING_MS) {
41939
+ return null;
41940
+ }
41941
+ return rounded;
41942
+ }
41943
+ function resolveRetryMetadata(options) {
41944
+ const {
41945
+ details,
41946
+ message,
41947
+ status,
41948
+ headers,
41949
+ retryAfterMs,
41950
+ resetAfterMs,
41951
+ retryAfterSeconds,
41952
+ allowZero,
41953
+ allowBareSeconds
41954
+ } = options;
41955
+ const bodyParserOptions = {
41956
+ allowZero,
41957
+ allowBareSeconds
41958
+ };
41959
+ if (Array.isArray(details)) {
41960
+ for (const entry of details) {
41961
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
41962
+ const type = entry["@type"];
41963
+ if (typeof type === "string" && type.includes("google.rpc.RetryInfo")) {
41964
+ const retryDelay = entry.retryDelay;
41965
+ if (typeof retryDelay === "string") {
41966
+ const ms = parseDurationToMsBigInt(retryDelay, bodyParserOptions);
41967
+ if (ms !== null) {
41968
+ return { delayMs: ms };
41969
+ }
41970
+ } else if (typeof retryDelay === "number") {
41971
+ if (Number.isFinite(retryDelay) && retryDelay >= 0) {
41972
+ const scaled = retryDelay * 1e3;
41973
+ if (Number.isFinite(scaled)) {
41974
+ const rounded = Math.round(scaled);
41975
+ if (Number.isSafeInteger(rounded) && rounded >= 0) {
41976
+ if (retryDelay === 0) {
41977
+ if (allowZero) return { delayMs: 0n };
41978
+ } else {
41979
+ return { delayMs: BigInt(Math.max(1, rounded)) };
41980
+ }
41981
+ }
41982
+ }
41983
+ }
41984
+ }
41985
+ }
41986
+ }
41987
+ for (const entry of details) {
41988
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
41989
+ const metadata = entry.metadata;
41990
+ if (metadata && typeof metadata === "object" && !Array.isArray(metadata)) {
41991
+ const quotaResetDelay = metadata.quotaResetDelay;
41992
+ if (typeof quotaResetDelay === "string") {
41993
+ const ms = parseDurationToMsBigInt(quotaResetDelay, bodyParserOptions);
41994
+ if (ms !== null) {
41995
+ const quotaResetTime = typeof metadata.quotaResetTimeStamp === "string" ? metadata.quotaResetTimeStamp : typeof metadata.quotaResetTime === "string" ? metadata.quotaResetTime : void 0;
41996
+ return {
41997
+ delayMs: ms,
41998
+ ...quotaResetTime !== void 0 ? { quotaResetTime } : {}
41999
+ };
42000
+ }
42001
+ }
42002
+ }
42003
+ }
42004
+ }
42005
+ const validGaMs = validateRetryAfterMsBigInt(retryAfterMs);
42006
+ if (validGaMs !== null) {
42007
+ return { delayMs: validGaMs };
42008
+ }
42009
+ const validResetMs = validateRetryAfterMsBigInt(resetAfterMs);
42010
+ if (validResetMs !== null) {
42011
+ return { delayMs: validResetMs };
42012
+ }
42013
+ const validGaSec = validateRetryAfterSecondsBigInt(retryAfterSeconds);
42014
+ if (validGaSec !== null) {
42015
+ return { delayMs: validGaSec * 1000n };
42016
+ }
42017
+ if (isQuotaError(status, message, details) && typeof message === "string") {
42018
+ const rawDuration = extractResetDurationFromText(message);
42019
+ if (rawDuration !== null) {
42020
+ const ms = parseDurationToMsBigInt(rawDuration, bodyParserOptions);
42021
+ if (ms !== null) {
42022
+ return { delayMs: ms };
42023
+ }
42024
+ }
42025
+ }
42026
+ if (headers) {
42027
+ const getHeader2 = (name) => {
42028
+ if (typeof headers.get === "function") {
42029
+ return headers.get(name);
42030
+ }
42031
+ const record3 = headers;
42032
+ for (const [key, value] of Object.entries(record3)) {
42033
+ if (key.toLowerCase() === name) return value;
42034
+ }
42035
+ return void 0;
42036
+ };
42037
+ const rawMs = getHeader2("retry-after-ms");
42038
+ const validHeaderMs = validateRetryAfterMsBigInt(rawMs);
42039
+ if (validHeaderMs !== null) {
42040
+ return { delayMs: validHeaderMs };
42041
+ }
42042
+ const rawSec = getHeader2("retry-after");
42043
+ const validHeaderSec = validateRetryAfterSecondsBigInt(rawSec);
42044
+ if (validHeaderSec !== null) {
42045
+ return { delayMs: validHeaderSec * 1000n };
42046
+ }
42047
+ }
42048
+ return null;
42049
+ }
41610
42050
 
41611
42051
  // src/plugin/thinking-recovery.ts
41612
42052
  function isThinkingPart2(part) {
@@ -43327,10 +43767,12 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
43327
43767
  const debugText = wire.debug.isDebugTuiEnabled() && Array.isArray(debugLines) && debugLines.length > 0 ? formatDebugLinesForThinking(debugLines) : wire.signatures.keepThinking ? SYNTHETIC_THINKING_PLACEHOLDER : void 0;
43328
43768
  const cacheSignatures = shouldCacheThinkingSignatures(effectiveModel);
43329
43769
  if (!isJsonResponse && !isEventStreamResponse) {
43330
- wire.debug.logAntigravityDebugResponse(debugContext, response, {
43331
- note: "Non-JSON response (body omitted)"
43332
- });
43333
- return response;
43770
+ if (response.ok) {
43771
+ wire.debug.logAntigravityDebugResponse(debugContext, response, {
43772
+ note: "Non-JSON response (body omitted)"
43773
+ });
43774
+ return response;
43775
+ }
43334
43776
  }
43335
43777
  if (streaming && response.ok && isEventStreamResponse && response.body) {
43336
43778
  const headers = new Headers(response.headers);
@@ -43379,27 +43821,143 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
43379
43821
  headers
43380
43822
  });
43381
43823
  }
43382
- const responseFallback = response.clone();
43383
- try {
43824
+ if (!response.ok) {
43825
+ const projectIds = projectId ? [projectId] : void 0;
43384
43826
  const headers = new Headers(response.headers);
43385
- const text2 = await response.text();
43827
+ const initialForwarded = collectForwardedHeaders(headers);
43828
+ if (initialForwarded["retry-after"] !== void 0 && initialForwarded["retry-after-ms"] !== void 0) {
43829
+ headers.set("Retry-After", initialForwarded["retry-after"]);
43830
+ headers.set("retry-after", initialForwarded["retry-after"]);
43831
+ headers.set("retry-after-ms", initialForwarded["retry-after-ms"]);
43832
+ } else {
43833
+ headers.delete("Retry-After");
43834
+ headers.delete("retry-after");
43835
+ headers.delete("retry-after-ms");
43836
+ }
43837
+ let text2;
43838
+ try {
43839
+ text2 = await response.text();
43840
+ } catch (readError) {
43841
+ const sanitizedCause = readError instanceof Error || readError !== null && typeof readError === "object" ? redactCredentialError(readError, void 0, projectIds) : void 0;
43842
+ const safeMessage = sanitizedCause ? sanitizedCause.message : redactCredentialText(String(readError), void 0, projectIds);
43843
+ const scrubbedStatusText = redactCredentialText(
43844
+ response.statusText,
43845
+ void 0,
43846
+ projectIds
43847
+ );
43848
+ const plainHeaders = {};
43849
+ for (const [key, value] of headers.entries()) {
43850
+ plainHeaders[key] = redactCredentialText(value, void 0, projectIds);
43851
+ }
43852
+ if (initialForwarded["retry-after"] !== void 0 && initialForwarded["retry-after-ms"] !== void 0) {
43853
+ plainHeaders["retry-after"] = initialForwarded["retry-after"];
43854
+ plainHeaders["retry-after-ms"] = initialForwarded["retry-after-ms"];
43855
+ plainHeaders["Retry-After"] = initialForwarded["retry-after"];
43856
+ }
43857
+ const freshError = new Error(
43858
+ `Failed to read response body: ${safeMessage}`,
43859
+ sanitizedCause ? { cause: sanitizedCause } : void 0
43860
+ );
43861
+ Object.assign(freshError, {
43862
+ statusCode: response.status,
43863
+ status: response.status,
43864
+ statusText: scrubbedStatusText,
43865
+ headers: plainHeaders
43866
+ });
43867
+ throw freshError;
43868
+ }
43386
43869
  noteGeminiDumpResponse(dumpContext, response);
43387
43870
  appendGeminiDumpResponseText(dumpContext, text2);
43388
- if (!response.ok) {
43389
- let errorBody;
43871
+ const createSafeFallback = (bodyContent, contentTypeOverride) => {
43872
+ const fallbackHeaders = new Headers(headers);
43873
+ fallbackHeaders.delete("content-length");
43874
+ if (contentTypeOverride) {
43875
+ fallbackHeaders.set("content-type", contentTypeOverride);
43876
+ }
43877
+ const safeText = redactProjectIdText(bodyContent, projectIds);
43878
+ const fallbackResponse = new Response(safeText, {
43879
+ status: response.status,
43880
+ statusText: response.statusText,
43881
+ headers: fallbackHeaders
43882
+ });
43883
+ return redactCredentialResponse(
43884
+ fallbackResponse,
43885
+ void 0,
43886
+ safeText,
43887
+ projectIds
43888
+ );
43889
+ };
43890
+ try {
43891
+ let parsedBody = null;
43892
+ let isJson = false;
43390
43893
  try {
43391
- errorBody = JSON.parse(text2);
43894
+ parsedBody = JSON.parse(text2);
43895
+ isJson = true;
43392
43896
  } catch {
43393
- errorBody = { error: { message: text2 } };
43897
+ isJson = false;
43898
+ }
43899
+ if (!isJson && (isEventStreamResponse || text2.includes("data:"))) {
43900
+ for (const line of text2.split("\n")) {
43901
+ const trimmed = line.trim();
43902
+ if (trimmed.startsWith("data:")) {
43903
+ const payload = trimmed.slice(5).trim();
43904
+ if (payload.length > 0 && payload !== "[DONE]") {
43905
+ try {
43906
+ parsedBody = JSON.parse(payload);
43907
+ isJson = true;
43908
+ break;
43909
+ } catch {
43910
+ }
43911
+ }
43912
+ }
43913
+ }
43394
43914
  }
43395
- if (errorBody?.error) {
43396
- const upstreamErrorMessage = typeof errorBody.error.message === "string" && errorBody.error.message.length > 0 ? errorBody.error.message : "Unknown error";
43397
- const rawErrorMessage = redactProjectIdText(upstreamErrorMessage, [
43398
- projectId ?? ""
43399
- ]);
43400
- const errorType = detectErrorType(rawErrorMessage);
43401
- const safeProjectId = maskSensitiveIdentifier(projectId) || "Unknown";
43402
- const debugInfo = `
43915
+ if (!isJson && isJsonResponse) {
43916
+ parsedBody = {
43917
+ error: {
43918
+ code: response.status,
43919
+ message: text2,
43920
+ status: "UNAVAILABLE"
43921
+ }
43922
+ };
43923
+ isJson = true;
43924
+ }
43925
+ const errorRecord = isJson ? extractAntigravityError(parsedBody) : null;
43926
+ const retryMeta = resolveRetryMetadata({
43927
+ details: errorRecord?.details,
43928
+ message: typeof errorRecord?.message === "string" ? errorRecord.message : void 0,
43929
+ status: response.status,
43930
+ headers,
43931
+ // The transformer renders what the host sees, so it follows the
43932
+ // executor's rule: an upstream zero delay falls through to the
43933
+ // response's own header instead of becoming a zero wait here.
43934
+ allowZero: false
43935
+ });
43936
+ if (retryMeta !== null) {
43937
+ const pair = deriveRetryHeaderPairFromMs(retryMeta.delayMs);
43938
+ headers.set("Retry-After", pair["retry-after"]);
43939
+ headers.set("retry-after", pair["retry-after"]);
43940
+ headers.set("retry-after-ms", pair["retry-after-ms"]);
43941
+ } else {
43942
+ headers.delete("Retry-After");
43943
+ headers.delete("retry-after");
43944
+ headers.delete("retry-after-ms");
43945
+ }
43946
+ let diagnosticErrorText = "";
43947
+ if (errorRecord && typeof errorRecord.message === "string") {
43948
+ diagnosticErrorText = errorRecord.message;
43949
+ } else if (parsedBody && typeof parsedBody === "object" && !Array.isArray(parsedBody)) {
43950
+ const errProp = parsedBody.error;
43951
+ if (typeof errProp === "string") {
43952
+ diagnosticErrorText = errProp;
43953
+ } else {
43954
+ diagnosticErrorText = text2;
43955
+ }
43956
+ } else {
43957
+ diagnosticErrorText = text2;
43958
+ }
43959
+ const safeProjectId = maskSensitiveIdentifier(projectId) || "Unknown";
43960
+ const debugInfo = `
43403
43961
 
43404
43962
  [Debug Info]
43405
43963
  Requested Model: ${requestedModel || "Unknown"}
@@ -43410,48 +43968,91 @@ Status: ${response.status}
43410
43968
  Request ID: ${headers.get("x-request-id") || "N/A"}${toolDebugMissing !== void 0 ? `
43411
43969
  Tool Debug Missing: ${toolDebugMissing}` : ""}${toolDebugSummary ? `
43412
43970
  Tool Debug Summary: ${toolDebugSummary}` : ""}`;
43413
- const injectedDebug = debugText ? `
43971
+ const injectedDebug = debugText ? `
43414
43972
 
43415
43973
  ${debugText}` : "";
43416
- errorBody.error.message = rawErrorMessage + debugInfo + injectedDebug;
43417
- if (errorType === "thinking_block_order") {
43418
- const recoveryError = new Error("THINKING_RECOVERY_NEEDED");
43419
- recoveryError.recoveryType = errorType;
43420
- recoveryError.originalError = errorBody;
43421
- recoveryError.debugInfo = debugInfo;
43422
- throw recoveryError;
43423
- }
43424
- const errorMessage2 = errorBody.error.message?.toLowerCase() || "";
43425
- if (errorMessage2.includes("prompt is too long") || errorMessage2.includes("context length exceeded") || errorMessage2.includes("context_length_exceeded") || errorMessage2.includes("maximum context length")) {
43426
- headers.set("x-antigravity-context-error", "prompt_too_long");
43427
- }
43428
- if (errorMessage2.includes("tool_use") && errorMessage2.includes("tool_result") && (errorMessage2.includes("without") || errorMessage2.includes("immediately after"))) {
43429
- headers.set("x-antigravity-context-error", "tool_pairing");
43430
- }
43431
- return new Response(JSON.stringify(errorBody), {
43974
+ const safeDiagnosticText = redactProjectIdText(
43975
+ diagnosticErrorText,
43976
+ projectIds
43977
+ );
43978
+ const errorType = detectErrorType(safeDiagnosticText);
43979
+ if (errorType === "thinking_block_order") {
43980
+ const recoveryError = new Error("THINKING_RECOVERY_NEEDED");
43981
+ recoveryError.recoveryType = errorType;
43982
+ recoveryError.originalError = parsedBody ?? safeDiagnosticText;
43983
+ recoveryError.debugInfo = debugInfo;
43984
+ throw recoveryError;
43985
+ }
43986
+ const errorMessageLower = safeDiagnosticText.toLowerCase();
43987
+ if (errorMessageLower.includes("prompt is too long") || errorMessageLower.includes("context length exceeded") || errorMessageLower.includes("context_length_exceeded") || errorMessageLower.includes("maximum context length")) {
43988
+ headers.set("x-antigravity-context-error", "prompt_too_long");
43989
+ }
43990
+ if (errorMessageLower.includes("tool_use") && errorMessageLower.includes("tool_result") && (errorMessageLower.includes("without") || errorMessageLower.includes("immediately after"))) {
43991
+ headers.set("x-antigravity-context-error", "tool_pairing");
43992
+ }
43993
+ if (!isJson && !isEventStreamResponse) {
43994
+ return await createSafeFallback(text2);
43995
+ }
43996
+ if (!isJson) {
43997
+ return await createSafeFallback(text2);
43998
+ }
43999
+ if (errorRecord !== null) {
44000
+ const upstreamErrorMessage = typeof errorRecord.message === "string" && errorRecord.message.length > 0 ? errorRecord.message : "Unknown error";
44001
+ const rawErrorMessage = redactProjectIdText(
44002
+ upstreamErrorMessage,
44003
+ projectIds
44004
+ );
44005
+ const isQuota = isQuotaError(
44006
+ response.status,
44007
+ upstreamErrorMessage,
44008
+ errorRecord.details
44009
+ );
44010
+ const normalizedErrorMessage = isQuota ? normalizeResetDuration(rawErrorMessage) : rawErrorMessage;
44011
+ errorRecord.message = normalizedErrorMessage + debugInfo + injectedDebug;
44012
+ const responseHeaders2 = new Headers(headers);
44013
+ responseHeaders2.delete("content-length");
44014
+ responseHeaders2.set("content-type", "application/json");
44015
+ const finalBody2 = JSON.stringify(parsedBody);
44016
+ const finalResponse2 = new Response(finalBody2, {
43432
44017
  status: response.status,
43433
44018
  statusText: response.statusText,
43434
- headers
44019
+ headers: responseHeaders2
43435
44020
  });
43436
- }
43437
- if (errorBody?.error?.details && Array.isArray(errorBody.error.details)) {
43438
- const retryInfo = errorBody.error.details.find(
43439
- (detail) => detail["@type"] === "type.googleapis.com/google.rpc.RetryInfo"
44021
+ return await redactCredentialResponse(
44022
+ finalResponse2,
44023
+ void 0,
44024
+ finalBody2,
44025
+ projectIds
43440
44026
  );
43441
- if (retryInfo?.retryDelay) {
43442
- const match = retryInfo.retryDelay.match(/^([\d.]+)s$/);
43443
- if (match?.[1]) {
43444
- const retrySeconds = parseFloat(match[1]);
43445
- if (!Number.isNaN(retrySeconds) && retrySeconds > 0) {
43446
- const retryAfterSec = Math.ceil(retrySeconds).toString();
43447
- const retryAfterMs = Math.ceil(retrySeconds * 1e3).toString();
43448
- headers.set("Retry-After", retryAfterSec);
43449
- headers.set("retry-after-ms", retryAfterMs);
43450
- }
43451
- }
43452
- }
43453
44027
  }
44028
+ const responseHeaders = new Headers(headers);
44029
+ responseHeaders.delete("content-length");
44030
+ responseHeaders.set("content-type", "application/json");
44031
+ const finalBody = JSON.stringify(parsedBody);
44032
+ const finalResponse = new Response(finalBody, {
44033
+ status: response.status,
44034
+ statusText: response.statusText,
44035
+ headers: responseHeaders
44036
+ });
44037
+ return await redactCredentialResponse(
44038
+ finalResponse,
44039
+ void 0,
44040
+ finalBody,
44041
+ projectIds
44042
+ );
44043
+ } catch (transformError) {
44044
+ if (transformError instanceof Error && transformError.message === "THINKING_RECOVERY_NEEDED") {
44045
+ throw transformError;
44046
+ }
44047
+ return await createSafeFallback(text2);
43454
44048
  }
44049
+ }
44050
+ const responseFallback = response.clone();
44051
+ try {
44052
+ const headers = new Headers(response.headers);
44053
+ const text2 = await response.text();
44054
+ noteGeminiDumpResponse(dumpContext, response);
44055
+ appendGeminiDumpResponseText(dumpContext, text2);
43455
44056
  const init = {
43456
44057
  status: response.status,
43457
44058
  statusText: response.statusText,
@@ -43958,6 +44559,111 @@ function isFlushReport(value) {
43958
44559
  return typeof value === "object" && value !== null && "completed" in value && typeof value.completed === "number" && "failures" in value && Array.isArray(value.failures);
43959
44560
  }
43960
44561
 
44562
+ // src/plugin/shared/request-cancellation.ts
44563
+ function createRequestCancellation(signals) {
44564
+ const controller = new AbortController();
44565
+ const remove2 = [];
44566
+ const release2 = () => {
44567
+ for (const detach of remove2.splice(0)) detach();
44568
+ };
44569
+ for (const source of signals) {
44570
+ if (source.aborted) {
44571
+ controller.abort(source.reason);
44572
+ release2();
44573
+ break;
44574
+ }
44575
+ const forward = () => {
44576
+ controller.abort(source.reason);
44577
+ release2();
44578
+ };
44579
+ remove2.push(() => source.removeEventListener("abort", forward));
44580
+ source.addEventListener("abort", forward, { once: true });
44581
+ if (source.aborted) forward();
44582
+ if (controller.signal.aborted) break;
44583
+ }
44584
+ return { signal: controller.signal, release: release2 };
44585
+ }
44586
+ async function retainResponseLifetime(response, cancellation) {
44587
+ if (!response.body) {
44588
+ cancellation.release();
44589
+ return { response, settled: Promise.resolve() };
44590
+ }
44591
+ let reader;
44592
+ try {
44593
+ reader = response.body.getReader();
44594
+ } catch (error) {
44595
+ cancellation.release();
44596
+ throw error;
44597
+ }
44598
+ let resolve28 = () => {
44599
+ };
44600
+ const settled = new Promise((done) => {
44601
+ resolve28 = done;
44602
+ });
44603
+ let stopping = false;
44604
+ let finished = false;
44605
+ let controller;
44606
+ const finish = () => {
44607
+ if (finished) return;
44608
+ finished = true;
44609
+ cancellation.signal.removeEventListener("abort", abort);
44610
+ cancellation.release();
44611
+ resolve28();
44612
+ };
44613
+ const abort = () => {
44614
+ if (finished || stopping) return;
44615
+ stopping = true;
44616
+ const reason = cancellation.signal.reason;
44617
+ controller.error(reason);
44618
+ void reader.cancel(reason).then(finish, finish);
44619
+ };
44620
+ const body = new ReadableStream({
44621
+ start(output2) {
44622
+ controller = output2;
44623
+ cancellation.signal.addEventListener("abort", abort, { once: true });
44624
+ if (cancellation.signal.aborted) abort();
44625
+ },
44626
+ async pull(output2) {
44627
+ try {
44628
+ const next = await reader.read();
44629
+ if (stopping) return;
44630
+ if (next.done) {
44631
+ output2.close();
44632
+ finish();
44633
+ } else {
44634
+ output2.enqueue(next.value);
44635
+ }
44636
+ } catch (error) {
44637
+ if (stopping) return;
44638
+ output2.error(error);
44639
+ finish();
44640
+ }
44641
+ },
44642
+ async cancel(reason) {
44643
+ stopping = true;
44644
+ try {
44645
+ await reader.cancel(reason);
44646
+ } finally {
44647
+ finish();
44648
+ }
44649
+ }
44650
+ });
44651
+ try {
44652
+ return {
44653
+ response: new Response(body, {
44654
+ status: response.status,
44655
+ statusText: response.statusText,
44656
+ headers: response.headers
44657
+ }),
44658
+ settled
44659
+ };
44660
+ } catch (error) {
44661
+ stopping = true;
44662
+ await reader.cancel(error).then(finish, finish);
44663
+ throw error;
44664
+ }
44665
+ }
44666
+
43961
44667
  // src/plugin/shared/request-services.ts
43962
44668
  init_dist();
43963
44669
 
@@ -44526,111 +45232,6 @@ function throwIfAllKilled(input2) {
44526
45232
  });
44527
45233
  }
44528
45234
 
44529
- // src/plugin/shared/request-cancellation.ts
44530
- function createRequestCancellation(signals) {
44531
- const controller = new AbortController();
44532
- const remove2 = [];
44533
- const release2 = () => {
44534
- for (const detach of remove2.splice(0)) detach();
44535
- };
44536
- for (const source of signals) {
44537
- if (source.aborted) {
44538
- controller.abort(source.reason);
44539
- release2();
44540
- break;
44541
- }
44542
- const forward = () => {
44543
- controller.abort(source.reason);
44544
- release2();
44545
- };
44546
- remove2.push(() => source.removeEventListener("abort", forward));
44547
- source.addEventListener("abort", forward, { once: true });
44548
- if (source.aborted) forward();
44549
- if (controller.signal.aborted) break;
44550
- }
44551
- return { signal: controller.signal, release: release2 };
44552
- }
44553
- async function retainResponseLifetime(response, cancellation) {
44554
- if (!response.body) {
44555
- cancellation.release();
44556
- return { response, settled: Promise.resolve() };
44557
- }
44558
- let reader;
44559
- try {
44560
- reader = response.body.getReader();
44561
- } catch (error) {
44562
- cancellation.release();
44563
- throw error;
44564
- }
44565
- let resolve28 = () => {
44566
- };
44567
- const settled = new Promise((done) => {
44568
- resolve28 = done;
44569
- });
44570
- let stopping = false;
44571
- let finished = false;
44572
- let controller;
44573
- const finish = () => {
44574
- if (finished) return;
44575
- finished = true;
44576
- cancellation.signal.removeEventListener("abort", abort);
44577
- cancellation.release();
44578
- resolve28();
44579
- };
44580
- const abort = () => {
44581
- if (finished || stopping) return;
44582
- stopping = true;
44583
- const reason = cancellation.signal.reason;
44584
- controller.error(reason);
44585
- void reader.cancel(reason).then(finish, finish);
44586
- };
44587
- const body = new ReadableStream({
44588
- start(output2) {
44589
- controller = output2;
44590
- cancellation.signal.addEventListener("abort", abort, { once: true });
44591
- if (cancellation.signal.aborted) abort();
44592
- },
44593
- async pull(output2) {
44594
- try {
44595
- const next = await reader.read();
44596
- if (stopping) return;
44597
- if (next.done) {
44598
- output2.close();
44599
- finish();
44600
- } else {
44601
- output2.enqueue(next.value);
44602
- }
44603
- } catch (error) {
44604
- if (stopping) return;
44605
- output2.error(error);
44606
- finish();
44607
- }
44608
- },
44609
- async cancel(reason) {
44610
- stopping = true;
44611
- try {
44612
- await reader.cancel(reason);
44613
- } finally {
44614
- finish();
44615
- }
44616
- }
44617
- });
44618
- try {
44619
- return {
44620
- response: new Response(body, {
44621
- status: response.status,
44622
- statusText: response.statusText,
44623
- headers: response.headers
44624
- }),
44625
- settled
44626
- };
44627
- } catch (error) {
44628
- stopping = true;
44629
- await reader.cancel(error).then(finish, finish);
44630
- throw error;
44631
- }
44632
- }
44633
-
44634
45235
  // src/plugin/shared/after-handoff.ts
44635
45236
  function createAfterHandoff(work, signals, onFailure) {
44636
45237
  const controller = new AbortController();
@@ -44954,23 +45555,6 @@ function createNoAccountResponse(message, model) {
44954
45555
  function terminalFetchError(lastError, fallbackMessage) {
44955
45556
  return lastError ?? new Error(fallbackMessage);
44956
45557
  }
44957
- function retryAfterMsFromResponse(response, defaultRetryMs = 6e4) {
44958
- const retryAfterMsHeader = response.headers.get("retry-after-ms");
44959
- if (retryAfterMsHeader) {
44960
- const parsed = Number.parseInt(retryAfterMsHeader, 10);
44961
- if (!Number.isNaN(parsed) && parsed > 0) {
44962
- return parsed;
44963
- }
44964
- }
44965
- const retryAfterHeader = response.headers.get("retry-after");
44966
- if (retryAfterHeader) {
44967
- const parsed = Number.parseInt(retryAfterHeader, 10);
44968
- if (!Number.isNaN(parsed) && parsed > 0) {
44969
- return parsed * 1e3;
44970
- }
44971
- }
44972
- return defaultRetryMs;
44973
- }
44974
45558
  function formatWaitTime(ms) {
44975
45559
  if (ms < 1e3) return `${ms}ms`;
44976
45560
  const seconds = Math.ceil(ms / 1e3);
@@ -44992,10 +45576,11 @@ function sleep4(ms, signal) {
44992
45576
  );
44993
45577
  return;
44994
45578
  }
45579
+ const timerMs = Math.min(Math.max(0, Math.floor(ms)), 2147483647);
44995
45580
  const timeout = setTimeout(() => {
44996
45581
  cleanup2();
44997
45582
  resolve28();
44998
- }, ms);
45583
+ }, timerMs);
44999
45584
  const onAbort = () => {
45000
45585
  cleanup2();
45001
45586
  reject(
@@ -45090,7 +45675,7 @@ function createRequestExecutor(deps) {
45090
45675
  };
45091
45676
  async function execute(input2, init, options, selectedCredentials, selectedProjectIds, deadline, waitPolicy) {
45092
45677
  const assertAdmission = async () => {
45093
- await deadline.wait(() => deps.assertAdmission?.());
45678
+ await deadline.wait(() => deps.assertAdmission?.(deadline.signal));
45094
45679
  };
45095
45680
  const logResponseBody2 = (...args) => deadline.wait(() => debug.logResponseBody(...args));
45096
45681
  await assertAdmission();
@@ -46102,10 +46687,6 @@ function createRequestExecutor(deps) {
46102
46687
  }
46103
46688
  const defaultRetryMs = (config.default_retry_after_seconds ?? 60) * 1e3;
46104
46689
  const _maxBackoffMs = (config.max_backoff_seconds ?? 60) * 1e3;
46105
- const headerRetryMs = retryAfterMsFromResponse(
46106
- response,
46107
- defaultRetryMs
46108
- );
46109
46690
  const bodyInfo = await (async () => {
46110
46691
  try {
46111
46692
  const text2 = await deadline.wait(
@@ -46121,8 +46702,12 @@ function createRequestExecutor(deps) {
46121
46702
  return null;
46122
46703
  }
46123
46704
  })();
46124
- const reasonInfo = bodyInfo ? extractRateLimitBodyInfo(bodyInfo) : { retryDelayMs: null };
46125
- const serverRetryMs = reasonInfo.retryDelayMs ?? headerRetryMs;
46705
+ const reasonInfo = extractRateLimitBodyInfo(
46706
+ bodyInfo,
46707
+ response.status,
46708
+ response.headers
46709
+ );
46710
+ const serverRetryMs = reasonInfo.retryDelayMs ?? defaultRetryMs;
46126
46711
  const rateLimitReason = parseRateLimitReason(
46127
46712
  reasonInfo.reason,
46128
46713
  reasonInfo.message,
@@ -46889,15 +47474,15 @@ function parseModelUnavailableError(bodyText) {
46889
47474
  }
46890
47475
  return { status: "NOT_FOUND", reasons };
46891
47476
  }
46892
- function extractRateLimitBodyInfo(body) {
46893
- if (!body || typeof body !== "object") return { retryDelayMs: null };
46894
- const error = body.error;
46895
- const message = error && typeof error === "object" ? error.message : void 0;
46896
- const details = error && typeof error === "object" ? error.details : void 0;
47477
+ function extractRateLimitBodyInfo(body, status, headers) {
47478
+ const errorRecord = extractAntigravityError(body);
47479
+ const message = errorRecord && typeof errorRecord.message === "string" ? errorRecord.message : void 0;
47480
+ const details = errorRecord && Array.isArray(errorRecord.details) ? errorRecord.details : void 0;
46897
47481
  let reason;
46898
47482
  if (Array.isArray(details)) {
46899
47483
  for (const detail of details) {
46900
- if (!detail || typeof detail !== "object") continue;
47484
+ if (!detail || typeof detail !== "object" || Array.isArray(detail))
47485
+ continue;
46901
47486
  const type = detail["@type"];
46902
47487
  if (typeof type === "string" && type.includes("google.rpc.ErrorInfo")) {
46903
47488
  const detailReason = detail.reason;
@@ -46907,95 +47492,28 @@ function extractRateLimitBodyInfo(body) {
46907
47492
  }
46908
47493
  }
46909
47494
  }
46910
- for (const detail of details) {
46911
- if (!detail || typeof detail !== "object") continue;
46912
- const type = detail["@type"];
46913
- if (typeof type === "string" && type.includes("google.rpc.RetryInfo")) {
46914
- const retryDelay = detail.retryDelay;
46915
- if (typeof retryDelay === "string") {
46916
- const retryDelayMs = parseDurationToMs(retryDelay);
46917
- if (retryDelayMs !== null) {
46918
- return { retryDelayMs, message, reason };
46919
- }
46920
- }
46921
- }
46922
- }
46923
- for (const detail of details) {
46924
- if (!detail || typeof detail !== "object") continue;
46925
- const metadata = detail.metadata;
46926
- if (metadata && typeof metadata === "object") {
46927
- const quotaResetDelay = metadata.quotaResetDelay;
46928
- const quotaResetTime = metadata.quotaResetTimeStamp;
46929
- if (typeof quotaResetDelay === "string") {
46930
- const quotaResetDelayMs = parseDurationToMs(quotaResetDelay);
46931
- if (quotaResetDelayMs !== null) {
46932
- return {
46933
- retryDelayMs: quotaResetDelayMs,
46934
- message,
46935
- quotaResetTime,
46936
- reason
46937
- };
46938
- }
46939
- }
46940
- }
46941
- }
46942
- }
46943
- if (message) {
46944
- const reset = message.match(/(?:reset after|resets? in)\s+([0-9hms.]+)/i);
46945
- const rawDuration = reset?.[1];
46946
- if (rawDuration) {
46947
- const parsed = parseDurationToMs(rawDuration);
46948
- if (parsed !== null) {
46949
- return { retryDelayMs: parsed, message, reason };
46950
- }
46951
- }
46952
- }
46953
- return { retryDelayMs: null, message, reason };
46954
- }
46955
- function parseDurationToMs(duration) {
46956
- const simpleMatch = duration.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/i);
46957
- if (simpleMatch) {
46958
- const value = parseFloat(simpleMatch[1]);
46959
- const unit = (simpleMatch[2] || "s").toLowerCase();
46960
- switch (unit) {
46961
- case "h":
46962
- return value * 3600 * 1e3;
46963
- case "m":
46964
- return value * 60 * 1e3;
46965
- case "s":
46966
- return value * 1e3;
46967
- case "ms":
46968
- return value;
46969
- default:
46970
- return value * 1e3;
46971
- }
46972
- }
46973
- const compoundRegex = /(\d+(?:\.\d+)?)(h|m(?!s)|s|ms)/gi;
46974
- let totalMs = 0;
46975
- let matchFound = false;
46976
- let match = null;
46977
- while (true) {
46978
- match = compoundRegex.exec(duration);
46979
- if (match === null) break;
46980
- matchFound = true;
46981
- const value = parseFloat(match[1]);
46982
- const unit = match[2]?.toLowerCase();
46983
- switch (unit) {
46984
- case "h":
46985
- totalMs += value * 3600 * 1e3;
46986
- break;
46987
- case "m":
46988
- totalMs += value * 60 * 1e3;
46989
- break;
46990
- case "s":
46991
- totalMs += value * 1e3;
46992
- break;
46993
- case "ms":
46994
- totalMs += value;
46995
- break;
46996
- }
46997
47495
  }
46998
- return matchFound ? totalMs : null;
47496
+ const resolved = resolveRetryMetadata({
47497
+ details,
47498
+ message,
47499
+ status,
47500
+ headers,
47501
+ // The executor keeps its historical reading of Google's body fields: an
47502
+ // upstream zero ("0s") falls through to the configured default retry
47503
+ // instead of retrying immediately, and a unitless delay such as "90"
47504
+ // still means 90 seconds.
47505
+ allowZero: false,
47506
+ allowBareSeconds: true
47507
+ });
47508
+ const retryDelayMs = resolved !== null ? Number(
47509
+ resolved.delayMs > BigInt(Number.MAX_SAFE_INTEGER) ? BigInt(Number.MAX_SAFE_INTEGER) : resolved.delayMs
47510
+ ) : null;
47511
+ return {
47512
+ retryDelayMs,
47513
+ message,
47514
+ quotaResetTime: resolved?.quotaResetTime,
47515
+ reason
47516
+ };
46999
47517
  }
47000
47518
 
47001
47519
  // src/plugin/shared/runtime.ts
@@ -47786,7 +48304,8 @@ function createVaultAccountMenuSections(pool, selectorOf, checkQuota) {
47786
48304
  return {
47787
48305
  accounts: {
47788
48306
  title: "Accounts",
47789
- build: () => {
48307
+ build: async () => {
48308
+ await pool.syncForDisplay();
47790
48309
  const rows = pool.selector.rows;
47791
48310
  return {
47792
48311
  lines: [
@@ -47802,7 +48321,8 @@ function createVaultAccountMenuSections(pool, selectorOf, checkQuota) {
47802
48321
  },
47803
48322
  quota: {
47804
48323
  title: "Quota",
47805
- build: () => {
48324
+ build: async () => {
48325
+ await pool.syncForDisplay();
47806
48326
  const rows = pool.selector.rows;
47807
48327
  return {
47808
48328
  lines: rows.length === 0 ? [] : rows.map(
@@ -48331,6 +48851,7 @@ function tokenExchange(overrides) {
48331
48851
  };
48332
48852
  }
48333
48853
  function storeRefusal(status) {
48854
+ if (status.status === "busy") return new AccountStoreBusyError();
48334
48855
  return new Error(
48335
48856
  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\`.`
48336
48857
  );
@@ -48683,7 +49204,8 @@ async function createGaLocalRequestPipeline(input2) {
48683
49204
  async function createGaVaultRequestPipeline(input2) {
48684
49205
  const { pool } = input2;
48685
49206
  await input2.assertAdmission?.();
48686
- await pool.sync();
49207
+ await pool.syncCached();
49208
+ const shutdown = new AbortController();
48687
49209
  const logger3 = input2.runtime.logger.createLogger("request");
48688
49210
  const executor = createRequestExecutor({
48689
49211
  ...gaEngineCollaborators({
@@ -48693,7 +49215,10 @@ async function createGaVaultRequestPipeline(input2) {
48693
49215
  logger: logger3
48694
49216
  }),
48695
49217
  accounts: pool.selector,
48696
- ...input2.assertAdmission ? { assertAdmission: input2.assertAdmission } : {},
49218
+ assertAdmission: async (signal) => {
49219
+ await input2.assertAdmission?.();
49220
+ await pool.sync(signal);
49221
+ },
48697
49222
  credentials: pool.credentials,
48698
49223
  trackers: {
48699
49224
  health: pool.selector.healthTracker,
@@ -48701,17 +49226,22 @@ async function createGaVaultRequestPipeline(input2) {
48701
49226
  }
48702
49227
  });
48703
49228
  return {
48704
- execute: async (job, context) => {
48705
- await input2.assertAdmission?.();
48706
- await pool.sync();
48707
- return createGaJobExecutor(executor, input2.overrides)(job, context);
49229
+ execute: createGaJobExecutor(executor, input2.overrides),
49230
+ rows: async (signal) => {
49231
+ const cancellation = createRequestCancellation([signal, shutdown.signal]);
49232
+ try {
49233
+ await pool.sync(cancellation.signal);
49234
+ return pool.selector.rows;
49235
+ } finally {
49236
+ cancellation.release();
49237
+ }
48708
49238
  },
48709
- rows: () => pool.selector.rows,
48710
49239
  refreshAccounts: async () => {
48711
49240
  await input2.assertAdmission?.();
48712
- await pool.refresh();
49241
+ await pool.refresh(shutdown.signal);
48713
49242
  },
48714
49243
  async dispose() {
49244
+ shutdown.abort(new Error("The Antigravity request executor is disposed"));
48715
49245
  await executor.dispose();
48716
49246
  await pool.flush();
48717
49247
  }
@@ -48736,7 +49266,7 @@ function createGaVaultStateSource(input2) {
48736
49266
  if (signal.aborted) throw abortError(signal);
48737
49267
  const stored = await input2.readState?.().catch(() => void 0);
48738
49268
  if (signal.aborted) throw abortError(signal);
48739
- const rows = input2.rows();
49269
+ const rows = await input2.rows(signal);
48740
49270
  const settings = input2.settings();
48741
49271
  const route = input2.route(scope);
48742
49272
  if (signal.aborted) throw abortError(signal);
@@ -48903,7 +49433,7 @@ async function createGaVaultLocationServices(input2) {
48903
49433
  return {
48904
49434
  execute: started.execute,
48905
49435
  state: createGaVaultStateSource({
48906
- rows: () => started.rows(),
49436
+ rows: (signal) => started.rows(signal),
48907
49437
  readState: () => custody.readState(),
48908
49438
  selectorOf,
48909
49439
  ...input2.nextReadSeq ? { nextReadSeq: input2.nextReadSeq } : {},
@@ -49338,8 +49868,7 @@ function createGaLocationServicesFactory(bindings) {
49338
49868
  });
49339
49869
  throw error;
49340
49870
  }
49341
- })().catch(async (error) => {
49342
- await custody.recycleStalledSource?.(VAULT_REFRESH_STALL_MS).catch(() => false);
49871
+ })().catch((error) => {
49343
49872
  vaultPromise = void 0;
49344
49873
  throw error;
49345
49874
  });
@@ -49355,6 +49884,7 @@ function createGaLocationServicesFactory(bindings) {
49355
49884
  return recovery;
49356
49885
  }
49357
49886
  try {
49887
+ await custody?.recycleStalledSource?.(VAULT_REFRESH_STALL_MS).catch(() => false);
49358
49888
  return await vault();
49359
49889
  } catch (error) {
49360
49890
  if (purpose === "execute") throw error;
@@ -51028,20 +51558,32 @@ function createGaPoolLogin(input2) {
51028
51558
  method,
51029
51559
  connectExisting: () => track(
51030
51560
  (async () => {
51561
+ let stage = "initial-admission";
51031
51562
  try {
51032
51563
  await admit2();
51033
51564
  if (!input2.local?.assertExistingPool) throw new Error(LOGIN_FAILED);
51565
+ stage = "existing-pool-admission";
51034
51566
  await abortable(
51035
51567
  track(input2.local.assertExistingPool(admit2)),
51036
51568
  shutdown.signal
51037
51569
  );
51570
+ stage = "final-admission";
51038
51571
  await admit2();
51572
+ stage = "placeholder";
51039
51573
  return placeholderCredential({
51040
51574
  integrationID: ANTIGRAVITY_PROVIDER_ID,
51041
51575
  methodID: GA_POOL_RECONNECT_METHOD_ID,
51042
51576
  now: Date.now()
51043
51577
  });
51044
- } catch {
51578
+ } catch (error) {
51579
+ const busy = error instanceof AccountStoreBusyError;
51580
+ try {
51581
+ console.warn(
51582
+ `[antigravity.pool-login] stage=${stage} reason=${busy ? "store-busy" : "store-refusal"}`
51583
+ );
51584
+ } catch {
51585
+ }
51586
+ if (busy) throw new AccountStoreBusyError();
51045
51587
  throw new Error(LOGIN_FAILED);
51046
51588
  }
51047
51589
  })()
@@ -51052,7 +51594,9 @@ function createGaPoolLogin(input2) {
51052
51594
  await admit2();
51053
51595
  await input2.local.persist(result, admit2);
51054
51596
  await admit2();
51055
- } catch {
51597
+ } catch (error) {
51598
+ if (error instanceof AccountStoreBusyError)
51599
+ throw new AccountStoreBusyError();
51056
51600
  throw new Error(LOGIN_FAILED);
51057
51601
  }
51058
51602
  })()
@@ -51214,11 +51758,80 @@ function isGaGoogleContentRequest(request) {
51214
51758
  }
51215
51759
  }
51216
51760
  function gaPreHeaderFailureResponse(error) {
51217
- const rawMessage = error instanceof Error && error.message ? error.message : "Antigravity request failed before a response arrived";
51218
- const message = redactProjectIdText(rawMessage);
51761
+ const err = error;
51762
+ const rawStatusCode = typeof err?.statusCode === "number" && Number.isSafeInteger(err.statusCode) ? err.statusCode : void 0;
51763
+ const rawStatus = typeof err?.status === "number" && Number.isSafeInteger(err.status) ? err.status : void 0;
51764
+ const numericStatus = rawStatusCode ?? rawStatus;
51765
+ let status = 502;
51766
+ let statusString = "UNAVAILABLE";
51767
+ if (numericStatus !== void 0) {
51768
+ switch (numericStatus) {
51769
+ case 400:
51770
+ status = 400;
51771
+ statusString = "INVALID_ARGUMENT";
51772
+ break;
51773
+ case 401:
51774
+ status = 401;
51775
+ statusString = "UNAUTHENTICATED";
51776
+ break;
51777
+ case 403:
51778
+ status = 403;
51779
+ statusString = "PERMISSION_DENIED";
51780
+ break;
51781
+ case 404:
51782
+ status = 404;
51783
+ statusString = "NOT_FOUND";
51784
+ break;
51785
+ case 412:
51786
+ status = 412;
51787
+ statusString = "FAILED_PRECONDITION";
51788
+ break;
51789
+ case 429:
51790
+ status = 429;
51791
+ statusString = "RESOURCE_EXHAUSTED";
51792
+ break;
51793
+ case 502:
51794
+ case 503:
51795
+ case 504:
51796
+ status = numericStatus;
51797
+ statusString = "UNAVAILABLE";
51798
+ break;
51799
+ default:
51800
+ status = 502;
51801
+ statusString = "UNAVAILABLE";
51802
+ break;
51803
+ }
51804
+ }
51805
+ const rawMessage = error instanceof Error && error.message ? error.message : typeof err?.message === "string" && err.message ? err.message : "Antigravity request failed before a response arrived";
51806
+ const redacted = redactProjectIdText(rawMessage);
51807
+ const isQuota = isQuotaError(status, rawMessage, err?.details);
51808
+ const message = isQuota ? normalizeResetDuration(redacted) : redacted;
51809
+ const headers = new Headers({ "content-type": "application/json" });
51810
+ const metadata = resolveRetryMetadata({
51811
+ details: err?.details,
51812
+ message: rawMessage,
51813
+ status,
51814
+ headers: err?.headers ?? null,
51815
+ retryAfterMs: err?.retryAfterMs,
51816
+ resetAfterMs: err?.resetAfterMs,
51817
+ retryAfterSeconds: err?.retryAfterSeconds,
51818
+ // The bridge may pass on a truthful local wait of zero seconds.
51819
+ allowZero: true
51820
+ });
51821
+ if (metadata !== null) {
51822
+ const pair = deriveRetryHeaderPairFromMs(metadata.delayMs);
51823
+ headers.set("retry-after", pair["retry-after"]);
51824
+ headers.set("retry-after-ms", pair["retry-after-ms"]);
51825
+ }
51219
51826
  return new Response(
51220
- JSON.stringify({ error: { code: 502, message, status: "UNAVAILABLE" } }),
51221
- { status: 502, headers: { "content-type": "application/json" } }
51827
+ JSON.stringify({
51828
+ error: {
51829
+ code: status,
51830
+ message,
51831
+ status: statusString
51832
+ }
51833
+ }),
51834
+ { status, headers }
51222
51835
  );
51223
51836
  }
51224
51837
  async function startGaLoopbackBridge(options) {
@@ -51483,10 +52096,11 @@ async function startGaLoopbackBridge(options) {
51483
52096
  function isGaJobId(value) {
51484
52097
  return JOB_ID_PATTERN.test(value);
51485
52098
  }
51486
- function writeResponseHead(response, status, contentType) {
52099
+ function writeResponseHead(response, status, contentType, extraHeaders) {
51487
52100
  response.writeHead(status, {
51488
52101
  "content-type": contentType,
51489
- "cache-control": "no-cache"
52102
+ "cache-control": "no-cache",
52103
+ ...extraHeaders
51490
52104
  });
51491
52105
  }
51492
52106
  async function pipeResponse(upstream, response, onFailure, onHandoff) {
@@ -51496,7 +52110,8 @@ async function pipeResponse(upstream, response, onFailure, onHandoff) {
51496
52110
  });
51497
52111
  return;
51498
52112
  }
51499
- writeResponseHead(response, upstream.status, contentType);
52113
+ const extraHeaders = collectForwardedHeaders(upstream.headers);
52114
+ writeResponseHead(response, upstream.status, contentType, extraHeaders);
51500
52115
  response.flushHeaders();
51501
52116
  onHandoff();
51502
52117
  if (!upstream.body) {
@@ -61316,7 +61931,10 @@ function createVaultFetchInterceptor(context) {
61316
61931
  const pool = context.pool ?? createVaultAccountPool({ source });
61317
61932
  const selector = pool.selector;
61318
61933
  const executor = createRequestExecutor({
61319
- assertAdmission: context.assertAdmission,
61934
+ assertAdmission: async (signal) => {
61935
+ await context.assertAdmission?.();
61936
+ await pool.sync(signal);
61937
+ },
61320
61938
  ...openCode1EngineCollaborators({
61321
61939
  ...context,
61322
61940
  transport: agyTransport
@@ -61333,7 +61951,6 @@ function createVaultFetchInterceptor(context) {
61333
61951
  async function fetch(input2, init) {
61334
61952
  if (!isGenerativeLanguageRequest(input2)) return upstreamFetch(input2, init);
61335
61953
  if (disposed) throw new Error("The vault request runtime is disposed");
61336
- await pool.sync();
61337
61954
  return executor.execute(input2, init);
61338
61955
  }
61339
61956
  function dispose() {
@@ -61995,7 +62612,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
61995
62612
  },
61996
62613
  vault: async () => {
61997
62614
  const { pool } = await currentVaultPool();
61998
- await pool.sync();
62615
+ await pool.syncCached();
61999
62616
  const projection = buildVaultSidebarProjection(
62000
62617
  pool,
62001
62618
  await vaultCustody.readState(),
@@ -62197,7 +62814,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
62197
62814
  let current;
62198
62815
  try {
62199
62816
  current = await currentVaultPool();
62200
- await current.pool.sync();
62817
+ await current.pool.syncForDisplay();
62201
62818
  } catch {
62202
62819
  return showUnavailableVaultMenu();
62203
62820
  }