@cortexkit/opencode-antigravity-auth 3.1.1 → 3.1.4

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 (37) hide show
  1. package/dist/cli.js +21 -6
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +27 -14
  4. package/dist/index.js +276 -76
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +33 -20
  7. package/dist/server.js +276 -76
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/fs/canonical-file-path.js +6 -2
  11. package/dist/src/common-auth-embedded/source-output.json +22 -22
  12. package/dist/src/common-auth-embedded/store/index.d.ts +1 -1
  13. package/dist/src/common-auth-embedded/store/index.js +1 -1
  14. package/dist/src/common-auth-embedded/store/settings.d.ts +8 -0
  15. package/dist/src/common-auth-embedded/store/settings.js +14 -4
  16. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  17. package/dist/src/plugin/request.d.ts.map +1 -1
  18. package/dist/src/plugin/request.js +3 -1
  19. package/dist/src/plugin/request.js.map +1 -1
  20. package/dist/src/plugin/shared/request-services.d.ts +2 -0
  21. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  22. package/dist/src/plugin/shared/request-services.js +135 -24
  23. package/dist/src/plugin/shared/request-services.js.map +1 -1
  24. package/dist/tui-build-map.json +1 -1
  25. package/dist/tui-ga-build-map.json +1 -1
  26. package/dist/types/src/common-auth-embedded/store/index.d.ts +1 -1
  27. package/dist/types/src/common-auth-embedded/store/settings.d.ts +8 -0
  28. package/dist/types/src/plugin/request.d.ts.map +1 -1
  29. package/dist/types/src/plugin/shared/request-services.d.ts +2 -0
  30. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  31. package/package.json +2 -2
  32. package/src/common-auth-embedded/fs/canonical-file-path.js +6 -2
  33. package/src/common-auth-embedded/source-output.json +22 -22
  34. package/src/common-auth-embedded/store/index.d.ts +1 -1
  35. package/src/common-auth-embedded/store/index.js +1 -1
  36. package/src/common-auth-embedded/store/settings.d.ts +8 -0
  37. package/src/common-auth-embedded/store/settings.js +14 -4
package/dist/index.js CHANGED
@@ -4561,6 +4561,11 @@ var init_model_registry = __esm({
4561
4561
  });
4562
4562
 
4563
4563
  // ../core/dist/rotation.js
4564
+ function unconfirmedRateLimitDelayMs(retryAfter, now = Date.now()) {
4565
+ const value = retryAfter?.trim();
4566
+ const delay3 = value ? /^\d+(?:\.\d+)?$/.test(value) ? Number(value) * 1e3 : Date.parse(value) - now : Number.NaN;
4567
+ return Number.isFinite(delay3) ? Math.min(UNCONFIRMED_RATE_LIMIT_MAX_MS, Math.max(UNCONFIRMED_RATE_LIMIT_MIN_MS, delay3)) : UNCONFIRMED_RATE_LIMIT_MIN_MS;
4568
+ }
4564
4569
  function parseRateLimitReason(reason, message, status) {
4565
4570
  if (status === 529 || status === 503)
4566
4571
  return "MODEL_CAPACITY_EXHAUSTED";
@@ -4572,6 +4577,8 @@ function parseRateLimitReason(reason, message, status) {
4572
4577
  return normalized;
4573
4578
  }
4574
4579
  }
