@cortexkit/opencode-antigravity-auth 3.0.26 → 3.0.28

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 (57) hide show
  1. package/dist/cli.js.map +1 -1
  2. package/dist/cli.meta.json +2 -2
  3. package/dist/index.js +670 -201
  4. package/dist/index.js.map +3 -3
  5. package/dist/index.meta.json +18 -18
  6. package/dist/server.js +876 -326
  7. package/dist/server.js.map +4 -4
  8. package/dist/server.meta.json +1 -1
  9. package/dist/src/ga/server/index.d.ts +3 -1
  10. package/dist/src/ga/server/index.d.ts.map +1 -1
  11. package/dist/src/ga/server/index.js +89 -6
  12. package/dist/src/ga/server/index.js.map +1 -1
  13. package/dist/src/plugin/background-vault-quota-refresh.js +1 -1
  14. package/dist/src/plugin/background-vault-quota-refresh.js.map +1 -1
  15. package/dist/src/plugin/fetch-interceptor.d.ts.map +1 -1
  16. package/dist/src/plugin/fetch-interceptor.js +4 -2
  17. package/dist/src/plugin/fetch-interceptor.js.map +1 -1
  18. package/dist/src/plugin/ga-location-services.d.ts +1 -1
  19. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  20. package/dist/src/plugin/ga-location-services.js +28 -20
  21. package/dist/src/plugin/ga-location-services.js.map +1 -1
  22. package/dist/src/plugin/index.js +2 -2
  23. package/dist/src/plugin/index.js.map +1 -1
  24. package/dist/src/plugin/request-helpers.d.ts +139 -0
  25. package/dist/src/plugin/request-helpers.d.ts.map +1 -1
  26. package/dist/src/plugin/request-helpers.js +512 -0
  27. package/dist/src/plugin/request-helpers.js.map +1 -1
  28. package/dist/src/plugin/request.d.ts.map +1 -1
  29. package/dist/src/plugin/request.js +219 -63
  30. package/dist/src/plugin/request.js.map +1 -1
  31. package/dist/src/plugin/shared/request-services.d.ts +1 -1
  32. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  33. package/dist/src/plugin/shared/request-services.js +36 -127
  34. package/dist/src/plugin/shared/request-services.js.map +1 -1
  35. package/dist/src/plugin/shared/vault-menu.d.ts +1 -1
  36. package/dist/src/plugin/shared/vault-menu.d.ts.map +1 -1
  37. package/dist/src/plugin/shared/vault-menu.js +4 -2
  38. package/dist/src/plugin/shared/vault-menu.js.map +1 -1
  39. package/dist/src/plugin/shared/vault-request-credentials.d.ts +11 -4
  40. package/dist/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  41. package/dist/src/plugin/shared/vault-request-credentials.js +67 -16
  42. package/dist/src/plugin/shared/vault-request-credentials.js.map +1 -1
  43. package/dist/types/src/ga/server/index.d.ts +3 -1
  44. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  45. package/dist/types/src/plugin/fetch-interceptor.d.ts.map +1 -1
  46. package/dist/types/src/plugin/ga-location-services.d.ts +1 -1
  47. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  48. package/dist/types/src/plugin/request-helpers.d.ts +139 -0
  49. package/dist/types/src/plugin/request-helpers.d.ts.map +1 -1
  50. package/dist/types/src/plugin/request.d.ts.map +1 -1
  51. package/dist/types/src/plugin/shared/request-services.d.ts +1 -1
  52. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  53. package/dist/types/src/plugin/shared/vault-menu.d.ts +1 -1
  54. package/dist/types/src/plugin/shared/vault-menu.d.ts.map +1 -1
  55. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts +11 -4
  56. package/dist/types/src/plugin/shared/vault-request-credentials.d.ts.map +1 -1
  57. package/package.json +2 -2
package/dist/server.js CHANGED
@@ -29931,6 +29931,11 @@ function createVaultAccountPool(options) {
29931
29931
  };
29932
29932
  let firstRead = null;
29933
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
+ });
29934
29939
  let readGeneration = 0;
29935
29940
  let firstReadStartedAt = null;
