@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/server.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();
@@ -47340,6 +47455,10 @@ function sanitizeRequestPayloadForAntigravity(payload) {
47340
47455
  };
47341
47456
  });
47342
47457
  }
47458
+ if ("systemInstruction" in anyPayload)
47459
+ anyPayload.systemInstruction = rewriteSystemInstruction(
47460
+ anyPayload.systemInstruction
47461
+ );
47343
47462
  const systemInstruction = anyPayload.systemInstruction;
47344
47463
  if (systemInstruction && typeof systemInstruction === "object" && !Array.isArray(systemInstruction)) {
47345
47464
  const sys = systemInstruction;
@@ -50558,11 +50677,23 @@ function createRequestExecutor(deps) {
50558
50677
  };
50559
50678
  }
50560
50679
  const sender = options.transport ?? defaultTransport2;
50561
- const transport = (url, sendInit, sendOptions) => deadline.open(() => {
50680
+ const transport = (url, sendInit, sendOptions, onSenderRejection) => deadline.open(() => {
50562
50681
  waits.resumed();
50563
- return sender(url, sendInit, {
50682
+ const optionsWithSignal = {
50564
50683
  ...sendOptions,
50565
50684
  signal: deadline.signal
50685
+ };
50686
+ if (!onSenderRejection) return sender(url, sendInit, optionsWithSignal);
50687
+ let pending;
50688
+ try {
50689
+ pending = sender(url, sendInit, optionsWithSignal);
50690
+ } catch (error) {
50691
+ onSenderRejection(error);
50692
+ throw error;
50693
+ }
50694
+ return pending.catch((error) => {
50695
+ onSenderRejection(error);
50696
+ throw error;
50566
50697
  });
50567
50698
  });
50568
50699
  const requestSessionIdentity = options.session ?? extractOpenCodeSessionIdentity(init?.headers);
@@ -50611,8 +50742,38 @@ function createRequestExecutor(deps) {
50611
50742
  `[Cache] ${label} model=${cachedStats.model} read=${cachedStats.read} total=${cachedStats.total} hitRate=${cachedStats.hitRate}%`
50612
50743
  );
50613
50744
  }
50614
- let lastFailure = null;
50745
+ let retainedMainAttemptFailure = null;
50615
50746
  let lastError = null;
50747
+ const retainMainTransportFailure = (error) => {
50748
+ retainedMainAttemptFailure = {
50749
+ kind: "transport",
50750
+ error: error instanceof Error ? error : new Error(String(error))
50751
+ };
50752
+ };
50753
+ const terminalMainAttemptFailure = async (fallbackMessage) => {
50754
+ const failure2 = retainedMainAttemptFailure;
50755
+ if (failure2?.kind === "http") {
50756
+ const context = failure2.context;
50757
+ return wire.transformResponse(
50758
+ context.response,
50759
+ context.streaming,
50760
+ context.debugContext,
50761
+ context.requestedModel,
50762
+ context.projectId,
50763
+ context.endpoint,
50764
+ context.effectiveModel,
50765
+ context.sessionId,
50766
+ context.toolDebugMissing,
50767
+ context.toolDebugSummary,
50768
+ debugLines,
50769
+ context.dumpContext
50770
+ );
50771
+ }
50772
+ throw terminalFetchError(
50773
+ lastError ?? (failure2?.kind === "transport" ? failure2.error : null),
50774
+ fallbackMessage
50775
+ );
50776
+ };
50616
50777
  const abortSignal = init?.signal ?? void 0;
50617
50778
  const routingSleep = (ms, reason, attempt) => waits.sleep(
50618
50779
  ms,
@@ -50658,6 +50819,7 @@ function createRequestExecutor(deps) {
50658
50819
  }
50659
50820
  };
50660
50821
  let accountSwitchCount = 0;
50822
+ let unconfirmedRetries = 0;
50661
50823
  const maxAccountSwitches = config.max_account_switches ?? 2;
50662
50824
  let previousAccountIndex = -1;
50663
50825
  let needsCacheWarmup = false;
@@ -51228,7 +51390,7 @@ function createRequestExecutor(deps) {
51228
51390
  }
51229
51391
  }
51230
51392
  const selected = account;
51231
- const sendPhysical = async (url, sendInit, admission, sendModel, requestKind) => {
51393
+ const sendPhysical = async (url, sendInit, admission, sendModel, requestKind, onMainTransportFailure) => {
51232
51394
  const source = credentials.domain === "local" ? "local" : hasVaultHost2() ? "hosted" : "vault";
51233
51395
  const message = `request-send source=${source} model=${sendModel} account=Account ${account.index + 1}`;
51234
51396
  if (source === "local") log18.info(message);
@@ -51244,10 +51406,15 @@ function createRequestExecutor(deps) {
51244
51406
  abortSignal
51245
51407
  ) : void 0;
51246
51408
  try {
51247
- const response = await transport(url, sendInit, {
51248
- signal: abortSignal,
51249
- onDebug: pushDebug
51250
- });
51409
+ const response = await transport(
51410
+ url,
51411
+ sendInit,
51412
+ {
51413
+ signal: abortSignal,
51414
+ onDebug: pushDebug
51415
+ },
51416
+ onMainTransportFailure
51417
+ );
51251
51418
  return billing?.observe(response) ?? response;
51252
51419
  } catch (error) {
51253
51420
  billing?.end(false);
@@ -51405,6 +51572,7 @@ function createRequestExecutor(deps) {
51405
51572
  let apiRequestCount = 0;
51406
51573
  let shouldSwitchAccount = false;
51407
51574
  let skippedForModelUnavailable = false;
51575
+ let switchedForUnconfirmed = false;
51408
51576
  if (account.fingerprint) {
51409
51577
  pushDebug(
51410
51578
  `fingerprint: deviceId=${account.fingerprint.deviceId.slice(0, 8)}...`
@@ -51508,6 +51676,12 @@ function createRequestExecutor(deps) {
51508
51676
  toolDebugSummary: prepared.toolDebugSummary,
51509
51677
  dumpContext
51510
51678
  });
51679
+ const retainHttpFailure = (failureResponse) => {
51680
+ retainedMainAttemptFailure = {
51681
+ kind: "http",
51682
+ context: createFailureContext(failureResponse)
51683
+ };
51684
+ };
51511
51685
  await runThinkingWarmup(prepared, sendProjectId);
51512
51686
  await runCacheWarmupProbe(prepared);
51513
51687
  if (config.request_jitter_max_ms > 0) {
@@ -51540,7 +51714,8 @@ function createRequestExecutor(deps) {
51540
51714
  prepared.init,
51541
51715
  sendAdmission,
51542
51716
  prepared.effectiveModel ?? model ?? "unknown",
51543
- kind ?? "primary"
51717
+ kind ?? "primary",
51718
+ retainMainTransportFailure
51544
51719
  );
51545
51720
  if (response.ok) deadline.acceptHeaders();
51546
51721
  apiRequestCount++;
@@ -51636,6 +51811,82 @@ function createRequestExecutor(deps) {
51636
51811
  reasonInfo.message,
51637
51812
  response.status
51638
51813
  );
51814
+ if (response.status === 429 && rateLimitReason === "UNKNOWN") {
51815
+ await logResponseBody2(debugContext, response, 429);
51816
+ const outgoing = JSON.parse(String(prepared.init.body));
51817
+ const recognised = systemInstructionHasHarnessIdentity(
51818
+ outgoing.request?.systemInstruction
51819
+ );
51820
+ const terminal = () => new Response(
51821
+ JSON.stringify({
51822
+ error: {
51823
+ code: 412,
51824
+ status: "FAILED_PRECONDITION",
51825
+ message: UNCONFIRMED_RATE_LIMIT_MESSAGE
51826
+ }
51827
+ }),
51828
+ {
51829
+ status: 412,
51830
+ headers: { "Content-Type": "application/json" }
51831
+ }
51832
+ );
51833
+ void response.body?.cancel().catch(() => {
51834
+ });
51835
+ if (recognised) return terminal();
51836
+ const delayMs = unconfirmedRateLimitDelayMs(
51837
+ response.headers.get("retry-after")
51838
+ );
51839
+ accountManager.markRateLimitedWithReason(
51840
+ account,
51841
+ family,
51842
+ model,
51843
+ "UNKNOWN",
51844
+ delayMs
51845
+ );
51846
+ const now = Date.now();
51847
+ const at = account.cachedQuotaUpdatedAt;
51848
+ const sameQuotaIdentity = credentials.domain === "vault" || account.cachedQuotaAccountId === quotaAccountIdentity(
51849
+ parseRefreshParts(
51850
+ credentials.toAuthDetails(account).refresh
51851
+ ).refreshToken
51852
+ );
51853
+ const emptyUntil = sameQuotaIdentity && at !== void 0 && now - at <= softQuotaCacheTtlMs ? quotaExhaustedUntil(account, family, model, now) : 0;
51854
+ const quotaKey3 = getQuotaKey(family, model);
51855
+ const resets = account.rateLimitResetTimes;
51856
+ if (emptyUntil > (resets[quotaKey3] ?? 0))
51857
+ accountManager.markRateLimited(
51858
+ account,
51859
+ emptyUntil - now,
51860
+ family,
51861
+ model
51862
+ );
51863
+ accountManager.requestSaveToDisk();
51864
+ if ((resets[quotaKey3] ?? 0) > now + delayMs) {
51865
+ switchedForUnconfirmed = true;
51866
+ shouldSwitchAccount = true;
51867
+ break;
51868
+ }
51869
+ if (unconfirmedRetries >= MAX_UNCONFIRMED_RATE_LIMIT_RETRIES)
51870
+ return terminal();
51871
+ unconfirmedRetries++;
51872
+ const ready = accountManager.getAccounts().some((entry) => {
51873
+ const resets2 = entry.rateLimitResetTimes;
51874
+ 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();
51875
+ });
51876
+ if (ready) {
51877
+ switchedForUnconfirmed = true;
51878
+ shouldSwitchAccount = true;
51879
+ break;
51880
+ }
51881
+ await routingSleep(delayMs, "rate_limited", unconfirmedRetries);
51882
+ if ((resets[quotaKey3] ?? 0) > now + delayMs) {
51883
+ switchedForUnconfirmed = true;
51884
+ shouldSwitchAccount = true;
51885
+ break;
51886
+ }
51887
+ i -= 1;
51888
+ continue;
51889
+ }
51639
51890
  if (credentials.domain === "vault" && sendAdmission && sessionKey && hasVaultRoutingAccessor()) {
51640
51891
  const group = resolveQuotaGroup(
51641
51892
  family,
@@ -51662,7 +51913,7 @@ function createRequestExecutor(deps) {
51662
51913
  pushDebug(
51663
51914
  `Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted, switching account`
51664
51915
  );
51665
- lastFailure = createFailureContext(response);
51916
+ retainHttpFailure(response);
51666
51917
  shouldSwitchAccount = true;
51667
51918
  break;
51668
51919
  }
@@ -51812,7 +52063,7 @@ function createRequestExecutor(deps) {
51812
52063
  backoff.attempt
51813
52064
  );
51814
52065
  }
51815
- lastFailure = createFailureContext(response);
52066
+ retainHttpFailure(response);
51816
52067
  shouldSwitchAccount = true;
51817
52068
  break;
51818
52069
  }
@@ -51874,7 +52125,7 @@ function createRequestExecutor(deps) {
51874
52125
  `account-ineligible: disabled account ${account.index}`
51875
52126
  );
51876
52127
  trackers.health.recordFailure(account.index);
51877
- lastFailure = createFailureContext(response);
52128
+ retainHttpFailure(response);
51878
52129
  shouldSwitchAccount = true;
51879
52130
  break;
51880
52131
  }
@@ -51909,7 +52160,7 @@ function createRequestExecutor(deps) {
51909
52160
  `verification-required: disabled account ${account.index}`
51910
52161
  );
51911
52162
  trackers.health.recordFailure(account.index);
51912
- lastFailure = createFailureContext(response);
52163
+ retainHttpFailure(response);
51913
52164
  shouldSwitchAccount = true;
51914
52165
  break;
51915
52166
  }
@@ -51917,7 +52168,7 @@ function createRequestExecutor(deps) {
51917
52168
  const shouldRetryEndpoint = response.status === 404 || response.status >= 500;
51918
52169
  if (shouldRetryEndpoint && i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
51919
52170
  await logResponseBody2(debugContext, response, response.status);
51920
- lastFailure = createFailureContext(response);
52171
+ retainHttpFailure(response);
51921
52172
  continue;
51922
52173
  }
51923
52174
  if (response.ok) {
@@ -52182,73 +52433,22 @@ function createRequestExecutor(deps) {
52182
52433
  continue;
52183
52434
  }
52184
52435
  if (shouldSwitchAccount) {
52436
+ if (switchedForUnconfirmed) continue;
52185
52437
  accountSwitchCount++;
52186
52438
  if (accountSwitchCount > maxAccountSwitches) {
52187
52439
  pushDebug(
52188
52440
  `account-switch-cap: exceeded max_account_switches=${maxAccountSwitches}, giving up`
52189
52441
  );
52190
- if (lastFailure) {
52191
- return wire.transformResponse(
52192
- lastFailure.response,
52193
- lastFailure.streaming,
52194
- lastFailure.debugContext,
52195
- lastFailure.requestedModel,
52196
- lastFailure.projectId,
52197
- lastFailure.endpoint,
52198
- lastFailure.effectiveModel,
52199
- lastFailure.sessionId,
52200
- lastFailure.toolDebugMissing,
52201
- lastFailure.toolDebugSummary,
52202
- debugLines,
52203
- lastFailure.dumpContext
52204
- );
52205
- }
52206
- throw terminalFetchError(
52207
- lastError,
52442
+ return terminalMainAttemptFailure(
52208
52443
  `Exceeded max account switches (${maxAccountSwitches}). All accounts rate-limited.`
52209
52444
  );
52210
52445
  }
52211
52446
  if (accountCount <= 1) {
52212
- if (lastFailure) {
52213
- return wire.transformResponse(
52214
- lastFailure.response,
52215
- lastFailure.streaming,
52216
- lastFailure.debugContext,
52217
- lastFailure.requestedModel,
52218
- lastFailure.projectId,
52219
- lastFailure.endpoint,
52220
- lastFailure.effectiveModel,
52221
- lastFailure.sessionId,
52222
- lastFailure.toolDebugMissing,
52223
- lastFailure.toolDebugSummary,
52224
- debugLines,
52225
- lastFailure.dumpContext
52226
- );
52227
- }
52228
- throw terminalFetchError(
52229
- lastError,
52230
- "All Antigravity endpoints failed"
52231
- );
52447
+ return terminalMainAttemptFailure("All Antigravity endpoints failed");
52232
52448
  }
52233
52449
  continue;
52234
52450
  }
52235
- if (lastFailure) {
52236
- return wire.transformResponse(
52237
- lastFailure.response,
52238
- lastFailure.streaming,
52239
- lastFailure.debugContext,
52240
- lastFailure.requestedModel,
52241
- lastFailure.projectId,
52242
- lastFailure.endpoint,
52243
- lastFailure.effectiveModel,
52244
- lastFailure.sessionId,
52245
- lastFailure.toolDebugMissing,
52246
- lastFailure.toolDebugSummary,
52247
- debugLines,
52248
- lastFailure.dumpContext
52249
- );
52250
- }
52251
- throw terminalFetchError(lastError, "All Antigravity accounts failed");
52451
+ return terminalMainAttemptFailure("All Antigravity accounts failed");
52252
52452
  }
52253
52453
  }
52254
52454
  function drain() {