@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/index.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((resolve27, 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(() => resolve27(false), remaining);
29984
+ if (signal?.aborted) abort();
29927
29985
  })
29928
29986
  ]);
29929
29987
  } finally {
29930
- clearTimeout(timer);
29988
+ cancelTimer2?.();
29989
+ detachAbort?.();
29931
29990
  }
29932
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;
29998
+ }
29999
+ throw new Error(
30000
+ "The vault roster is not available yet. Check vault access and try the request again."
30001
+ );
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
 
@@ -32841,6 +32927,8 @@ async function assertLegacyPoolInUse(legacyPath) {
32841
32927
  }
32842
32928
  function refusalMessage2(admission) {
32843
32929
  switch (admission.status) {
32930
+ case "busy":
32931
+ return new AccountStoreBusyError().message;
32844
32932
  case "pending":
32845
32933
  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}\`.`;
32846
32934
  case "inactive":
@@ -49115,6 +49203,358 @@ function createNativeGoogleErrorResponse(options) {
49115
49203
  headers
49116
49204
  });
49117
49205
  }
49206
+ function extractAntigravityError(body) {
49207
+ if (!body || typeof body !== "object") return null;
49208
+ let target = body;
49209
+ if (Array.isArray(body)) {
49210
+ if (body.length === 0 || !body[0] || typeof body[0] !== "object" || Array.isArray(body[0])) {
49211
+ return null;
49212
+ }
49213
+ target = body[0];
49214
+ }
49215
+ const candidate = target.error;
49216
+ if (candidate && typeof candidate === "object" && !Array.isArray(candidate)) {
49217
+ return candidate;
49218
+ }
49219
+ return null;
49220
+ }
49221
+ var MAX_FINITE_WAIT_MS = BigInt(Math.ceil(Number.MAX_VALUE));
49222
+ var MAX_FINITE_WAIT_SECONDS = (MAX_FINITE_WAIT_MS + 999n) / 1000n;
49223
+ var MAX_FINITE_FORWARDING_MS = MAX_FINITE_WAIT_SECONDS * 1000n;
49224
+ 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$/;
49225
+ function validateRetryAfterSecondsBigInt(raw) {
49226
+ if (raw === null || raw === void 0) return null;
49227
+ if (typeof raw === "bigint") {
49228
+ return raw >= 0n && raw <= MAX_FINITE_WAIT_SECONDS ? raw : null;
49229
+ }
49230
+ if (typeof raw === "number") {
49231
+ if (!Number.isFinite(raw) || raw < 0 || !Number.isInteger(raw)) {
49232
+ return null;
49233
+ }
49234
+ const b = BigInt(raw);
49235
+ return b <= MAX_FINITE_WAIT_SECONDS ? b : null;
49236
+ }
49237
+ if (typeof raw !== "string") return null;
49238
+ const trimmed = raw.trim();
49239
+ if (trimmed.length === 0) return null;
49240
+ if (/^\d+$/.test(trimmed)) {
49241
+ if (trimmed.length > 309) return null;
49242
+ const val = BigInt(trimmed);
49243
+ return val >= 0n && val <= MAX_FINITE_WAIT_SECONDS ? val : null;
49244
+ }
49245
+ if (RFC_HTTP_DATE_REGEX.test(trimmed)) {
49246
+ const parsedDate = Date.parse(trimmed);
49247
+ if (!Number.isNaN(parsedDate)) {
49248
+ const roundtrip = new Date(parsedDate).toUTCString();
49249
+ if (roundtrip === trimmed) {
49250
+ const diffSec = Math.ceil((parsedDate - Date.now()) / 1e3);
49251
+ if (diffSec >= 0 && Number.isSafeInteger(diffSec)) {
49252
+ return BigInt(diffSec);
49253
+ }
49254
+ }
49255
+ }
49256
+ }
49257
+ return null;
49258
+ }
49259
+ function validateRetryAfterMsBigInt(raw) {
49260
+ if (raw === null || raw === void 0) return null;
49261
+ if (typeof raw === "bigint") {
49262
+ return raw >= 0n && raw <= MAX_FINITE_FORWARDING_MS ? raw : null;
49263
+ }
49264
+ if (typeof raw === "number") {
49265
+ if (!Number.isFinite(raw) || raw < 0 || !Number.isInteger(raw)) {
49266
+ return null;
49267
+ }
49268
+ const b = BigInt(raw);
49269
+ return b <= MAX_FINITE_FORWARDING_MS ? b : null;
49270
+ }
49271
+ if (typeof raw !== "string") return null;
49272
+ const trimmed = raw.trim();
49273
+ if (trimmed.length === 0 || !/^\d+$/.test(trimmed)) return null;
49274
+ if (trimmed.length > 309) return null;
49275
+ const val = BigInt(trimmed);
49276
+ return val >= 0n && val <= MAX_FINITE_FORWARDING_MS ? val : null;
49277
+ }
49278
+ function deriveRetryHeaderPairFromMs(ms) {
49279
+ if (typeof ms !== "bigint" || ms < 0n || ms > MAX_FINITE_FORWARDING_MS) {
49280
+ throw new RangeError(
49281
+ `deriveRetryHeaderPairFromMs: ms must be a non-negative BigInt <= MAX_FINITE_FORWARDING_MS (got ${String(ms)})`
49282
+ );
49283
+ }
49284
+ const sec = (ms + 999n) / 1000n;
49285
+ return {
49286
+ "retry-after": sec.toString(),
49287
+ "retry-after-ms": ms.toString()
49288
+ };
49289
+ }
49290
+ function deriveRetryHeaderPairFromSeconds(sec) {
49291
+ if (typeof sec !== "bigint" || sec < 0n || sec > MAX_FINITE_WAIT_SECONDS) {
49292
+ throw new RangeError(
49293
+ `deriveRetryHeaderPairFromSeconds: sec must be a non-negative BigInt <= MAX_FINITE_WAIT_SECONDS (got ${String(sec)})`
49294
+ );
49295
+ }
49296
+ const ms = sec * 1000n;
49297
+ return {
49298
+ "retry-after": sec.toString(),
49299
+ "retry-after-ms": ms.toString()
49300
+ };
49301
+ }
49302
+ function collectForwardedHeaders(sourceHeaders) {
49303
+ if (!sourceHeaders) return {};
49304
+ const getHeader2 = (name) => {
49305
+ if (typeof sourceHeaders.get === "function") {
49306
+ return sourceHeaders.get(name);
49307
+ }
49308
+ const record3 = sourceHeaders;
49309
+ for (const [key, value] of Object.entries(record3)) {
49310
+ if (key.toLowerCase() === name) return value;
49311
+ }
49312
+ return void 0;
49313
+ };
49314
+ const rawRetryAfterMs = getHeader2("retry-after-ms");
49315
+ const validMs = validateRetryAfterMsBigInt(rawRetryAfterMs);
49316
+ if (validMs !== null) {
49317
+ return deriveRetryHeaderPairFromMs(validMs);
49318
+ }
49319
+ const rawRetryAfter = getHeader2("retry-after");
49320
+ const validSec = validateRetryAfterSecondsBigInt(rawRetryAfter);
49321
+ if (validSec !== null) {
49322
+ return deriveRetryHeaderPairFromSeconds(validSec);
49323
+ }
49324
+ return {};
49325
+ }
49326
+ function isQuotaError(status, message, details) {
49327
+ if (status === 429) return true;
49328
+ const lower = (message ?? "").toLowerCase();
49329
+ if (hasQuotaResetClause(lower)) return true;
49330
+ return hasStructuredQuotaReason(details);
49331
+ }
49332
+ var QUOTA_REASON_CODES = /* @__PURE__ */ new Set([
49333
+ "QUOTA_EXHAUSTED",
49334
+ "RATE_LIMIT_EXCEEDED",
49335
+ "RESOURCE_EXHAUSTED"
49336
+ ]);
49337
+ function hasQuotaResetClause(lowerMessage) {
49338
+ if (lowerMessage.length === 0) return false;
49339
+ if (extractResetDurationFromText(lowerMessage) === null) return false;
49340
+ return lowerMessage.includes("quota") || lowerMessage.includes("rate limit") || lowerMessage.includes("rate_limit") || lowerMessage.includes("resource_exhausted");
49341
+ }
49342
+ function hasStructuredQuotaReason(details) {
49343
+ if (!Array.isArray(details)) return false;
49344
+ return details.some((detail) => {
49345
+ if (!detail || typeof detail !== "object") return false;
49346
+ const record3 = detail;
49347
+ const type = record3["@type"];
49348
+ if (typeof type === "string" && type.includes("google.rpc.QuotaFailure"))
49349
+ return true;
49350
+ const reason = record3.reason;
49351
+ if (typeof reason === "string" && QUOTA_REASON_CODES.has(reason))
49352
+ return true;
49353
+ const nested = record3.details;
49354
+ return Array.isArray(nested) ? hasStructuredQuotaReason(nested) : false;
49355
+ });
49356
+ }
49357
+ 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;
49358
+ function extractResetDurationFromText(text2) {
49359
+ if (typeof text2 !== "string" || text2.length === 0) return null;
49360
+ const regex = new RegExp(RESET_CLAUSE_REGEX.source, "i");
49361
+ const match = text2.match(regex);
49362
+ if (!match?.[1]) return null;
49363
+ const raw = match[1].trim().replace(/[.,;:]+$/, "");
49364
+ return raw.length > 0 ? raw : null;
49365
+ }
49366
+ function normalizeResetDuration(text2) {
49367
+ if (typeof text2 !== "string" || text2.length === 0) return text2;
49368
+ return text2.replace(RESET_CLAUSE_REGEX, (_match, rawDuration) => {
49369
+ if (!rawDuration) return _match;
49370
+ const duration = String(rawDuration).match(/^(.*?)([ \t]*)$/);
49371
+ if (!duration) return _match;
49372
+ const spaced = (duration[1] ?? "").replace(
49373
+ /(\d+(?:\.\d+)?)[ \t]*(ms|[dhms])(?=\d)/gi,
49374
+ "$1$2 "
49375
+ );
49376
+ return `quota resets in ${spaced}${duration[2] ?? ""}`;
49377
+ });
49378
+ }
49379
+ 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;
49380
+ function parseDecimalComponent(str, multMs) {
49381
+ const parts = str.split(".");
49382
+ const intStr = parts[0] ?? "";
49383
+ const fracStr = parts[1] ?? "";
49384
+ const effectiveIntStr = intStr.replace(/^0+/, "");
49385
+ if (effectiveIntStr.length > 15) return null;
49386
+ if (str.length > 60) return null;
49387
+ const intPart = intStr.length > 0 ? BigInt(intStr) : 0n;
49388
+ return { intPart, fracStr, mult: multMs };
49389
+ }
49390
+ function parseDurationToMsBigInt(duration, options) {
49391
+ if (typeof duration !== "string") return null;
49392
+ const trimmed = duration.trim();
49393
+ if (trimmed.length === 0) return null;
49394
+ let dStr;
49395
+ let hStr;
49396
+ let mStr;
49397
+ let sStr;
49398
+ let msStr;
49399
+ const match = trimmed.match(DURATION_REGEX);
49400
+ if (match) {
49401
+ ;
49402
+ [, dStr, hStr, mStr, sStr, msStr] = match;
49403
+ }
49404
+ if (dStr === void 0 && hStr === void 0 && mStr === void 0 && sStr === void 0 && msStr === void 0) {
49405
+ if (options?.allowBareSeconds && /^(?:\d+(?:\.\d+)?|\.\d+)$/.test(trimmed)) {
49406
+ sStr = trimmed;
49407
+ } else {
49408
+ return null;
49409
+ }
49410
+ }
49411
+ const rawComponents = [];
49412
+ if (dStr !== void 0) rawComponents.push({ str: dStr, mult: 86400000n });
49413
+ if (hStr !== void 0) rawComponents.push({ str: hStr, mult: 3600000n });
49414
+ if (mStr !== void 0) rawComponents.push({ str: mStr, mult: 60000n });
49415
+ if (sStr !== void 0) rawComponents.push({ str: sStr, mult: 1000n });
49416
+ if (msStr !== void 0) rawComponents.push({ str: msStr, mult: 1n });
49417
+ if (rawComponents.length === 0) return null;
49418
+ let maxFracDigits = 0;
49419
+ const parsedComponents = [];
49420
+ for (const rc of rawComponents) {
49421
+ const parsed = parseDecimalComponent(rc.str, rc.mult);
49422
+ if (!parsed) return null;
49423
+ if (parsed.fracStr.length > maxFracDigits) {
49424
+ maxFracDigits = parsed.fracStr.length;
49425
+ }
49426
+ parsedComponents.push(parsed);
49427
+ }
49428
+ const commonDenominator = 10n ** BigInt(maxFracDigits);
49429
+ let totalScaledNumerator = 0n;
49430
+ for (const c of parsedComponents) {
49431
+ const fracLen = BigInt(c.fracStr.length);
49432
+ const fracVal = c.fracStr.length > 0 ? BigInt(c.fracStr) : 0n;
49433
+ const scaleFactor = 10n ** (BigInt(maxFracDigits) - fracLen);
49434
+ const numerator = (c.intPart * commonDenominator + fracVal * scaleFactor) * c.mult;
49435
+ totalScaledNumerator += numerator;
49436
+ }
49437
+ if (totalScaledNumerator === 0n) {
49438
+ return options?.allowZero ? 0n : null;
49439
+ }
49440
+ const quotient = totalScaledNumerator / commonDenominator;
49441
+ const remainder = totalScaledNumerator % commonDenominator;
49442
+ let rounded = remainder * 2n >= commonDenominator ? quotient + 1n : quotient;
49443
+ if (rounded === 0n) {
49444
+ rounded = 1n;
49445
+ }
49446
+ if (rounded > MAX_FINITE_FORWARDING_MS) {
49447
+ return null;
49448
+ }
49449
+ return rounded;
49450
+ }
49451
+ function resolveRetryMetadata(options) {
49452
+ const {
49453
+ details,
49454
+ message,
49455
+ status,
49456
+ headers,
49457
+ retryAfterMs,
49458
+ resetAfterMs,
49459
+ retryAfterSeconds,
49460
+ allowZero,
49461
+ allowBareSeconds
49462
+ } = options;
49463
+ const bodyParserOptions = {
49464
+ allowZero,
49465
+ allowBareSeconds
49466
+ };
49467
+ if (Array.isArray(details)) {
49468
+ for (const entry of details) {
49469
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
49470
+ const type = entry["@type"];
49471
+ if (typeof type === "string" && type.includes("google.rpc.RetryInfo")) {
49472
+ const retryDelay = entry.retryDelay;
49473
+ if (typeof retryDelay === "string") {
49474
+ const ms = parseDurationToMsBigInt(retryDelay, bodyParserOptions);
49475
+ if (ms !== null) {
49476
+ return { delayMs: ms };
49477
+ }
49478
+ } else if (typeof retryDelay === "number") {
49479
+ if (Number.isFinite(retryDelay) && retryDelay >= 0) {
49480
+ const scaled = retryDelay * 1e3;
49481
+ if (Number.isFinite(scaled)) {
49482
+ const rounded = Math.round(scaled);
49483
+ if (Number.isSafeInteger(rounded) && rounded >= 0) {
49484
+ if (retryDelay === 0) {
49485
+ if (allowZero) return { delayMs: 0n };
49486
+ } else {
49487
+ return { delayMs: BigInt(Math.max(1, rounded)) };
49488
+ }
49489
+ }
49490
+ }
49491
+ }
49492
+ }
49493
+ }
49494
+ }
49495
+ for (const entry of details) {
49496
+ if (!entry || typeof entry !== "object" || Array.isArray(entry)) continue;
49497
+ const metadata = entry.metadata;
49498
+ if (metadata && typeof metadata === "object" && !Array.isArray(metadata)) {
49499
+ const quotaResetDelay = metadata.quotaResetDelay;
49500
+ if (typeof quotaResetDelay === "string") {
49501
+ const ms = parseDurationToMsBigInt(quotaResetDelay, bodyParserOptions);
49502
+ if (ms !== null) {
49503
+ const quotaResetTime = typeof metadata.quotaResetTimeStamp === "string" ? metadata.quotaResetTimeStamp : typeof metadata.quotaResetTime === "string" ? metadata.quotaResetTime : void 0;
49504
+ return {
49505
+ delayMs: ms,
49506
+ ...quotaResetTime !== void 0 ? { quotaResetTime } : {}
49507
+ };
49508
+ }
49509
+ }
49510
+ }
49511
+ }
49512
+ }
49513
+ const validGaMs = validateRetryAfterMsBigInt(retryAfterMs);
49514
+ if (validGaMs !== null) {
49515
+ return { delayMs: validGaMs };
49516
+ }
49517
+ const validResetMs = validateRetryAfterMsBigInt(resetAfterMs);
49518
+ if (validResetMs !== null) {
49519
+ return { delayMs: validResetMs };
49520
+ }
49521
+ const validGaSec = validateRetryAfterSecondsBigInt(retryAfterSeconds);
49522
+ if (validGaSec !== null) {
49523
+ return { delayMs: validGaSec * 1000n };
49524
+ }
49525
+ if (isQuotaError(status, message, details) && typeof message === "string") {
49526
+ const rawDuration = extractResetDurationFromText(message);
49527
+ if (rawDuration !== null) {
49528
+ const ms = parseDurationToMsBigInt(rawDuration, bodyParserOptions);
49529
+ if (ms !== null) {
49530
+ return { delayMs: ms };
49531
+ }
49532
+ }
49533
+ }
49534
+ if (headers) {
49535
+ const getHeader2 = (name) => {
49536
+ if (typeof headers.get === "function") {
49537
+ return headers.get(name);
49538
+ }
49539
+ const record3 = headers;
49540
+ for (const [key, value] of Object.entries(record3)) {
49541
+ if (key.toLowerCase() === name) return value;
49542
+ }
49543
+ return void 0;
49544
+ };
49545
+ const rawMs = getHeader2("retry-after-ms");
49546
+ const validHeaderMs = validateRetryAfterMsBigInt(rawMs);
49547
+ if (validHeaderMs !== null) {
49548
+ return { delayMs: validHeaderMs };
49549
+ }
49550
+ const rawSec = getHeader2("retry-after");
49551
+ const validHeaderSec = validateRetryAfterSecondsBigInt(rawSec);
49552
+ if (validHeaderSec !== null) {
49553
+ return { delayMs: validHeaderSec * 1000n };
49554
+ }
49555
+ }
49556
+ return null;
49557
+ }
49118
49558
 