29936
29941
  const readOnce = () => {
@@ -29945,7 +29950,11 @@ function createVaultAccountPool(options) {
29945
29950
  firstRead = (async () => {
29946
29951
  await source.refresh();
29947
29952
  const rows = await rowsFromSource();
29948
- if (current()) selector.resetAccounts(rows);
29953
+ if (current())
29954
+ selector.replaceAccounts(rows, {
29955
+ keyOf: vaultAccountRowKey,
29956
+ refresh: refreshVaultAccountRow
29957
+ });
29949
29958
  })().then(
29950
29959
  () => {
29951
29960
  if (current()) firstReadStartedAt = null;
@@ -29960,39 +29969,64 @@ function createVaultAccountPool(options) {
29960
29969
  );
29961
29970
  return firstRead;
29962
29971
  };
29963
- const waitForFirstRoster = async () => {
29964
- let timer;
29972
+ const waitForRead = async (read, signal, remaining) => {
29973
+ let cancelTimer2;
29974
+ let detachAbort;
29965
29975
  try {
29966
- await Promise.race([
29967
- readOnce(),
29968
- new Promise((_, reject) => {
29969
- timer = setTimeout(
29970
- () => reject(
29971
- new Error(
29972
- "The vault roster is not available yet. Check vault access and try the request again."
29973
- )
29974
- ),
29975
- 2e3
29976
- );
29977
- 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();
29978
29985
  })
29979
29986
  ]);
29980
29987
  } finally {
29981
- clearTimeout(timer);
29988
+ cancelTimer2?.();
29989
+ detachAbort?.();
29982
29990
  }
29983
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
+ };
29984
30003
  return {
29985
30004
  selector,
29986
30005
  credentials,
29987
30006
  state,
29988
- async sync() {
30007
+ async sync(signal) {
29989
30008
  const pending = firstRead;
29990
- await waitForFirstRoster();
30009
+ await waitForFirstRoster(signal);
29991
30010
  if (pending !== null) await replace();
29992
30011
  },
29993
- async refresh() {
29994
- await waitForFirstRoster();
29995
- 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);
29996
30030
  await replace();
29997
30031
  },
29998
30032
  flush: async () => {
@@ -30092,7 +30126,7 @@ async function checkVaultQuota(input2) {
30092
30126
  }
30093
30127
  return { checked, notChecked: rows.length - checked };
30094
30128
  }
30095
- var VaultSendGrant, VAULT_REFRESH_STALL_MS;
30129
+ var VaultSendGrant, VAULT_REFRESH_STALL_MS, VAULT_DISPLAY_ROSTER_WAIT_MS;
30096
30130
  var init_vault_request_credentials = __esm({
30097
30131
  "src/plugin/shared/vault-request-credentials.ts"() {
30098
30132
  "use strict";
@@ -30118,6 +30152,7 @@ var init_vault_request_credentials = __esm({
30118
30152
  }
30119
30153
  };
30120
30154
  VAULT_REFRESH_STALL_MS = 3e4;
30155
+ VAULT_DISPLAY_ROSTER_WAIT_MS = 2e3;
30121
30156
  }
30122
30157
  });
30123
30158
 
@@ -37901,7 +37936,7 @@ var BackgroundVaultQuotaRefresh = class {
37901
37936
  outcome.stage = "roster";
37902
37937
  const { source, pool } = await this.options.currentVaultPool();
37903
37938
  await this.assertActive(controller);
37904
- await pool.sync();
37939
+ await pool.sync(controller.signal);
37905
37940
  await this.assertActive(controller);
37906
37941
  outcome.stage = "state";
37907
37942
  const state = await this.options.readProviderState();
@@ -41660,6 +41695,358 @@ function createNativeGoogleErrorResponse(options) {
41660
41695
  headers
41661
41696
  });
41662
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
+ }
41663
42050
 
41664
42051
  // src/plugin/thinking-recovery.ts
41665
42052
  function isThinkingPart2(part) {
@@ -43380,10 +43767,12 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
43380
43767
  const debugText = wire.debug.isDebugTuiEnabled() && Array.isArray(debugLines) && debugLines.length > 0 ? formatDebugLinesForThinking(debugLines) : wire.signatures.keepThinking ? SYNTHETIC_THINKING_PLACEHOLDER : void 0;
43381
43768
  const cacheSignatures = shouldCacheThinkingSignatures(effectiveModel);
43382
43769
  if (!isJsonResponse && !isEventStreamResponse) {
43383
- wire.debug.logAntigravityDebugResponse(debugContext, response, {
43384
- note: "Non-JSON response (body omitted)"
43385
- });
43386
- return response;
43770
+ if (response.ok) {
43771
+ wire.debug.logAntigravityDebugResponse(debugContext, response, {
43772
+ note: "Non-JSON response (body omitted)"
43773
+ });
43774
+ return response;
43775
+ }
43387
43776
  }
43388
43777
  if (streaming && response.ok && isEventStreamResponse && response.body) {
43389
43778
  const headers = new Headers(response.headers);
@@ -43432,27 +43821,143 @@ async function transformAntigravityResponseIn(wire, response, streaming, debugCo
43432
43821
  headers
43433
43822
  });
43434
43823
  }
43435
- const responseFallback = response.clone();
43436
- try {
43824
+ if (!response.ok) {
43825
+ const projectIds = projectId ? [projectId] : void 0;
43437
43826
  const headers = new Headers(response.headers);
43438
- 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
+ }
43439
43869
  noteGeminiDumpResponse(dumpContext, response);
43440
43870
  appendGeminiDumpResponseText(dumpContext, text2);
43441
- if (!response.ok) {
43442
- 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;
43443
43893
  try {
43444
- errorBody = JSON.parse(text2);
43894
+ parsedBody = JSON.parse(text2);
43895
+ isJson = true;
43445
43896
  } catch {
43446
- 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
+ }
43447
43914
  }
43448
- if (errorBody?.error) {
43449
- const upstreamErrorMessage = typeof errorBody.error.message === "string" && errorBody.error.message.length > 0 ? errorBody.error.message : "Unknown error";
43450
- const rawErrorMessage = redactProjectIdText(upstreamErrorMessage, [
43451
- projectId ?? ""
43452
- ]);
43453
- const errorType = detectErrorType(rawErrorMessage);
43454
- const safeProjectId = maskSensitiveIdentifier(projectId) || "Unknown";
43455
- 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 = `
43456
43961
 
43457
43962
  [Debug Info]
43458
43963
  Requested Model: ${requestedModel || "Unknown"}
@@ -43463,48 +43968,91 @@ Status: ${response.status}
43463
43968
  Request ID: ${headers.get("x-request-id") || "N/A"}${toolDebugMissing !== void 0 ? `
43464
43969
  Tool Debug Missing: ${toolDebugMissing}` : ""}${toolDebugSummary ? `
43465
43970
  Tool Debug Summary: ${toolDebugSummary}` : ""}`;
43466
- const injectedDebug = debugText ? `
43971
+ const injectedDebug = debugText ? `
43467
43972
 
43468
43973
  ${debugText}` : "";
43469
- errorBody.error.message = rawErrorMessage + debugInfo + injectedDebug;
43470
- if (errorType === "thinking_block_order") {
43471
- const recoveryError = new Error("THINKING_RECOVERY_NEEDED");
43472
- recoveryError.recoveryType = errorType;
43473
- recoveryError.originalError = errorBody;
43474
- recoveryError.debugInfo = debugInfo;
43475
- throw recoveryError;
43476
- }
43477
- const errorMessage2 = errorBody.error.message?.toLowerCase() || "";
43478
- if (errorMessage2.includes("prompt is too long") || errorMessage2.includes("context length exceeded") || errorMessage2.includes("context_length_exceeded") || errorMessage2.includes("maximum context length")) {
43479
- headers.set("x-antigravity-context-error", "prompt_too_long");
43480
- }
43481
- if (errorMessage2.includes("tool_use") && errorMessage2.includes("tool_result") && (errorMessage2.includes("without") || errorMessage2.includes("immediately after"))) {
43482
- headers.set("x-antigravity-context-error", "tool_pairing");
43483
- }
43484
- 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, {
43485
44017
  status: response.status,
43486
44018
  statusText: response.statusText,
43487
- headers
44019
+ headers: responseHeaders2
43488
44020
  });
43489
- }
43490
- if (errorBody?.error?.details && Array.isArray(errorBody.error.details)) {
43491
- const retryInfo = errorBody.error.details.find(
43492
- (detail) => detail["@type"] === "type.googleapis.com/google.rpc.RetryInfo"
44021
+ return await redactCredentialResponse(
44022
+ finalResponse2,
44023
+ void 0,
44024
+ finalBody2,
44025
+ projectIds
43493
44026
  );
43494
- if (retryInfo?.retryDelay) {
43495
- const match = retryInfo.retryDelay.match(/^([\d.]+)s$/);
43496
- if (match?.[1]) {
43497
- const retrySeconds = parseFloat(match[1]);
43498
- if (!Number.isNaN(retrySeconds) && retrySeconds > 0) {
43499
- const retryAfterSec = Math.ceil(retrySeconds).toString();
43500
- const retryAfterMs = Math.ceil(retrySeconds * 1e3).toString();
43501
- headers.set("Retry-After", retryAfterSec);
43502
- headers.set("retry-after-ms", retryAfterMs);
43503
- }
43504
- }
43505
- }
43506
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);
43507
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);
43508
44056
  const init = {
43509
44057
  status: response.status,
43510
44058
  statusText: response.statusText,
@@ -44011,6 +44559,111 @@ function isFlushReport(value) {
44011
44559
  return typeof value === "object" && value !== null && "completed" in value && typeof value.completed === "number" && "failures" in value && Array.isArray(value.failures);
44012
44560
  }
44013
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
+
44014
44667
  // src/plugin/shared/request-services.ts
44015
44668
  init_dist();
44016
44669
 
@@ -44579,111 +45232,6 @@ function throwIfAllKilled(input2) {
44579
45232
  });
44580
45233
  }
44581
45234
 
44582
- // src/plugin/shared/request-cancellation.ts
44583
- function createRequestCancellation(signals) {
44584
- const controller = new AbortController();
44585
- const remove2 = [];
44586
- const release2 = () => {
44587
- for (const detach of remove2.splice(0)) detach();
44588
- };
44589
- for (const source of signals) {
44590
- if (source.aborted) {
44591
- controller.abort(source.reason);
44592
- release2();
44593
- break;
44594
- }
44595
- const forward = () => {
44596
- controller.abort(source.reason);
44597
- release2();
44598
- };
44599
- remove2.push(() => source.removeEventListener("abort", forward));
44600
- source.addEventListener("abort", forward, { once: true });
44601
- if (source.aborted) forward();
44602
- if (controller.signal.aborted) break;
44603
- }
44604
- return { signal: controller.signal, release: release2 };
44605
- }
44606
- async function retainResponseLifetime(response, cancellation) {
44607
- if (!response.body) {
44608
- cancellation.release();
44609
- return { response, settled: Promise.resolve() };
44610
- }
44611
- let reader;
44612
- try {
44613
- reader = response.body.getReader();
44614
- } catch (error) {
44615
- cancellation.release();
44616
- throw error;
44617
- }
44618
- let resolve28 = () => {
44619
- };
44620
- const settled = new Promise((done) => {
44621
- resolve28 = done;
44622
- });
44623
- let stopping = false;
44624
- let finished = false;
44625
- let controller;
44626
- const finish = () => {
44627
- if (finished) return;
44628
- finished = true;
44629
- cancellation.signal.removeEventListener("abort", abort);
44630
- cancellation.release();
44631
- resolve28();
44632
- };
44633
- const abort = () => {
44634
- if (finished || stopping) return;
44635
- stopping = true;
44636
- const reason = cancellation.signal.reason;
44637
- controller.error(reason);
44638
- void reader.cancel(reason).then(finish, finish);
44639
- };
44640
- const body = new ReadableStream({
44641
- start(output2) {
44642
- controller = output2;
44643
- cancellation.signal.addEventListener("abort", abort, { once: true });
44644
- if (cancellation.signal.aborted) abort();
44645
- },
44646
- async pull(output2) {
44647
- try {
44648
- const next = await reader.read();
44649
- if (stopping) return;
44650
- if (next.done) {
44651
- output2.close();
44652
- finish();
44653
- } else {
44654
- output2.enqueue(next.value);
44655
- }
44656
- } catch (error) {
44657
- if (stopping) return;
44658
- output2.error(error);
44659
- finish();
44660
- }
44661
- },
44662
- async cancel(reason) {
44663
- stopping = true;
44664
- try {
44665
- await reader.cancel(reason);
44666
- } finally {
44667
- finish();
44668
- }
44669
- }
44670
- });
44671
- try {
44672
- return {
44673
- response: new Response(body, {
44674
- status: response.status,
44675
- statusText: response.statusText,
44676
- headers: response.headers
44677
- }),
44678
- settled
44679
- };
44680
- } catch (error) {
44681
- stopping = true;
44682
- await reader.cancel(error).then(finish, finish);
44683
- throw error;
44684
- }
44685
- }
44686
-
44687
45235
  // src/plugin/shared/after-handoff.ts
44688
45236
  function createAfterHandoff(work, signals, onFailure) {
44689
45237
  const controller = new AbortController();
@@ -45007,23 +45555,6 @@ function createNoAccountResponse(message, model) {
45007
45555
  function terminalFetchError(lastError, fallbackMessage) {
45008
45556
  return lastError ?? new Error(fallbackMessage);
45009
45557
  }
45010
- function retryAfterMsFromResponse(response, defaultRetryMs = 6e4) {
45011
- const retryAfterMsHeader = response.headers.get("retry-after-ms");
45012
- if (retryAfterMsHeader) {
45013
- const parsed = Number.parseInt(retryAfterMsHeader, 10);
45014
- if (!Number.isNaN(parsed) && parsed > 0) {
45015
- return parsed;
45016
- }
45017
- }
45018
- const retryAfterHeader = response.headers.get("retry-after");
45019
- if (retryAfterHeader) {
45020
- const parsed = Number.parseInt(retryAfterHeader, 10);
45021
- if (!Number.isNaN(parsed) && parsed > 0) {
45022
- return parsed * 1e3;
45023
- }
45024
- }
45025
- return defaultRetryMs;
45026
- }
45027
45558
  function formatWaitTime(ms) {
45028
45559
  if (ms < 1e3) return `${ms}ms`;
45029
45560
  const seconds = Math.ceil(ms / 1e3);
@@ -45045,10 +45576,11 @@ function sleep4(ms, signal) {
45045
45576
  );
45046
45577
  return;
45047
45578
  }
45579
+ const timerMs = Math.min(Math.max(0, Math.floor(ms)), 2147483647);
45048
45580
  const timeout = setTimeout(() => {
45049
45581
  cleanup2();
45050
45582
  resolve28();
45051
- }, ms);
45583
+ }, timerMs);
45052
45584
  const onAbort = () => {
45053
45585
  cleanup2();
45054
45586
  reject(
@@ -45143,7 +45675,7 @@ function createRequestExecutor(deps) {
45143
45675
  };
45144
45676
  async function execute(input2, init, options, selectedCredentials, selectedProjectIds, deadline, waitPolicy) {
45145
45677
  const assertAdmission = async () => {
45146
- await deadline.wait(() => deps.assertAdmission?.());
45678
+ await deadline.wait(() => deps.assertAdmission?.(deadline.signal));
45147
45679
  };
45148
45680
  const logResponseBody2 = (...args) => deadline.wait(() => debug.logResponseBody(...args));
45149
45681
  await assertAdmission();
@@ -46155,10 +46687,6 @@ function createRequestExecutor(deps) {
46155
46687
  }
46156
46688
  const defaultRetryMs = (config.default_retry_after_seconds ?? 60) * 1e3;
46157
46689
  const _maxBackoffMs = (config.max_backoff_seconds ?? 60) * 1e3;
46158
- const headerRetryMs = retryAfterMsFromResponse(
46159
- response,
46160
- defaultRetryMs
46161
- );
46162
46690
  const bodyInfo = await (async () => {
46163
46691
  try {
46164
46692
  const text2 = await deadline.wait(
@@ -46174,8 +46702,12 @@ function createRequestExecutor(deps) {
46174
46702
  return null;
46175
46703
  }
46176
46704
  })();
46177
- const reasonInfo = bodyInfo ? extractRateLimitBodyInfo(bodyInfo) : { retryDelayMs: null };
46178
- const serverRetryMs = reasonInfo.retryDelayMs ?? headerRetryMs;
46705
+ const reasonInfo = extractRateLimitBodyInfo(
46706
+ bodyInfo,
46707
+ response.status,
46708
+ response.headers
46709
+ );
46710
+ const serverRetryMs = reasonInfo.retryDelayMs ?? defaultRetryMs;
46179
46711
  const rateLimitReason = parseRateLimitReason(
46180
46712
  reasonInfo.reason,
46181
46713
  reasonInfo.message,
@@ -46942,15 +47474,15 @@ function parseModelUnavailableError(bodyText) {
46942
47474
  }
46943
47475
  return { status: "NOT_FOUND", reasons };
46944
47476
  }
46945
- function extractRateLimitBodyInfo(body) {
46946
- if (!body || typeof body !== "object") return { retryDelayMs: null };
46947
- const error = body.error;
46948
- const message = error && typeof error === "object" ? error.message : void 0;
46949
- 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;
46950
47481
  let reason;
46951
47482
  if (Array.isArray(details)) {
46952
47483
  for (const detail of details) {
46953
- if (!detail || typeof detail !== "object") continue;
47484
+ if (!detail || typeof detail !== "object" || Array.isArray(detail))
47485
+ continue;
46954
47486
  const type = detail["@type"];
46955
47487
  if (typeof type === "string" && type.includes("google.rpc.ErrorInfo")) {
46956
47488
  const detailReason = detail.reason;
@@ -46960,95 +47492,28 @@ function extractRateLimitBodyInfo(body) {
46960
47492
  }
46961
47493
  }
46962
47494
  }
46963
- for (const detail of details) {
46964
- if (!detail || typeof detail !== "object") continue;
46965
- const type = detail["@type"];
46966
- if (typeof type === "string" && type.includes("google.rpc.RetryInfo")) {
46967
- const retryDelay = detail.retryDelay;
46968
- if (typeof retryDelay === "string") {
46969
- const retryDelayMs = parseDurationToMs(retryDelay);
46970
- if (retryDelayMs !== null) {
46971
- return { retryDelayMs, message, reason };
46972
- }
46973
- }
46974
- }
46975
- }
46976
- for (const detail of details) {
46977
- if (!detail || typeof detail !== "object") continue;
46978
- const metadata = detail.metadata;
46979
- if (metadata && typeof metadata === "object") {
46980
- const quotaResetDelay = metadata.quotaResetDelay;
46981
- const quotaResetTime = metadata.quotaResetTimeStamp;
46982
- if (typeof quotaResetDelay === "string") {
46983
- const quotaResetDelayMs = parseDurationToMs(quotaResetDelay);
46984
- if (quotaResetDelayMs !== null) {
46985
- return {
46986
- retryDelayMs: quotaResetDelayMs,
46987
- message,
46988
- quotaResetTime,
46989
- reason
46990
- };
46991
- }
46992
- }
46993
- }
46994
- }
46995
- }
46996
- if (message) {
46997
- const reset = message.match(/(?:reset after|resets? in)\s+([0-9hms.]+)/i);
46998
- const rawDuration = reset?.[1];
46999
- if (rawDuration) {
47000
- const parsed = parseDurationToMs(rawDuration);
47001
- if (parsed !== null) {
47002
- return { retryDelayMs: parsed, message, reason };
47003
- }
47004
- }
47005
- }
47006
- return { retryDelayMs: null, message, reason };
47007
- }
47008
- function parseDurationToMs(duration) {
47009
- const simpleMatch = duration.match(/^(\d+(?:\.\d+)?)(ms|s|m|h)?$/i);
47010
- if (simpleMatch) {
47011
- const value = parseFloat(simpleMatch[1]);
47012
- const unit = (simpleMatch[2] || "s").toLowerCase();
47013
- switch (unit) {
47014
- case "h":
47015
- return value * 3600 * 1e3;
47016
- case "m":
47017
- return value * 60 * 1e3;
47018
- case "s":
47019
- return value * 1e3;
47020
- case "ms":
47021
- return value;
47022
- default:
47023
- return value * 1e3;
47024
- }
47025
47495
  }
47026
- const compoundRegex = /(\d+(?:\.\d+)?)(h|m(?!s)|s|ms)/gi;
47027
- let totalMs = 0;
47028
- let matchFound = false;
47029
- let match = null;
47030
- while (true) {
47031
- match = compoundRegex.exec(duration);
47032
- if (match === null) break;
47033
- matchFound = true;
47034
- const value = parseFloat(match[1]);
47035
- const unit = match[2]?.toLowerCase();
47036
- switch (unit) {
47037
- case "h":
47038
- totalMs += value * 3600 * 1e3;
47039
- break;
47040
- case "m":
47041
- totalMs += value * 60 * 1e3;
47042
- break;
47043
- case "s":
47044
- totalMs += value * 1e3;
47045
- break;
47046
- case "ms":
47047
- totalMs += value;
47048
- break;
47049
- }
47050
- }
47051
- 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
+ };
47052
47517
  }
47053
47518
 
47054
47519
  // src/plugin/shared/runtime.ts
@@ -47839,7 +48304,8 @@ function createVaultAccountMenuSections(pool, selectorOf, checkQuota) {
47839
48304
  return {
47840
48305
  accounts: {
47841
48306
  title: "Accounts",
47842
- build: () => {
48307
+ build: async () => {
48308
+ await pool.syncForDisplay();
47843
48309
  const rows = pool.selector.rows;
47844
48310
  return {
47845
48311
  lines: [
@@ -47855,7 +48321,8 @@ function createVaultAccountMenuSections(pool, selectorOf, checkQuota) {
47855
48321
  },
47856
48322
  quota: {
47857
48323
  title: "Quota",
47858
- build: () => {
48324
+ build: async () => {
48325
+ await pool.syncForDisplay();
47859
48326
  const rows = pool.selector.rows;
47860
48327
  return {
47861
48328
  lines: rows.length === 0 ? [] : rows.map(
@@ -48737,7 +49204,8 @@ async function createGaLocalRequestPipeline(input2) {
48737
49204
  async function createGaVaultRequestPipeline(input2) {
48738
49205
  const { pool } = input2;
48739
49206
  await input2.assertAdmission?.();
48740
- await pool.sync();
49207
+ await pool.syncCached();
49208
+ const shutdown = new AbortController();
48741
49209
  const logger3 = input2.runtime.logger.createLogger("request");
48742
49210
  const executor = createRequestExecutor({
48743
49211
  ...gaEngineCollaborators({
@@ -48747,7 +49215,10 @@ async function createGaVaultRequestPipeline(input2) {
48747
49215
  logger: logger3
48748
49216
  }),
48749
49217
  accounts: pool.selector,
48750
- ...input2.assertAdmission ? { assertAdmission: input2.assertAdmission } : {},
49218
+ assertAdmission: async (signal) => {
49219
+ await input2.assertAdmission?.();
49220
+ await pool.sync(signal);
49221
+ },
48751
49222
  credentials: pool.credentials,
48752
49223
  trackers: {
48753
49224
  health: pool.selector.healthTracker,
@@ -48755,17 +49226,22 @@ async function createGaVaultRequestPipeline(input2) {
48755
49226
  }
48756
49227
  });
48757
49228
  return {
48758
- execute: async (job, context) => {
48759
- await input2.assertAdmission?.();
48760
- await pool.sync();
48761
- 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
+ }
48762
49238
  },
48763
- rows: () => pool.selector.rows,
48764
49239
  refreshAccounts: async () => {
48765
49240
  await input2.assertAdmission?.();
48766
- await pool.refresh();
49241
+ await pool.refresh(shutdown.signal);
48767
49242
  },
48768
49243
  async dispose() {
49244
+ shutdown.abort(new Error("The Antigravity request executor is disposed"));
48769
49245
  await executor.dispose();
48770
49246
  await pool.flush();
48771
49247
  }
@@ -48790,7 +49266,7 @@ function createGaVaultStateSource(input2) {
48790
49266
  if (signal.aborted) throw abortError(signal);
48791
49267
  const stored = await input2.readState?.().catch(() => void 0);
48792
49268
  if (signal.aborted) throw abortError(signal);
48793
- const rows = input2.rows();
49269
+ const rows = await input2.rows(signal);
48794
49270
  const settings = input2.settings();
48795
49271
  const route = input2.route(scope);
48796
49272
  if (signal.aborted) throw abortError(signal);
@@ -48957,7 +49433,7 @@ async function createGaVaultLocationServices(input2) {
48957
49433
  return {
48958
49434
  execute: started.execute,
48959
49435
  state: createGaVaultStateSource({
48960
- rows: () => started.rows(),
49436
+ rows: (signal) => started.rows(signal),
48961
49437
  readState: () => custody.readState(),
48962
49438
  selectorOf,
48963
49439
  ...input2.nextReadSeq ? { nextReadSeq: input2.nextReadSeq } : {},
@@ -49392,8 +49868,7 @@ function createGaLocationServicesFactory(bindings) {
49392
49868
  });
49393
49869
  throw error;
49394
49870
  }
49395
- })().catch(async (error) => {
49396
- await custody.recycleStalledSource?.(VAULT_REFRESH_STALL_MS).catch(() => false);
49871
+ })().catch((error) => {
49397
49872
  vaultPromise = void 0;
49398
49873
  throw error;
49399
49874
  });
@@ -49409,6 +49884,7 @@ function createGaLocationServicesFactory(bindings) {
49409
49884
  return recovery;
49410
49885
  }
49411
49886
  try {
49887
+ await custody?.recycleStalledSource?.(VAULT_REFRESH_STALL_MS).catch(() => false);
49412
49888
  return await vault();
49413
49889
  } catch (error) {
49414
49890
  if (purpose === "execute") throw error;
@@ -49556,7 +50032,8 @@ function createGaLocationServicesForHost(vault) {
49556
50032
  readHostSlot,
49557
50033
  ...vault.connectionFile ? { connectionFile: vault.connectionFile } : {},
49558
50034
  // The engine reads each send's HTTP status itself.
49559
- reporterSource: "direct"
50035
+ reporterSource: "direct",
50036
+ insulaQuota: true
49560
50037
  }),
49561
50038
  ...vault.quota ? { quota: vault.quota } : {}
49562
50039
  });
@@ -51282,11 +51759,80 @@ function isGaGoogleContentRequest(request) {
51282
51759
  }
51283
51760
  }
51284
51761
  function gaPreHeaderFailureResponse(error) {
51285
- const rawMessage = error instanceof Error && error.message ? error.message : "Antigravity request failed before a response arrived";
51286
- const message = redactProjectIdText(rawMessage);
51762
+ const err = error;
51763
+ const rawStatusCode = typeof err?.statusCode === "number" && Number.isSafeInteger(err.statusCode) ? err.statusCode : void 0;
51764
+ const rawStatus = typeof err?.status === "number" && Number.isSafeInteger(err.status) ? err.status : void 0;
51765
+ const numericStatus = rawStatusCode ?? rawStatus;
51766
+ let status = 502;
51767
+ let statusString = "UNAVAILABLE";
51768
+ if (numericStatus !== void 0) {
51769
+ switch (numericStatus) {
51770
+ case 400:
51771
+ status = 400;
51772
+ statusString = "INVALID_ARGUMENT";
51773
+ break;
51774
+ case 401:
51775
+ status = 401;
51776
+ statusString = "UNAUTHENTICATED";
51777
+ break;
51778
+ case 403:
51779
+ status = 403;
51780
+ statusString = "PERMISSION_DENIED";
51781
+ break;
51782
+ case 404:
51783
+ status = 404;
51784
+ statusString = "NOT_FOUND";
51785
+ break;
51786
+ case 412:
51787
+ status = 412;
51788
+ statusString = "FAILED_PRECONDITION";
51789
+ break;
51790
+ case 429:
51791
+ status = 429;
51792
+ statusString = "RESOURCE_EXHAUSTED";
51793
+ break;
51794
+ case 502:
51795
+ case 503:
51796
+ case 504:
51797
+ status = numericStatus;
51798
+ statusString = "UNAVAILABLE";
51799
+ break;
51800
+ default:
51801
+ status = 502;
51802
+ statusString = "UNAVAILABLE";
51803
+ break;
51804
+ }
51805
+ }
51806
+ const rawMessage = error instanceof Error && error.message ? error.message : typeof err?.message === "string" && err.message ? err.message : "Antigravity request failed before a response arrived";
51807
+ const redacted = redactProjectIdText(rawMessage);
51808
+ const isQuota = isQuotaError(status, rawMessage, err?.details);
51809
+ const message = isQuota ? normalizeResetDuration(redacted) : redacted;
51810
+ const headers = new Headers({ "content-type": "application/json" });
51811
+ const metadata = resolveRetryMetadata({
51812
+ details: err?.details,
51813
+ message: rawMessage,
51814
+ status,
51815
+ headers: err?.headers ?? null,
51816
+ retryAfterMs: err?.retryAfterMs,
51817
+ resetAfterMs: err?.resetAfterMs,
51818
+ retryAfterSeconds: err?.retryAfterSeconds,
51819
+ // The bridge may pass on a truthful local wait of zero seconds.
51820
+ allowZero: true
51821
+ });
51822
+ if (metadata !== null) {
51823
+ const pair = deriveRetryHeaderPairFromMs(metadata.delayMs);
51824
+ headers.set("retry-after", pair["retry-after"]);
51825
+ headers.set("retry-after-ms", pair["retry-after-ms"]);
51826
+ }
51287
51827
  return new Response(
51288
- JSON.stringify({ error: { code: 502, message, status: "UNAVAILABLE" } }),
51289
- { status: 502, headers: { "content-type": "application/json" } }
51828
+ JSON.stringify({
51829
+ error: {
51830
+ code: status,
51831
+ message,
51832
+ status: statusString
51833
+ }
51834
+ }),
51835
+ { status, headers }
51290
51836
  );
51291
51837
  }
51292
51838
  async function startGaLoopbackBridge(options) {
@@ -51551,10 +52097,11 @@ async function startGaLoopbackBridge(options) {
51551
52097
  function isGaJobId(value) {
51552
52098
  return JOB_ID_PATTERN.test(value);
51553
52099
  }
51554
- function writeResponseHead(response, status, contentType) {
52100
+ function writeResponseHead(response, status, contentType, extraHeaders) {
51555
52101
  response.writeHead(status, {
51556
52102
  "content-type": contentType,
51557
- "cache-control": "no-cache"
52103
+ "cache-control": "no-cache",
52104
+ ...extraHeaders
51558
52105
  });
51559
52106
  }
51560
52107
  async function pipeResponse(upstream, response, onFailure, onHandoff) {
@@ -51564,7 +52111,8 @@ async function pipeResponse(upstream, response, onFailure, onHandoff) {
51564
52111
  });
51565
52112
  return;
51566
52113
  }
51567
- writeResponseHead(response, upstream.status, contentType);
52114
+ const extraHeaders = collectForwardedHeaders(upstream.headers);
52115
+ writeResponseHead(response, upstream.status, contentType, extraHeaders);
51568
52116
  response.flushHeaders();
51569
52117
  onHandoff();
51570
52118
  if (!upstream.body) {
@@ -61384,7 +61932,10 @@ function createVaultFetchInterceptor(context) {
61384
61932
  const pool = context.pool ?? createVaultAccountPool({ source });
61385
61933
  const selector = pool.selector;
61386
61934
  const executor = createRequestExecutor({
61387
- assertAdmission: context.assertAdmission,
61935
+ assertAdmission: async (signal) => {
61936
+ await context.assertAdmission?.();
61937
+ await pool.sync(signal);
61938
+ },
61388
61939
  ...openCode1EngineCollaborators({
61389
61940
  ...context,
61390
61941
  transport: agyTransport
@@ -61401,7 +61952,6 @@ function createVaultFetchInterceptor(context) {
61401
61952
  async function fetch(input2, init) {
61402
61953
  if (!isGenerativeLanguageRequest(input2)) return upstreamFetch(input2, init);
61403
61954
  if (disposed) throw new Error("The vault request runtime is disposed");
61404
- await pool.sync();
61405
61955
  return executor.execute(input2, init);
61406
61956
  }
61407
61957
  function dispose() {
@@ -62063,7 +62613,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
62063
62613
  },
62064
62614
  vault: async () => {
62065
62615
  const { pool } = await currentVaultPool();
62066
- await pool.sync();
62616
+ await pool.syncCached();
62067
62617
  const projection = buildVaultSidebarProjection(
62068
62618
  pool,
62069
62619
  await vaultCustody.readState(),
@@ -62265,7 +62815,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
62265
62815
  let current;
62266
62816
  try {
62267
62817
  current = await currentVaultPool();
62268
- await current.pool.sync();
62818
+ await current.pool.syncForDisplay();
62269
62819
  } catch {
62270
62820
  return showUnavailableVaultMenu();
62271
62821
  }