4580
+ if (status === 429)
4581
+ return "UNKNOWN";
4575
4582
  if (message) {
4576
4583
  const normalized = message.toLowerCase();
4577
4584
  if (normalized.includes("capacity") || normalized.includes("overloaded") || normalized.includes("resource exhausted")) {
@@ -4587,6 +4594,9 @@ function parseRateLimitReason(reason, message, status) {
4587
4594
  return "UNKNOWN";
4588
4595
  }
4589
4596
  function calculateBackoffMs(reason, consecutiveFailures, retryAfterMs, random = Math.random) {
4597
+ if (reason === "UNKNOWN") {
4598
+ return Math.min(UNCONFIRMED_RATE_LIMIT_MAX_MS, Math.max(UNCONFIRMED_RATE_LIMIT_MIN_MS, retryAfterMs ?? 0));
4599
+ }
4590
4600
  if (retryAfterMs && retryAfterMs > 0) {
4591
4601
  return Math.max(retryAfterMs, MIN_BACKOFF_MS);
4592
4602
  }
@@ -4676,7 +4686,7 @@ function initHealthTracker(config) {
4676
4686
  globalHealthTracker = new HealthScoreTracker(config);
4677
4687
  return globalHealthTracker;
4678
4688
  }
4679
- var QUOTA_EXHAUSTED_BACKOFFS, MAX_QUOTA_EXHAUSTED_BACKOFF_MS, RATE_LIMIT_EXCEEDED_BACKOFF, MODEL_CAPACITY_EXHAUSTED_BASE_BACKOFF, MODEL_CAPACITY_EXHAUSTED_JITTER_MAX, SERVER_ERROR_BACKOFF, UNKNOWN_BACKOFF, MIN_BACKOFF_MS, DEFAULT_HEALTH_SCORE_CONFIG, HealthScoreTracker, STICKINESS_BONUS, SWITCH_THRESHOLD, DEFAULT_TOKEN_BUCKET_CONFIG, TokenBucketTracker, globalTokenTracker, globalHealthTracker;
4689
+ var QUOTA_EXHAUSTED_BACKOFFS, MAX_QUOTA_EXHAUSTED_BACKOFF_MS, RATE_LIMIT_EXCEEDED_BACKOFF, MODEL_CAPACITY_EXHAUSTED_BASE_BACKOFF, MODEL_CAPACITY_EXHAUSTED_JITTER_MAX, SERVER_ERROR_BACKOFF, UNKNOWN_BACKOFF, MIN_BACKOFF_MS, UNCONFIRMED_RATE_LIMIT_MIN_MS, UNCONFIRMED_RATE_LIMIT_MAX_MS, MAX_UNCONFIRMED_RATE_LIMIT_RETRIES, UNCONFIRMED_RATE_LIMIT_MESSAGE, DEFAULT_HEALTH_SCORE_CONFIG, HealthScoreTracker, STICKINESS_BONUS, SWITCH_THRESHOLD, DEFAULT_TOKEN_BUCKET_CONFIG, TokenBucketTracker, globalTokenTracker, globalHealthTracker;
4680
4690
  var init_rotation = __esm({
4681
4691
  "../core/dist/rotation.js"() {
4682
4692
  "use strict";
@@ -4693,6 +4703,10 @@ var init_rotation = __esm({
4693
4703
  SERVER_ERROR_BACKOFF = 2e4;
4694
4704
  UNKNOWN_BACKOFF = 6e4;
4695
4705
  MIN_BACKOFF_MS = 2e3;
4706
+ UNCONFIRMED_RATE_LIMIT_MIN_MS = 5e3;
4707
+ UNCONFIRMED_RATE_LIMIT_MAX_MS = 3e4;
4708
+ MAX_UNCONFIRMED_RATE_LIMIT_RETRIES = 2;
4709
+ UNCONFIRMED_RATE_LIMIT_MESSAGE = "Antigravity could not confirm a temporary request limit. Try again later or change the agent system prompt.";
4696
4710
  DEFAULT_HEALTH_SCORE_CONFIG = {
4697
4711
  initial: 70,
4698
4712
  successReward: 1,
@@ -5678,6 +5692,14 @@ var init_account_selector = __esm({
5678
5692
  }
5679
5693
  markRateLimitedWithReason(account, family, model, reason, retryAfterMs, failureTtlMs = 36e5) {
5680
5694
  const now = this.now();
5695
+ if (reason === "UNKNOWN") {
5696
+ const backoffMs2 = calculateBackoffMs(reason, 0, retryAfterMs);
5697
+ const key2 = getQuotaKey(family, model);
5698
+ const resetAt = Math.max(account.rateLimitResetTimes[key2] ?? 0, now + backoffMs2);
5699
+ if (resetAt !== account.rateLimitResetTimes[key2])
5700
+ this.setRateLimit(account, key2, resetAt);
5701
+ return backoffMs2;
5702
+ }
5681
5703
  if (account.lastFailureTime !== void 0 && now - account.lastFailureTime > failureTtlMs) {
5682
5704
  account.consecutiveFailures = 0;
5683
5705
  }
@@ -18056,14 +18078,17 @@ function settingsRefusal(message) {
18056
18078
  message
18057
18079
  });
18058
18080
  }
18059
- async function readPoolSettings(rt) {
18060
- const read = async ([configPath = rt.ctx.configPath] = []) => {
18061
- const result2 = await readPoolConfig(configPath);
18081
+ function readPoolSettings(rt) {
18082
+ return readPoolSettingsAt(rt.ctx.configPath);
18083
+ }
18084
+ async function readPoolSettingsAt(configPath) {
18085
+ const read = async ([path5 = configPath] = []) => {
18086
+ const result2 = await readPoolConfig(path5);
18062
18087
  if (result2.status === "error")
18063
18088
  return { status: "error", file: "config", reason: result2.reason };
18064
18089
  return { status: result2.status, settings: settingsOf2(result2.config) };
18065
18090
  };
18066
- const result = windowsPrivateFiles ? await read() : await settingsCache.read([rt.ctx.configPath], read);
18091
+ const result = windowsPrivateFiles ? await read() : await settingsCache.read([configPath], read);
18067
18092
  return structuredClone(result);
18068
18093
  }
18069
18094
  async function updatePoolSettings(rt, mutator, options = {}) {
@@ -18276,6 +18301,7 @@ __export(store_exports, {
18276
18301
  countUnknownIdentityRows: () => countUnknownIdentityRows,
18277
18302
  fingerprintOf: () => fingerprintOf,
18278
18303
  openPoolStore: () => openPoolStore,
18304
+ readPoolSettingsAt: () => readPoolSettingsAt,
18279
18305
  rowLockKey: () => rowLockKey
18280
18306
  });
18281
18307
  var init_store = __esm({
@@ -18293,6 +18319,9 @@ var init_store = __esm({
18293
18319
 
18294
18320
  // ../core/dist/common-auth-embedded/fs/canonical-file-path.js
18295
18321
  import { basename as basename4, dirname as dirname9, join as join7, resolve as resolve7 } from "node:path";
18322
+ function symlinkLoop(file) {
18323
+ return Object.assign(new Error(`ELOOP: too many symbolic links encountered, realpath '${file}'`), { code: "ELOOP", syscall: "realpath", path: file });
18324
+ }
18296
18325
  async function canonicalFilePath(file, fs7) {
18297
18326
  let target = file;
18298
18327
  for (let hops = 0; ; hops++) {
@@ -18308,7 +18337,7 @@ async function canonicalFilePath(file, fs7) {
18308
18337
  if (!isSymlink)
18309
18338
  return target;
18310
18339
  if (hops >= maxSymlinkHops)
18311
- throw new Error("Too many file symlink hops");
18340
+ throw symlinkLoop(file);
18312
18341
  target = resolve7(dirname9(target), await fs7.readlink(target));
18313
18342
  }
18314
18343
  }
@@ -18327,7 +18356,7 @@ function canonicalFilePathSync(file, fs7) {
18327
18356
  if (!isSymlink)
18328
18357
  return target;
18329
18358
  if (hops >= maxSymlinkHops)
18330
- throw new Error("Too many file symlink hops");
18359
+ throw symlinkLoop(file);
18331
18360
  target = resolve7(dirname9(target), fs7.readlinkSync(target));
18332
18361
  }
18333
18362
  }
@@ -27556,6 +27585,91 @@ var init_credential_redaction = __esm({
27556
27585
  }
27557
27586
  });
27558
27587
 
27588
+ // ../core/dist/harness-identity.js
27589
+ function rewriteHarnessIdentity(text2) {
27590
+ const paragraphs = HARNESS_IDENTITY_PARAGRAPHS.some((marker) => text2.includes(marker)) ? text2.split(/\n\n+/).filter((paragraph) => !HARNESS_IDENTITY_PARAGRAPHS.some((marker) => paragraph.includes(marker))).join("\n\n") : text2;
27591
+ return HARNESS_IDENTITY_REWRITES.reduce((result, { pattern, replacement }) => result.replace(pattern, replacement), paragraphs);
27592
+ }
27593
+ function hasHarnessIdentity(text2) {
27594
+ return HARNESS_IDENTITY_PARAGRAPHS.some((marker) => text2.includes(marker)) || HARNESS_IDENTITY_REWRITES.some(({ pattern, replacement }) => text2.replace(pattern, replacement) !== text2);
27595
+ }
27596
+ function rewriteSystemInstruction(instruction) {
27597
+ if (typeof instruction === "string")
27598
+ return rewriteHarnessIdentity(instruction);
27599
+ if (!instruction || typeof instruction !== "object" || Array.isArray(instruction))
27600
+ return instruction;
27601
+ const record5 = instruction;
27602
+ if (!Array.isArray(record5.parts))
27603
+ return instruction;
27604
+ return {
27605
+ ...record5,
27606
+ parts: record5.parts.map((part) => {
27607
+ if (!part || typeof part !== "object" || Array.isArray(part))
27608
+ return part;
27609
+ const value = part;
27610
+ return typeof value.text === "string" ? { ...value, text: rewriteHarnessIdentity(value.text) } : part;
27611
+ })
27612
+ };
27613
+ }
27614
+ function systemInstructionHasHarnessIdentity(instruction) {
27615
+ if (typeof instruction === "string")
27616
+ return hasHarnessIdentity(instruction);
27617
+ if (!instruction || typeof instruction !== "object" || Array.isArray(instruction))
27618
+ return false;
27619
+ const parts = instruction.parts;
27620
+ return Array.isArray(parts) && parts.some((part) => {
27621
+ if (!part || typeof part !== "object" || Array.isArray(part))
27622
+ return false;
27623
+ const text2 = part.text;
27624
+ return typeof text2 === "string" && hasHarnessIdentity(text2);
27625
+ });
27626
+ }
27627
+ var HARNESS_IDENTITY_PARAGRAPHS, HARNESS_IDENTITY_REWRITES;
27628
+ var init_harness_identity = __esm({
27629
+ "../core/dist/harness-identity.js"() {
27630
+ "use strict";
27631
+ HARNESS_IDENTITY_PARAGRAPHS = [
27632
+ "github.com/anomalyco/opencode",
27633
+ "github.com/sst/opencode",
27634
+ "opencode.ai/docs"
27635
+ ];
27636
+ HARNESS_IDENTITY_REWRITES = [
27637
+ {
27638
+ pattern: /\btools\.opencode\b/g,
27639
+ replacement: "tools['opencode']"
27640
+ },
27641
+ {
27642
+ pattern: /You are opencode, /gi,
27643
+ replacement: "You are "
27644
+ },
27645
+ {
27646
+ pattern: /You are opencode(?!\.\w)(?=[.!;:]|$|\n)/gi,
27647
+ replacement: "You are a coding assistant"
27648
+ },
27649
+ {
27650
+ pattern: /if OpenCode honestly/g,
27651
+ replacement: "if the assistant honestly"
27652
+ },
27653
+ {
27654
+ pattern: /running inside Pi-Bolt, a build of pi \(a coding agent harness\) compiled ahead of time/gi,
27655
+ replacement: "running inside your development environment"
27656
+ },
27657
+ {
27658
+ pattern: /running inside pi, a coding agent harness/gi,
27659
+ replacement: "running inside your development environment"
27660
+ },
27661
+ {
27662
+ pattern: /running (?:inside|in) opencode, a coding agent harness/gi,
27663
+ replacement: "running inside your development environment"
27664
+ },
27665
+ {
27666
+ pattern: /\brunning (?:inside|in) (?:pi-bolt|pi|opencode)(?!\.\w)(?=$|\s|[.,;:!?])/gi,
27667
+ replacement: "running inside your development environment"
27668
+ }
27669
+ ];
27670
+ }
27671
+ });
27672
+
27559
27673
  // ../core/dist/model-types.js
27560
27674
  var init_model_types = __esm({
27561
27675
  "../core/dist/model-types.js"() {
@@ -30553,6 +30667,7 @@ var init_dist = __esm({
30553
30667
  init_fetch_timeout();
30554
30668
  init_file_lock();
30555
30669
  init_fingerprint();
30670
+ init_harness_identity();
30556
30671
  init_logger();
30557
30672
  init_model_registry();
30558
30673
  init_model_types();
@@ -55858,6 +55973,10 @@ function sanitizeRequestPayloadForAntigravity(payload) {
55858
55973
  };
55859
55974
  });
55860
55975
  }
55976
+ if ("systemInstruction" in anyPayload)
55977
+ anyPayload.systemInstruction = rewriteSystemInstruction(
55978
+ anyPayload.systemInstruction
55979
+ );
55861
55980
  const systemInstruction = anyPayload.systemInstruction;
55862
55981
  if (systemInstruction && typeof systemInstruction === "object" && !Array.isArray(systemInstruction)) {
55863
55982
  const sys = systemInstruction;
@@ -60700,11 +60819,23 @@ function createRequestExecutor(deps) {
60700
60819
  };
60701
60820
  }
60702
60821
  const sender = options.transport ?? defaultTransport2;
60703
- const transport = (url, sendInit, sendOptions) => deadline.open(() => {
60822
+ const transport = (url, sendInit, sendOptions, onSenderRejection) => deadline.open(() => {
60704
60823
  waits.resumed();
60705
- return sender(url, sendInit, {
60824
+ const optionsWithSignal = {
60706
60825
  ...sendOptions,
60707
60826
  signal: deadline.signal
60827
+ };
60828
+ if (!onSenderRejection) return sender(url, sendInit, optionsWithSignal);
60829
+ let pending;
60830
+ try {
60831
+ pending = sender(url, sendInit, optionsWithSignal);
60832
+ } catch (error) {
60833
+ onSenderRejection(error);
60834
+ throw error;
60835
+ }
60836
+ return pending.catch((error) => {
60837
+ onSenderRejection(error);
60838
+ throw error;
60708
60839
  });
60709
60840
  });
60710
60841
  const requestSessionIdentity = options.session ?? extractOpenCodeSessionIdentity(init?.headers);
@@ -60753,8 +60884,38 @@ function createRequestExecutor(deps) {
60753
60884
  `[Cache] ${label} model=${cachedStats.model} read=${cachedStats.read} total=${cachedStats.total} hitRate=${cachedStats.hitRate}%`
60754
60885
  );
60755
60886
  }
60756
- let lastFailure = null;
60887
+ let retainedMainAttemptFailure = null;
60757
60888
  let lastError = null;
60889
+ const retainMainTransportFailure = (error) => {
60890
+ retainedMainAttemptFailure = {
60891
+ kind: "transport",
60892
+ error: error instanceof Error ? error : new Error(String(error))
60893
+ };
60894
+ };
60895
+ const terminalMainAttemptFailure = async (fallbackMessage) => {
60896
+ const failure2 = retainedMainAttemptFailure;
60897
+ if (failure2?.kind === "http") {
60898
+ const context = failure2.context;
60899
+ return wire.transformResponse(
60900
+ context.response,
60901
+ context.streaming,
60902
+ context.debugContext,
60903
+ context.requestedModel,
60904
+ context.projectId,
60905
+ context.endpoint,
60906
+ context.effectiveModel,
60907
+ context.sessionId,
60908
+ context.toolDebugMissing,
60909
+ context.toolDebugSummary,
60910
+ debugLines,
60911
+ context.dumpContext
60912
+ );
60913
+ }
60914
+ throw terminalFetchError(
60915
+ lastError ?? (failure2?.kind === "transport" ? failure2.error : null),
60916
+ fallbackMessage
60917
+ );
60918
+ };
60758
60919
  const abortSignal = init?.signal ?? void 0;
60759
60920
  const routingSleep = (ms, reason, attempt) => waits.sleep(
60760
60921
  ms,
@@ -60800,6 +60961,7 @@ function createRequestExecutor(deps) {
60800
60961
  }
60801
60962
  };
60802
60963
  let accountSwitchCount = 0;
60964
+ let unconfirmedRetries = 0;
60803
60965
  const maxAccountSwitches = config.max_account_switches ?? 2;
60804
60966
  let previousAccountIndex = -1;
60805
60967
  let needsCacheWarmup = false;
@@ -61370,7 +61532,7 @@ function createRequestExecutor(deps) {
61370
61532
  }
61371
61533
  }
61372
61534
  const selected = account;
61373
- const sendPhysical = async (url, sendInit, admission, sendModel, requestKind) => {
61535
+ const sendPhysical = async (url, sendInit, admission, sendModel, requestKind, onMainTransportFailure) => {
61374
61536
  const source = credentials.domain === "local" ? "local" : hasVaultHost2() ? "hosted" : "vault";
61375
61537
  const message = `request-send source=${source} model=${sendModel} account=Account ${account.index + 1}`;
61376
61538
  if (source === "local") log18.info(message);
@@ -61386,10 +61548,15 @@ function createRequestExecutor(deps) {
61386
61548
  abortSignal
61387
61549
  ) : void 0;
61388
61550
  try {
61389
- const response = await transport(url, sendInit, {
61390
- signal: abortSignal,
61391
- onDebug: pushDebug
61392
- });
61551
+ const response = await transport(
61552
+ url,
61553
+ sendInit,
61554
+ {
61555
+ signal: abortSignal,
61556
+ onDebug: pushDebug
61557
+ },
61558
+ onMainTransportFailure
61559
+ );
61393
61560
  return billing?.observe(response) ?? response;
61394
61561
  } catch (error) {
61395
61562
  billing?.end(false);
@@ -61547,6 +61714,7 @@ function createRequestExecutor(deps) {
61547
61714
  let apiRequestCount = 0;
61548
61715
  let shouldSwitchAccount = false;
61549
61716
  let skippedForModelUnavailable = false;
61717
+ let switchedForUnconfirmed = false;
61550
61718
  if (account.fingerprint) {
61551
61719
  pushDebug(
61552
61720
  `fingerprint: deviceId=${account.fingerprint.deviceId.slice(0, 8)}...`
@@ -61650,6 +61818,12 @@ function createRequestExecutor(deps) {
61650
61818
  toolDebugSummary: prepared.toolDebugSummary,
61651
61819
  dumpContext
61652
61820
  });
61821
+ const retainHttpFailure = (failureResponse) => {
61822
+ retainedMainAttemptFailure = {
61823
+ kind: "http",
61824
+ context: createFailureContext(failureResponse)
61825
+ };
61826
+ };
61653
61827
  await runThinkingWarmup(prepared, sendProjectId);
61654
61828
  await runCacheWarmupProbe(prepared);
61655
61829
  if (config.request_jitter_max_ms > 0) {
@@ -61682,7 +61856,8 @@ function createRequestExecutor(deps) {
61682
61856
  prepared.init,
61683
61857
  sendAdmission,
61684
61858
  prepared.effectiveModel ?? model ?? "unknown",
61685
- kind ?? "primary"
61859
+ kind ?? "primary",
61860
+ retainMainTransportFailure
61686
61861
  );
61687
61862
  if (response.ok) deadline.acceptHeaders();
61688
61863
  apiRequestCount++;
@@ -61778,6 +61953,82 @@ function createRequestExecutor(deps) {
61778
61953
  reasonInfo.message,
61779
61954
  response.status
61780
61955
  );
61956
+ if (response.status === 429 && rateLimitReason === "UNKNOWN") {
61957
+ await logResponseBody2(debugContext, response, 429);
61958
+ const outgoing = JSON.parse(String(prepared.init.body));
61959
+ const recognised = systemInstructionHasHarnessIdentity(
61960
+ outgoing.request?.systemInstruction
61961
+ );
61962
+ const terminal = () => new Response(
61963
+ JSON.stringify({
61964
+ error: {
61965
+ code: 412,
61966
+ status: "FAILED_PRECONDITION",
61967
+ message: UNCONFIRMED_RATE_LIMIT_MESSAGE
61968
+ }
61969
+ }),
61970
+ {
61971
+ status: 412,
61972
+ headers: { "Content-Type": "application/json" }
61973
+ }
61974
+ );
61975
+ void response.body?.cancel().catch(() => {
61976
+ });
61977
+ if (recognised) return terminal();
61978
+ const delayMs = unconfirmedRateLimitDelayMs(
61979
+ response.headers.get("retry-after")
61980
+ );
61981
+ accountManager.markRateLimitedWithReason(
61982
+ account,
61983
+ family,
61984
+ model,
61985
+ "UNKNOWN",
61986
+ delayMs
61987
+ );
61988
+ const now = Date.now();
61989
+ const at = account.cachedQuotaUpdatedAt;
61990
+ const sameQuotaIdentity = credentials.domain === "vault" || account.cachedQuotaAccountId === quotaAccountIdentity(
61991
+ parseRefreshParts(
61992
+ credentials.toAuthDetails(account).refresh
61993
+ ).refreshToken
61994
+ );
61995
+ const emptyUntil = sameQuotaIdentity && at !== void 0 && now - at <= softQuotaCacheTtlMs ? quotaExhaustedUntil(account, family, model, now) : 0;
61996
+ const quotaKey3 = getQuotaKey(family, model);
61997
+ const resets = account.rateLimitResetTimes;
61998
+ if (emptyUntil > (resets[quotaKey3] ?? 0))
61999
+ accountManager.markRateLimited(
62000
+ account,
62001
+ emptyUntil - now,
62002
+ family,
62003
+ model
62004
+ );
62005
+ accountManager.requestSaveToDisk();
62006
+ if ((resets[quotaKey3] ?? 0) > now + delayMs) {
62007
+ switchedForUnconfirmed = true;
62008
+ shouldSwitchAccount = true;
62009
+ break;
62010
+ }
62011
+ if (unconfirmedRetries >= MAX_UNCONFIRMED_RATE_LIMIT_RETRIES)
62012
+ return terminal();
62013
+ unconfirmedRetries++;
62014
+ const ready = accountManager.getAccounts().some((entry) => {
62015
+ const resets2 = entry.rateLimitResetTimes;
62016
+ return entry.index !== account.index && entry.enabled !== false && !entry.accountIneligible && !entry.verificationRequired && !allowlistExcluded?.has(entry.index) && !unavailableIndexes.has(entry.index) && (eligibleIndexes === null || eligibleIndexes.has(entry.index)) && (entry.coolingDownUntil ?? 0) <= Date.now() && (resets2[family] ?? 0) <= Date.now() && (resets2[getQuotaKey(family, model)] ?? 0) <= Date.now();
62017
+ });
62018
+ if (ready) {
62019
+ switchedForUnconfirmed = true;
62020
+ shouldSwitchAccount = true;
62021
+ break;
62022
+ }
62023
+ await routingSleep(delayMs, "rate_limited", unconfirmedRetries);
62024
+ if ((resets[quotaKey3] ?? 0) > now + delayMs) {
62025
+ switchedForUnconfirmed = true;
62026
+ shouldSwitchAccount = true;
62027
+ break;
62028
+ }
62029
+ i -= 1;
62030
+ continue;
62031
+ }
61781
62032
  if (credentials.domain === "vault" && sendAdmission && sessionKey && hasVaultRoutingAccessor()) {
61782
62033
  const group = resolveQuotaGroup(
61783
62034
  family,
@@ -61804,7 +62055,7 @@ function createRequestExecutor(deps) {
61804
62055
  pushDebug(
61805
62056
  `Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted, switching account`
61806
62057
  );
61807
- lastFailure = createFailureContext(response);
62058
+ retainHttpFailure(response);
61808
62059
  shouldSwitchAccount = true;
61809
62060
  break;
61810
62061
  }
@@ -61954,7 +62205,7 @@ function createRequestExecutor(deps) {
61954
62205
  backoff.attempt
61955
62206
  );
61956
62207
  }
61957
- lastFailure = createFailureContext(response);
62208
+ retainHttpFailure(response);
61958
62209
  shouldSwitchAccount = true;
61959
62210
  break;
61960
62211
  }
@@ -62016,7 +62267,7 @@ function createRequestExecutor(deps) {
62016
62267
  `account-ineligible: disabled account ${account.index}`
62017
62268
  );
62018
62269
  trackers.health.recordFailure(account.index);
62019
- lastFailure = createFailureContext(response);
62270
+ retainHttpFailure(response);
62020
62271
  shouldSwitchAccount = true;
62021
62272
  break;
62022
62273
  }
@@ -62051,7 +62302,7 @@ function createRequestExecutor(deps) {
62051
62302
  `verification-required: disabled account ${account.index}`
62052
62303
  );
62053
62304
  trackers.health.recordFailure(account.index);
62054
- lastFailure = createFailureContext(response);
62305
+ retainHttpFailure(response);
62055
62306
  shouldSwitchAccount = true;
62056
62307
  break;
62057
62308
  }
@@ -62059,7 +62310,7 @@ function createRequestExecutor(deps) {
62059
62310
  const shouldRetryEndpoint = response.status === 404 || response.status >= 500;
62060
62311
  if (shouldRetryEndpoint && i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
62061
62312
  await logResponseBody2(debugContext, response, response.status);
62062
- lastFailure = createFailureContext(response);
62313
+ retainHttpFailure(response);
62063
62314
  continue;
62064
62315
  }
62065
62316
  if (response.ok) {
@@ -62324,73 +62575,22 @@ function createRequestExecutor(deps) {
62324
62575
  continue;
62325
62576
  }
62326
62577
  if (shouldSwitchAccount) {
62578
+ if (switchedForUnconfirmed) continue;
62327
62579
  accountSwitchCount++;
62328
62580
  if (accountSwitchCount > maxAccountSwitches) {
62329
62581
  pushDebug(
62330
62582
  `account-switch-cap: exceeded max_account_switches=${maxAccountSwitches}, giving up`
62331
62583
  );
62332
- if (lastFailure) {
62333
- return wire.transformResponse(
62334
- lastFailure.response,
62335
- lastFailure.streaming,
62336
- lastFailure.debugContext,
62337
- lastFailure.requestedModel,
62338
- lastFailure.projectId,
62339
- lastFailure.endpoint,
62340
- lastFailure.effectiveModel,
62341
- lastFailure.sessionId,
62342
- lastFailure.toolDebugMissing,
62343
- lastFailure.toolDebugSummary,
62344
- debugLines,
62345
- lastFailure.dumpContext
62346
- );
62347
- }
62348
- throw terminalFetchError(
62349
- lastError,
62584
+ return terminalMainAttemptFailure(
62350
62585
  `Exceeded max account switches (${maxAccountSwitches}). All accounts rate-limited.`
62351
62586
  );
62352
62587
  }
62353
62588
  if (accountCount <= 1) {
62354
- if (lastFailure) {
62355
- return wire.transformResponse(
62356
- lastFailure.response,
62357
- lastFailure.streaming,
62358
- lastFailure.debugContext,
62359
- lastFailure.requestedModel,
62360
- lastFailure.projectId,
62361
- lastFailure.endpoint,
62362
- lastFailure.effectiveModel,
62363
- lastFailure.sessionId,
62364
- lastFailure.toolDebugMissing,
62365
- lastFailure.toolDebugSummary,
62366
- debugLines,
62367
- lastFailure.dumpContext
62368
- );
62369
- }
62370
- throw terminalFetchError(
62371
- lastError,
62372
- "All Antigravity endpoints failed"
62373
- );
62589
+ return terminalMainAttemptFailure("All Antigravity endpoints failed");
62374
62590
  }
62375
62591
  continue;
62376
62592
  }
62377
- if (lastFailure) {
62378
- return wire.transformResponse(
62379
- lastFailure.response,
62380
- lastFailure.streaming,
62381
- lastFailure.debugContext,
62382
- lastFailure.requestedModel,
62383
- lastFailure.projectId,
62384
- lastFailure.endpoint,
62385
- lastFailure.effectiveModel,
62386
- lastFailure.sessionId,
62387
- lastFailure.toolDebugMissing,
62388
- lastFailure.toolDebugSummary,
62389
- debugLines,
62390
- lastFailure.dumpContext
62391
- );
62392
- }
62393
- throw terminalFetchError(lastError, "All Antigravity accounts failed");
62593
+ return terminalMainAttemptFailure("All Antigravity accounts failed");
62394
62594
  }
62395
62595
  }
62396
62596
  function drain() {