49119
49559
  // src/plugin/thinking-recovery.ts
49120
49560
  function isThinkingPart2(part) {
@@ -50835,10 +51275,12 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
50835
51275
  const debugText = wire.debug.isDebugTuiEnabled() && Array.isArray(debugLines) && debugLines.length > 0 ? formatDebugLinesForThinking(debugLines) : wire.signatures.keepThinking ? SYNTHETIC_THINKING_PLACEHOLDER : void 0;
50836
51276
  const cacheSignatures = shouldCacheThinkingSignatures(effectiveModel);
50837
51277
  if (!isJsonResponse && !isEventStreamResponse) {
50838
- wire.debug.logAntigravityDebugResponse(debugContext, response, {
50839
- note: "Non-JSON response (body omitted)"
50840
- });
50841
- return response;
51278
+ if (response.ok) {
51279
+ wire.debug.logAntigravityDebugResponse(debugContext, response, {
51280
+ note: "Non-JSON response (body omitted)"
51281
+ });
51282
+ return response;
51283
+ }
50842
51284
  }
50843
51285
  if (streaming && response.ok && isEventStreamResponse && response.body) {
50844
51286
  const headers = new Headers(response.headers);
@@ -50887,27 +51329,143 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
50887
51329
  headers
50888
51330
  });
50889
51331
  }
50890
- const responseFallback = response.clone();
50891
- try {
51332
+ if (!response.ok) {
51333
+ const projectIds = projectId ? [projectId] : void 0;
50892
51334
  const headers = new Headers(response.headers);
50893
- const text2 = await response.text();
51335
+ const initialForwarded = collectForwardedHeaders(headers);
51336
+ if (initialForwarded["retry-after"] !== void 0 && initialForwarded["retry-after-ms"] !== void 0) {
51337
+ headers.set("Retry-After", initialForwarded["retry-after"]);
51338
+ headers.set("retry-after", initialForwarded["retry-after"]);
51339
+ headers.set("retry-after-ms", initialForwarded["retry-after-ms"]);
51340
+ } else {
51341
+ headers.delete("Retry-After");
51342
+ headers.delete("retry-after");
51343
+ headers.delete("retry-after-ms");
51344
+ }
51345
+ let text2;
51346
+ try {
51347
+ text2 = await response.text();
51348
+ } catch (readError) {
51349
+ const sanitizedCause = readError instanceof Error || readError !== null && typeof readError === "object" ? redactCredentialError(readError, void 0, projectIds) : void 0;
51350
+ const safeMessage = sanitizedCause ? sanitizedCause.message : redactCredentialText(String(readError), void 0, projectIds);
51351
+ const scrubbedStatusText = redactCredentialText(
51352
+ response.statusText,
51353
+ void 0,
51354
+ projectIds
51355
+ );
51356
+ const plainHeaders = {};
51357
+ for (const [key, value] of headers.entries()) {
51358
+ plainHeaders[key] = redactCredentialText(value, void 0, projectIds);
51359
+ }
51360
+ if (initialForwarded["retry-after"] !== void 0 && initialForwarded["retry-after-ms"] !== void 0) {
51361
+ plainHeaders["retry-after"] = initialForwarded["retry-after"];
51362
+ plainHeaders["retry-after-ms"] = initialForwarded["retry-after-ms"];
51363
+ plainHeaders["Retry-After"] = initialForwarded["retry-after"];
51364
+ }
51365
+ const freshError = new Error(
51366
+ `Failed to read response body: ${safeMessage}`,
51367
+ sanitizedCause ? { cause: sanitizedCause } : void 0
51368
+ );
51369
+ Object.assign(freshError, {
51370
+ statusCode: response.status,
51371
+ status: response.status,
51372
+ statusText: scrubbedStatusText,
51373
+ headers: plainHeaders
51374
+ });
51375
+ throw freshError;
51376
+ }
50894
51377
  noteGeminiDumpResponse(dumpContext, response);
50895
51378
  appendGeminiDumpResponseText(dumpContext, text2);
50896
- if (!response.ok) {
50897
- let errorBody;
51379
+ const createSafeFallback = (bodyContent, contentTypeOverride) => {
51380
+ const fallbackHeaders = new Headers(headers);
51381
+ fallbackHeaders.delete("content-length");
51382
+ if (contentTypeOverride) {
51383
+ fallbackHeaders.set("content-type", contentTypeOverride);
51384
+ }
51385
+ const safeText = redactProjectIdText(bodyContent, projectIds);
51386
+ const fallbackResponse = new Response(safeText, {
51387
+ status: response.status,
51388
+ statusText: response.statusText,
51389
+ headers: fallbackHeaders
51390
+ });
51391
+ return redactCredentialResponse(
51392
+ fallbackResponse,
51393
+ void 0,
51394
+ safeText,
51395
+ projectIds
51396
+ );
51397
+ };
51398
+ try {
51399
+ let parsedBody = null;
51400
+ let isJson = false;
50898
51401
  try {
50899
- errorBody = JSON.parse(text2);
51402
+ parsedBody = JSON.parse(text2);
51403
+ isJson = true;
50900
51404
  } catch {
50901
- errorBody = { error: { message: text2 } };
51405
+ isJson = false;
51406
+ }
51407
+ if (!isJson && (isEventStreamResponse || text2.includes("data:"))) {
51408
+ for (const line of text2.split("\n")) {
51409
+ const trimmed = line.trim();
51410
+ if (trimmed.startsWith("data:")) {
51411
+ const payload = trimmed.slice(5).trim();
51412
+ if (payload.length > 0 && payload !== "[DONE]") {
51413
+ try {
51414
+ parsedBody = JSON.parse(payload);
51415
+ isJson = true;
51416
+ break;
51417
+ } catch {
51418
+ }
51419
+ }
51420
+ }
51421
+ }
50902
51422
  }
50903
- if (errorBody?.error) {
50904
- const upstreamErrorMessage = typeof errorBody.error.message === "string" && errorBody.error.message.length > 0 ? errorBody.error.message : "Unknown error";
50905
- const rawErrorMessage = redactProjectIdText(upstreamErrorMessage, [
50906
- projectId ?? ""
50907
- ]);
50908
- const errorType = detectErrorType(rawErrorMessage);
50909
- const safeProjectId = maskSensitiveIdentifier(projectId) || "Unknown";
50910
- const debugInfo = `
51423
+ if (!isJson && isJsonResponse) {
51424
+ parsedBody = {
51425
+ error: {
51426
+ code: response.status,
51427
+ message: text2,
51428
+ status: "UNAVAILABLE"
51429
+ }
51430
+ };
51431
+ isJson = true;
51432
+ }
51433
+ const errorRecord = isJson ? extractAntigravityError(parsedBody) : null;
51434
+ const retryMeta = resolveRetryMetadata({
51435
+ details: errorRecord?.details,
51436
+ message: typeof errorRecord?.message === "string" ? errorRecord.message : void 0,
51437
+ status: response.status,
51438
+ headers,
51439
+ // The transformer renders what the host sees, so it follows the
51440
+ // executor's rule: an upstream zero delay falls through to the
51441
+ // response's own header instead of becoming a zero wait here.
51442
+ allowZero: false
51443
+ });
51444
+ if (retryMeta !== null) {
51445
+ const pair = deriveRetryHeaderPairFromMs(retryMeta.delayMs);
51446
+ headers.set("Retry-After", pair["retry-after"]);
51447
+ headers.set("retry-after", pair["retry-after"]);
51448
+ headers.set("retry-after-ms", pair["retry-after-ms"]);
51449
+ } else {
51450
+ headers.delete("Retry-After");
51451
+ headers.delete("retry-after");
51452
+ headers.delete("retry-after-ms");
51453
+ }
51454
+ let diagnosticErrorText = "";
51455
+ if (errorRecord && typeof errorRecord.message === "string") {
51456
+ diagnosticErrorText = errorRecord.message;
51457
+ } else if (parsedBody && typeof parsedBody === "object" && !Array.isArray(parsedBody)) {
51458
+ const errProp = parsedBody.error;
51459
+ if (typeof errProp === "string") {
51460
+ diagnosticErrorText = errProp;
51461
+ } else {
51462
+ diagnosticErrorText = text2;
51463
+ }
51464
+ } else {
51465
+ diagnosticErrorText = text2;
51466
+ }
51467
+ const safeProjectId = maskSensitiveIdentifier(projectId) || "Unknown";
51468
+ const debugInfo = `
50911
51469
 
50912
51470
  [Debug Info]
50913
51471
  Requested Model: ${requestedModel || "Unknown"}
@@ -50918,48 +51476,91 @@ Status: ${response.status}
50918
51476
  Request ID: ${headers.get("x-request-id") || "N/A"}${toolDebugMissing !== void 0 ? `
50919
51477
  Tool Debug Missing: ${toolDebugMissing}` : ""}${toolDebugSummary ? `
50920
51478
  Tool Debug Summary: ${toolDebugSummary}` : ""}`;
50921
- const injectedDebug = debugText ? `
51479
+ const injectedDebug = debugText ? `
50922
51480
 
50923
51481
  ${debugText}` : "";
50924
- errorBody.error.message = rawErrorMessage + debugInfo + injectedDebug;
50925
- if (errorType === "thinking_block_order") {
50926
- const recoveryError = new Error("THINKING_RECOVERY_NEEDED");
50927
- recoveryError.recoveryType = errorType;
50928
- recoveryError.originalError = errorBody;
50929
- recoveryError.debugInfo = debugInfo;
50930
- throw recoveryError;
50931
- }
50932
- const errorMessage = errorBody.error.message?.toLowerCase() || "";
50933
- if (errorMessage.includes("prompt is too long") || errorMessage.includes("context length exceeded") || errorMessage.includes("context_length_exceeded") || errorMessage.includes("maximum context length")) {
50934
- headers.set("x-antigravity-context-error", "prompt_too_long");
50935
- }
50936
- if (errorMessage.includes("tool_use") && errorMessage.includes("tool_result") && (errorMessage.includes("without") || errorMessage.includes("immediately after"))) {
50937
- headers.set("x-antigravity-context-error", "tool_pairing");
50938
- }
50939
- return new Response(JSON.stringify(errorBody), {
51482
+ const safeDiagnosticText = redactProjectIdText(
51483
+ diagnosticErrorText,
51484
+ projectIds
51485
+ );
51486
+ const errorType = detectErrorType(safeDiagnosticText);
51487
+ if (errorType === "thinking_block_order") {
51488
+ const recoveryError = new Error("THINKING_RECOVERY_NEEDED");
51489
+ recoveryError.recoveryType = errorType;
51490
+ recoveryError.originalError = parsedBody ?? safeDiagnosticText;
51491
+ recoveryError.debugInfo = debugInfo;
51492
+ throw recoveryError;
51493
+ }
51494
+ const errorMessageLower = safeDiagnosticText.toLowerCase();
51495
+ if (errorMessageLower.includes("prompt is too long") || errorMessageLower.includes("context length exceeded") || errorMessageLower.includes("context_length_exceeded") || errorMessageLower.includes("maximum context length")) {
51496
+ headers.set("x-antigravity-context-error", "prompt_too_long");
51497
+ }
51498
+ if (errorMessageLower.includes("tool_use") && errorMessageLower.includes("tool_result") && (errorMessageLower.includes("without") || errorMessageLower.includes("immediately after"))) {
51499
+ headers.set("x-antigravity-context-error", "tool_pairing");
51500
+ }
51501
+ if (!isJson && !isEventStreamResponse) {
51502
+ return await createSafeFallback(text2);
51503
+ }
51504
+ if (!isJson) {
51505
+ return await createSafeFallback(text2);
51506
+ }
51507
+ if (errorRecord !== null) {
51508
+ const upstreamErrorMessage = typeof errorRecord.message === "string" && errorRecord.message.length > 0 ? errorRecord.message : "Unknown error";
51509
+ const rawErrorMessage = redactProjectIdText(
51510
+ upstreamErrorMessage,
51511
+ projectIds
51512
+ );
51513
+ const isQuota = isQuotaError(
51514
+ response.status,
51515
+ upstreamErrorMessage,
51516
+ errorRecord.details
51517
+ );
51518
+ const normalizedErrorMessage = isQuota ? normalizeResetDuration(rawErrorMessage) : rawErrorMessage;
51519
+ errorRecord.message = normalizedErrorMessage + debugInfo + injectedDebug;
51520
+ const responseHeaders2 = new Headers(headers);
51521
+ responseHeaders2.delete("content-length");
51522
+ responseHeaders2.set("content-type", "application/json");
51523
+ const finalBody2 = JSON.stringify(parsedBody);
51524
+ const finalResponse2 = new Response(finalBody2, {
50940
51525
  status: response.status,
50941
51526
  statusText: response.statusText,
50942
- headers
51527
+ headers: responseHeaders2
50943
51528
  });
50944
- }
50945
- if (errorBody?.error?.details && Array.isArray(errorBody.error.details)) {
50946
- const retryInfo = errorBody.error.details.find(
50947
- (detail) => detail["@type"] === "type.googleapis.com/google.rpc.RetryInfo"
51529
+ return await redactCredentialResponse(
51530
+ finalResponse2,
51531
+ void 0,
51532
+ finalBody2,
51533
+ projectIds
50948
51534
  );
50949
- if (retryInfo?.retryDelay) {
50950
- const match = retryInfo.retryDelay.match(/^([\d.]+)s$/);
50951
- if (match?.[1]) {
50952
- const retrySeconds = parseFloat(match[1]);
50953
- if (!Number.isNaN(retrySeconds) && retrySeconds > 0) {
50954
- const retryAfterSec = Math.ceil(retrySeconds).toString();
50955
- const retryAfterMs = Math.ceil(retrySeconds * 1e3).toString();
50956
- headers.set("Retry-After", retryAfterSec);
50957
- headers.set("retry-after-ms", retryAfterMs);
50958
- }
50959
- }
50960
- }
50961
51535
  }
51536
+ const responseHeaders = new Headers(headers);
51537
+ responseHeaders.delete("content-length");
51538
+ responseHeaders.set("content-type", "application/json");
51539
+ const finalBody = JSON.stringify(parsedBody);
51540
+ const finalResponse = new Response(finalBody, {
51541
+ status: response.status,
51542
+ statusText: response.statusText,
51543
+ headers: responseHeaders
51544
+ });
51545
+ return await redactCredentialResponse(
51546
+ finalResponse,
51547
+ void 0,
51548
+ finalBody,
51549
+ projectIds
51550
+ );
51551
+ } catch (transformError) {
51552
+ if (transformError instanceof Error && transformError.message === "THINKING_RECOVERY_NEEDED") {
51553
+ throw transformError;
51554
+ }
51555
+ return await createSafeFallback(text2);
50962
51556
  }
51557
+ }
51558
+ const responseFallback = response.clone();
51559
+ try {
51560
+ const headers = new Headers(response.headers);
51561
+ const text2 = await response.text();
51562
+ noteGeminiDumpResponse(dumpContext, response);
51563
+ appendGeminiDumpResponseText(dumpContext, text2);
50963
51564
  const init = {
50964
51565
  status: response.status,
50965
51566
  statusText: response.statusText,
@@ -52185,7 +52786,7 @@ var BackgroundVaultQuotaRefresh = class {
52185
52786
  outcome.stage = "roster";
52186
52787
  const { source, pool } = await this.options.currentVaultPool();
52187
52788
  await this.assertActive(controller);
52188
- await pool.sync();
52789
+ await pool.sync(controller.signal);
52189
52790
  await this.assertActive(controller);
52190
52791
  outcome.stage = "state";
52191
52792
  const state = await this.options.readProviderState();
@@ -54055,23 +54656,6 @@ function createNoAccountResponse(message, model) {
54055
54656
  function terminalFetchError(lastError, fallbackMessage) {
54056
54657
  return lastError ?? new Error(fallbackMessage);
54057
54658
  }
54058
- function retryAfterMsFromResponse(response, defaultRetryMs = 6e4) {
54059
- const retryAfterMsHeader = response.headers.get("retry-after-ms");
54060
- if (retryAfterMsHeader) {
54061
- const parsed = Number.parseInt(retryAfterMsHeader, 10);
54062
- if (!Number.isNaN(parsed) && parsed > 0) {
54063
- return parsed;
54064
- }
54065
- }
54066
- const retryAfterHeader = response.headers.get("retry-after");
54067
- if (retryAfterHeader) {
54068
- const parsed = Number.parseInt(retryAfterHeader, 10);
54069
- if (!Number.isNaN(parsed) && parsed > 0) {
54070
- return parsed * 1e3;
54071
- }
54072
- }
54073
- return defaultRetryMs;
54074
- }
54075
54659
  function formatWaitTime(ms) {
54076
54660
  if (ms < 1e3) return `${ms}ms`;
54077
54661
  const seconds = Math.ceil(ms / 1e3);
@@ -54093,10 +54677,11 @@ function sleep4(ms, signal) {
54093
54677
  );
54094
54678
  return;
54095
54679
  }
54680
+ const timerMs = Math.min(Math.max(0, Math.floor(ms)), 2147483647);
54096
54681
  const timeout = setTimeout(() => {
54097
54682
  cleanup2();
54098
54683
  resolve27();
54099
- }, ms);
54684
+ }, timerMs);
54100
54685
  const onAbort = () => {
54101
54686
  cleanup2();
54102
54687
  reject(
@@ -54191,7 +54776,7 @@ function createRequestExecutor(deps) {
54191
54776
  };
54192
54777
  async function execute(input2, init, options, selectedCredentials, selectedProjectIds, deadline, waitPolicy) {
54193
54778
  const assertAdmission = async () => {
54194
- await deadline.wait(() => deps.assertAdmission?.());
54779
+ await deadline.wait(() => deps.assertAdmission?.(deadline.signal));
54195
54780
  };
54196
54781
  const logResponseBody2 = (...args) => deadline.wait(() => debug.logResponseBody(...args));
54197
54782
  await assertAdmission();
@@ -55203,10 +55788,6 @@ function createRequestExecutor(deps) {
55203
55788
  }
55204
55789
  const defaultRetryMs = (config.default_retry_after_seconds ?? 60) * 1e3;
55205
55790
  const _maxBackoffMs = (config.max_backoff_seconds ?? 60) * 1e3;
55206
- const headerRetryMs = retryAfterMsFromResponse(
55207
- response,
55208
- defaultRetryMs
55209
- );
55210
55791
  const bodyInfo = await (async () => {
55211
55792
  try {
55212
55793
  const text2 = await deadline.wait(
@@ -55222,8 +55803,12 @@ function createRequestExecutor(deps) {
55222
55803
  return null;
55223
55804
  }
55224
55805
  })();
55225
- const reasonInfo = bodyInfo ? extractRateLimitBodyInfo(bodyInfo) : { retryDelayMs: null };
55226
- const serverRetryMs = reasonInfo.retryDelayMs ?? headerRetryMs;
55806
+ const reasonInfo = extractRateLimitBodyInfo(
55807
+ bodyInfo,
55808
+ response.status,
55809
+ response.headers
55810
+ );
55811
+ const serverRetryMs = reasonInfo.retryDelayMs ?? defaultRetryMs;
55227
55812
  const rateLimitReason = parseRateLimitReason(
55228
55813
  reasonInfo.reason,
55229
55814
  reasonInfo.message,
@@ -55990,15 +56575,15 @@ function parseModelUnavailableError(bodyText) {
55990
56575
  }
55991
56576
  return { status: "NOT_FOUND", reasons };
55992
56577
  }
55993
- function extractRateLimitBodyInfo(body) {
55994
- if (!body || typeof body !== "object") return { retryDelayMs: null };
55995
- const error = body.error;
55996
- const message = error && typeof error === "object" ? error.message : void 0;
55997
- const details = error && typeof error === "object" ? error.details : void 0;
56578
+ function extractRateLimitBodyInfo(body, status, headers) {
56579
+ const errorRecord = extractAntigravityError(body);
56580
+ const message = errorRecord && typeof errorRecord.message === "string" ? errorRecord.message : void 0;
56581
+ const details = errorRecord && Array.isArray(errorRecord.details) ? errorRecord.details : void 0;
55998
56582
  let reason;
55999
56583
  if (Array.isArray(details)) {
56000
56584
  for (const detail of details) {
56001
- if (!detail || typeof detail !== "object") continue;
56585
+ if (!detail || typeof detail !== "object" || Array.isArray(detail))
56586
+ continue;
56002
56587
  const type = detail["@type"];
56003
56588
  if (typeof type === "string" && type.includes("google.rpc.ErrorInfo")) {
56004
56589
  const detailReason = detail.reason;
@@ -56008,95 +56593,28 @@ function extractRateLimitBodyInfo(body) {
56008
56593
  }
56009
56594
  }
56010
56595
  }
56011
- for (const detail of details) {
56012
- if (!detail || typeof detail !== "object") continue;
56013
- const type = detail["@type"];
56014
- if (typeof type === "string" && type.includes("google.rpc.RetryInfo")) {
56015
- const retryDelay = detail.retryDelay;
56016
- if (typeof retryDelay === "string") {
56017
- const retryDelayMs = parseDurationToMs(retryDelay);
56018
- if (retryDelayMs !== null) {
56019
- return { retryDelayMs, message, reason };
56020
- }
56021
- }
56022
- }
56023
- }
56024
- for (const detail of details) {
56025
- if (!detail || typeof detail !== "object") continue;
56026
- const metadata = detail.metadata;
56027
- if (metadata && typeof metadata === "object") {
56028
- const quotaResetDelay = metadata.quotaResetDelay;
56029
- const quotaResetTime = metadata.quotaResetTimeStamp;
56030
- if (typeof quotaResetDelay === "string") {
56031
- const quotaResetDelayMs = parseDurationToMs(quotaResetDelay);
56032
- if (quotaResetDelayMs !== null) {
56033
- return {
56034
- retryDelayMs: quotaResetDelayMs,
56035
- message,
56036
- quotaResetTime,
56037
- reason
56038
- };
56039
- }
56040
- }
56041
- }
56042
- }
56043
- }
56044
- if (message) {
56045
- const reset = message.match(/(?:reset after|resets? in)\s+([0-9hms.]+)/i);
56046
- const rawDuration = reset?.[1];
56047
- if (rawDuration) {
56048
- const parsed = parseDurationToMs(rawDuration);
56049
- if (parsed !== null) {
56050
- return { retryDelayMs: parsed, message, reason };
56051
- }
56052
- }
56053
- }
56054
- return { retryDelayMs: null, message, reason };
56055
- }
56056
- function parseDurationToMs(duration) {
56057
- const simpleMatch = duration.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/i);
56058
- if (simpleMatch) {
56059
- const value = parseFloat(simpleMatch[1]);
56060
- const unit = (simpleMatch[2] || "s").toLowerCase();
56061
- switch (unit) {
56062
- case "h":
56063
- return value * 3600 * 1e3;
56064
- case "m":
56065
- return value * 60 * 1e3;
56066
- case "s":
56067
- return value * 1e3;
56068
- case "ms":
56069
- return value;
56070
- default:
56071
- return value * 1e3;
56072
- }
56073
- }
56074
- const compoundRegex = /(\d+(?:\.\d+)?)(h|m(?!s)|s|ms)/gi;
56075
- let totalMs = 0;
56076
- let matchFound = false;
56077
- let match = null;
56078
- while (true) {
56079
- match = compoundRegex.exec(duration);
56080
- if (match === null) break;
56081
- matchFound = true;
56082
- const value = parseFloat(match[1]);
56083
- const unit = match[2]?.toLowerCase();
56084
- switch (unit) {
56085
- case "h":
56086
- totalMs += value * 3600 * 1e3;
56087
- break;
56088
- case "m":
56089
- totalMs += value * 60 * 1e3;
56090
- break;
56091
- case "s":
56092
- totalMs += value * 1e3;
56093
- break;
56094
- case "ms":
56095
- totalMs += value;
56096
- break;
56097
- }
56098
56596
  }
56099
- return matchFound ? totalMs : null;
56597
+ const resolved = resolveRetryMetadata({
56598
+ details,
56599
+ message,
56600
+ status,
56601
+ headers,
56602
+ // The executor keeps its historical reading of Google's body fields: an
56603
+ // upstream zero ("0s") falls through to the configured default retry
56604
+ // instead of retrying immediately, and a unitless delay such as "90"
56605
+ // still means 90 seconds.
56606
+ allowZero: false,
56607
+ allowBareSeconds: true
56608
+ });
56609
+ const retryDelayMs = resolved !== null ? Number(
56610
+ resolved.delayMs > BigInt(Number.MAX_SAFE_INTEGER) ? BigInt(Number.MAX_SAFE_INTEGER) : resolved.delayMs
56611
+ ) : null;
56612
+ return {
56613
+ retryDelayMs,
56614
+ message,
56615
+ quotaResetTime: resolved?.quotaResetTime,
56616
+ reason
56617
+ };
56100
56618
  }
56101
56619
 
56102
56620
  // src/plugin/fetch-interceptor.ts
@@ -56289,7 +56807,10 @@ function createVaultFetchInterceptor(context) {
56289
56807
  const pool = context.pool ?? createVaultAccountPool({ source });
56290
56808
  const selector = pool.selector;
56291
56809
  const executor = createRequestExecutor({
56292
- assertAdmission: context.assertAdmission,
56810
+ assertAdmission: async (signal) => {
56811
+ await context.assertAdmission?.();
56812
+ await pool.sync(signal);
56813
+ },
56293
56814
  ...openCode1EngineCollaborators({
56294
56815
  ...context,
56295
56816
  transport: agyTransport
@@ -56306,7 +56827,6 @@ function createVaultFetchInterceptor(context) {
56306
56827
  async function fetch(input2, init) {
56307
56828
  if (!isGenerativeLanguageRequest(input2)) return upstreamFetch(input2, init);
56308
56829
  if (disposed) throw new Error("The vault request runtime is disposed");
56309
- await pool.sync();
56310
56830
  return executor.execute(input2, init);
56311
56831
  }
56312
56832
  function dispose() {
@@ -56788,7 +57308,8 @@ function createVaultAccountMenuSections(pool, selectorOf, checkQuota) {
56788
57308
  return {
56789
57309
  accounts: {
56790
57310
  title: "Accounts",
56791
- build: () => {
57311
+ build: async () => {
57312
+ await pool.syncForDisplay();
56792
57313
  const rows = pool.selector.rows;
56793
57314
  return {
56794
57315
  lines: [
@@ -56804,7 +57325,8 @@ function createVaultAccountMenuSections(pool, selectorOf, checkQuota) {
56804
57325
  },
56805
57326
  quota: {
56806
57327
  title: "Quota",
56807
- build: () => {
57328
+ build: async () => {
57329
+ await pool.syncForDisplay();
56808
57330
  const rows = pool.selector.rows;
56809
57331
  return {
56810
57332
  lines: rows.length === 0 ? [] : rows.map(
@@ -57018,7 +57540,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
57018
57540
  },
57019
57541
  vault: async () => {
57020
57542
  const { pool } = await currentVaultPool();
57021
- await pool.sync();
57543
+ await pool.syncCached();
57022
57544
  const projection = buildVaultSidebarProjection(
57023
57545
  pool,
57024
57546
  await vaultCustody.readState(),
@@ -57220,7 +57742,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
57220
57742
  let current;
57221
57743
  try {
57222
57744
  current = await currentVaultPool();
57223
- await current.pool.sync();
57745
+ await current.pool.syncForDisplay();
57224
57746
  } catch {
57225
57747
  return showUnavailableVaultMenu();
57226
57748
  }