@cortexkit/opencode-antigravity-auth 3.1.2 → 3.1.5

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 (64) hide show
  1. package/README.md +3 -2
  2. package/dist/cli.js +171 -80
  3. package/dist/cli.js.map +4 -4
  4. package/dist/cli.meta.json +100 -27
  5. package/dist/index.js +369 -176
  6. package/dist/index.js.map +4 -4
  7. package/dist/index.meta.json +109 -36
  8. package/dist/server.js +367 -174
  9. package/dist/server.js.map +4 -4
  10. package/dist/server.meta.json +1 -1
  11. package/dist/src/common-auth-embedded/auth-menu/login.js +4 -1
  12. package/dist/src/common-auth-embedded/fs/canonical-file-path.js +6 -2
  13. package/dist/src/common-auth-embedded/routing-accessor/cache-policy.d.ts +2 -2
  14. package/dist/src/common-auth-embedded/routing-accessor/cache-policy.js +1 -0
  15. package/dist/src/common-auth-embedded/setup/command.js +40 -19
  16. package/dist/src/common-auth-embedded/setup/enroll.d.ts +2 -1
  17. package/dist/src/common-auth-embedded/setup/enroll.js +12 -7
  18. package/dist/src/common-auth-embedded/setup/process-fence.d.ts +9 -0
  19. package/dist/src/common-auth-embedded/setup/process-fence.js +52 -8
  20. package/dist/src/common-auth-embedded/setup/process-guard.d.ts +12 -0
  21. package/dist/src/common-auth-embedded/setup/process-guard.js +32 -0
  22. package/dist/src/common-auth-embedded/setup/register.d.ts +2 -1
  23. package/dist/src/common-auth-embedded/setup/register.js +12 -2
  24. package/dist/src/common-auth-embedded/source-output.json +69 -53
  25. package/dist/src/common-auth-embedded/store/index.d.ts +1 -1
  26. package/dist/src/common-auth-embedded/store/index.js +1 -1
  27. package/dist/src/common-auth-embedded/store/settings.d.ts +8 -0
  28. package/dist/src/common-auth-embedded/store/settings.js +14 -4
  29. package/dist/src/plugin/__fixtures__/verified-store.d.ts +1 -1
  30. package/dist/src/plugin/__fixtures__/verified-store.js +4 -4
  31. package/dist/src/plugin/shared/request-services.d.ts +1 -0
  32. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  33. package/dist/src/plugin/shared/request-services.js +81 -24
  34. package/dist/src/plugin/shared/request-services.js.map +1 -1
  35. package/dist/tui-build-map.json +1 -1
  36. package/dist/tui-ga-build-map.json +1 -1
  37. package/dist/types/src/common-auth-embedded/routing-accessor/cache-policy.d.ts +2 -2
  38. package/dist/types/src/common-auth-embedded/setup/enroll.d.ts +2 -1
  39. package/dist/types/src/common-auth-embedded/setup/process-fence.d.ts +9 -0
  40. package/dist/types/src/common-auth-embedded/setup/process-guard.d.ts +12 -0
  41. package/dist/types/src/common-auth-embedded/setup/register.d.ts +2 -1
  42. package/dist/types/src/common-auth-embedded/store/index.d.ts +1 -1
  43. package/dist/types/src/common-auth-embedded/store/settings.d.ts +8 -0
  44. package/dist/types/src/plugin/shared/request-services.d.ts +1 -0
  45. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  46. package/package.json +2 -2
  47. package/src/common-auth-embedded/auth-menu/login.js +4 -1
  48. package/src/common-auth-embedded/fs/canonical-file-path.js +6 -2
  49. package/src/common-auth-embedded/routing-accessor/cache-policy.d.ts +2 -2
  50. package/src/common-auth-embedded/routing-accessor/cache-policy.js +1 -0
  51. package/src/common-auth-embedded/setup/command.js +40 -19
  52. package/src/common-auth-embedded/setup/enroll.d.ts +2 -1
  53. package/src/common-auth-embedded/setup/enroll.js +12 -7
  54. package/src/common-auth-embedded/setup/process-fence.d.ts +9 -0
  55. package/src/common-auth-embedded/setup/process-fence.js +52 -8
  56. package/src/common-auth-embedded/setup/process-guard.d.ts +12 -0
  57. package/src/common-auth-embedded/setup/process-guard.js +32 -0
  58. package/src/common-auth-embedded/setup/register.d.ts +2 -1
  59. package/src/common-auth-embedded/setup/register.js +12 -2
  60. package/src/common-auth-embedded/source-output.json +69 -53
  61. package/src/common-auth-embedded/store/index.d.ts +1 -1
  62. package/src/common-auth-embedded/store/index.js +1 -1
  63. package/src/common-auth-embedded/store/settings.d.ts +8 -0
  64. package/src/common-auth-embedded/store/settings.js +14 -4
package/dist/server.js CHANGED
@@ -761,12 +761,12 @@ async function replaceWindowsFile(from, to, options = {}) {
761
761
  const delays = [0, 10, 20, 40, 80, 100];
762
762
  let original;
763
763
  let attempts2 = 0;
764
- for (const delay3 of delays) {
764
+ for (const delay4 of delays) {
765
765
  const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
766
766
  if (now() >= deadline)
767
767
  break;
768
- if (delay3)
769
- await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
768
+ if (delay4)
769
+ await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay4, Math.max(0, deadline - now())));
770
770
  if (now() >= deadline)
771
771
  break;
772
772
  const fenceStart = now();
@@ -4563,8 +4563,8 @@ var init_model_registry = __esm({
4563
4563
  // ../core/dist/rotation.js
4564
4564
  function unconfirmedRateLimitDelayMs(retryAfter, now = Date.now()) {
4565
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;
4566
+ const delay4 = value ? /^\d+(?:\.\d+)?$/.test(value) ? Number(value) * 1e3 : Date.parse(value) - now : Number.NaN;
4567
+ return Number.isFinite(delay4) ? Math.min(UNCONFIRMED_RATE_LIMIT_MAX_MS, Math.max(UNCONFIRMED_RATE_LIMIT_MIN_MS, delay4)) : UNCONFIRMED_RATE_LIMIT_MIN_MS;
4568
4568
  }
4569
4569
  function parseRateLimitReason(reason, message, status) {
4570
4570
  if (status === 529 || status === 503)
@@ -4577,6 +4577,8 @@ function parseRateLimitReason(reason, message, status) {
4577
4577
  return normalized;
4578
4578
  }
4579
4579
  }
4580
+ if (status === 429)
4581
+ return "UNKNOWN";
4580
4582
  if (message) {
4581
4583
  const normalized = message.toLowerCase();
4582
4584
  if (normalized.includes("capacity") || normalized.includes("overloaded") || normalized.includes("resource exhausted")) {
@@ -5692,7 +5694,10 @@ var init_account_selector = __esm({
5692
5694
  const now = this.now();
5693
5695
  if (reason === "UNKNOWN") {
5694
5696
  const backoffMs2 = calculateBackoffMs(reason, 0, retryAfterMs);
5695
- this.setRateLimit(account, getQuotaKey(family, model), now + backoffMs2);
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);
5696
5701
  return backoffMs2;
5697
5702
  }
5698
5703
  if (account.lastFailureTime !== void 0 && now - account.lastFailureTime > failureTtlMs) {
@@ -8906,9 +8911,9 @@ async function acquireWithRetry(path5, sleep5) {
8906
8911
  return lock;
8907
8912
  }
8908
8913
  if (attempt < RETRY_DELAYS_MS.length) {
8909
- const delay3 = RETRY_DELAYS_MS[attempt];
8910
- if (delay3 !== void 0) {
8911
- await sleep5(delay3);
8914
+ const delay4 = RETRY_DELAYS_MS[attempt];
8915
+ if (delay4 !== void 0) {
8916
+ await sleep5(delay4);
8912
8917
  }
8913
8918
  }
8914
8919
  }
@@ -17620,11 +17625,11 @@ var init_quota_writer = __esm({
17620
17625
  overlay(rows) {
17621
17626
  return rows.map((row) => this.overlayRow(row));
17622
17627
  }
17623
- schedule(delay3) {
17628
+ schedule(delay4) {
17624
17629
  if (this.running || this.timer || !this.pending.size || this.stopped)
17625
17630
  return;
17626
17631
  const remaining = this.closed ? 0 : (this.committedAt ?? -Infinity) + QUOTA_COMMIT_INTERVAL_MS - this.clock.now();
17627
- this.timer = this.clock.schedule(Math.max(delay3, remaining), () => {
17632
+ this.timer = this.clock.schedule(Math.max(delay4, remaining), () => {
17628
17633
  this.timer = void 0;
17629
17634
  return this.flush();
17630
17635
  });
@@ -17724,8 +17729,8 @@ var init_quota_writer = __esm({
17724
17729
  this.running = void 0;
17725
17730
  for (const wake of this.wake)
17726
17731
  wake();
17727
- const delay3 = this.failures ? Math.min(5e3, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS;
17728
- this.schedule(delay3);
17732
+ const delay4 = this.failures ? Math.min(5e3, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS;
17733
+ this.schedule(delay4);
17729
17734
  }
17730
17735
  })();
17731
17736
  return this.running;
@@ -18073,14 +18078,17 @@ function settingsRefusal(message) {
18073
18078
  message
18074
18079
  });
18075
18080
  }
18076
- async function readPoolSettings(rt) {
18077
- const read = async ([configPath = rt.ctx.configPath] = []) => {
18078
- 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);
18079
18087
  if (result2.status === "error")
18080
18088
  return { status: "error", file: "config", reason: result2.reason };
18081
18089
  return { status: result2.status, settings: settingsOf2(result2.config) };
18082
18090
  };
18083
- const result = windowsPrivateFiles ? await read() : await settingsCache.read([rt.ctx.configPath], read);
18091
+ const result = windowsPrivateFiles ? await read() : await settingsCache.read([configPath], read);
18084
18092
  return structuredClone(result);
18085
18093
  }
18086
18094
  async function updatePoolSettings(rt, mutator, options = {}) {
@@ -18293,6 +18301,7 @@ __export(store_exports, {
18293
18301
  countUnknownIdentityRows: () => countUnknownIdentityRows,
18294
18302
  fingerprintOf: () => fingerprintOf,
18295
18303
  openPoolStore: () => openPoolStore,
18304
+ readPoolSettingsAt: () => readPoolSettingsAt,
18296
18305
  rowLockKey: () => rowLockKey
18297
18306
  });
18298
18307
  var init_store = __esm({
@@ -18310,6 +18319,9 @@ var init_store = __esm({
18310
18319
 
18311
18320
  // ../core/dist/common-auth-embedded/fs/canonical-file-path.js
18312
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
+ }
18313
18325
  async function canonicalFilePath(file, fs7) {
18314
18326
  let target = file;
18315
18327
  for (let hops = 0; ; hops++) {
@@ -18325,7 +18337,7 @@ async function canonicalFilePath(file, fs7) {
18325
18337
  if (!isSymlink)
18326
18338
  return target;
18327
18339
  if (hops >= maxSymlinkHops)
18328
- throw new Error("Too many file symlink hops");
18340
+ throw symlinkLoop(file);
18329
18341
  target = resolve7(dirname9(target), await fs7.readlink(target));
18330
18342
  }
18331
18343
  }
@@ -18344,7 +18356,7 @@ function canonicalFilePathSync(file, fs7) {
18344
18356
  if (!isSymlink)
18345
18357
  return target;
18346
18358
  if (hops >= maxSymlinkHops)
18347
- throw new Error("Too many file symlink hops");
18359
+ throw symlinkLoop(file);
18348
18360
  target = resolve7(dirname9(target), fs7.readlinkSync(target));
18349
18361
  }
18350
18362
  }
@@ -20458,11 +20470,12 @@ var init_doctor = __esm({
20458
20470
 
20459
20471
  // ../core/dist/common-auth-embedded/auth-menu/login.js
20460
20472
  import { spawn as defaultSpawn } from "node:child_process";
20473
+ import { win32 } from "node:path";
20461
20474
  function openBrowserForMenu(url, platform = process.platform, spawn2 = defaultSpawn) {
20462
20475
  try {
20463
20476
  if (platform === "win32") {
20464
20477
  const command = `Start-Process '${url.replaceAll("'", "''")}'`;
20465
- const child2 = spawn2("powershell.exe", [
20478
+ const child2 = spawn2(win32.resolve(process.env.SystemRoot ?? process.env.windir ?? "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe"), [
20466
20479
  "-NoProfile",
20467
20480
  "-NonInteractive",
20468
20481
  "-WindowStyle",
@@ -21405,12 +21418,12 @@ var init_watch = __esm({
21405
21418
  this.#options.logger?.debug("claustrum vault watch", { mode, reason });
21406
21419
  this.#options.onMode?.(mode);
21407
21420
  }
21408
- #later(delay3, run) {
21421
+ #later(delay4, run) {
21409
21422
  this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
21410
21423
  this.#timer = void 0;
21411
21424
  if (!this.#stopped)
21412
21425
  run();
21413
- }, delay3);
21426
+ }, delay4);
21414
21427
  this.#timer.unref?.();
21415
21428
  }
21416
21429
  async #open(resubscribed) {
@@ -21482,10 +21495,10 @@ var init_watch = __esm({
21482
21495
  const now = (this.#options.now ?? Date.now)();
21483
21496
  if (watch2.acceptedAt !== void 0 && now - watch2.acceptedAt >= SAFETY_POLL_MS)
21484
21497
  this.#closes = 0;
21485
- const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
21498
+ const delay4 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
21486
21499
  this.#closes++;
21487
21500
  this.#setMode("polling", "resubscribing");
21488
- this.#later(delay3, () => void this.#open(true));
21501
+ this.#later(delay4, () => void this.#open(true));
21489
21502
  return;
21490
21503
  }
21491
21504
  this.#fallback(end.kind);
@@ -21776,12 +21789,12 @@ var init_insula = __esm({
21776
21789
  watch2?.handle?.stop();
21777
21790
  this.#mode = "polling";
21778
21791
  }
21779
- #later(delay3) {
21792
+ #later(delay4) {
21780
21793
  this.#timer = (this.#timers.setTimeoutImpl ?? setTimeout)(() => {
21781
21794
  this.#timer = void 0;
21782
21795
  if (this.#watchers > 0 && !this.#watch)
21783
21796
  this.#open();
21784
- }, delay3);
21797
+ }, delay4);
21785
21798
  this.#timer.unref?.();
21786
21799
  }
21787
21800
  #open() {
@@ -21829,10 +21842,10 @@ var init_insula = __esm({
21829
21842
  return;
21830
21843
  }
21831
21844
  if (watch2.notices > 0) {
21832
- const delay3 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
21845
+ const delay4 = Math.min(RESUBSCRIBE_BACKOFF_MS * 2 ** Math.min(this.#closes, 16), WATCH_RETRY_MS);
21833
21846
  this.#closes++;
21834
21847
  this.#mode = "polling";
21835
- this.#later(delay3);
21848
+ this.#later(delay4);
21836
21849
  return;
21837
21850
  }
21838
21851
  this.#mode = "fallback";
@@ -23521,9 +23534,9 @@ var init_custody = __esm({
23521
23534
  users: 0,
23522
23535
  error,
23523
23536
  pending: Promise.resolve().then(async () => {
23524
- let delay3 = 250;
23537
+ let delay4 = 250;
23525
23538
  for (; ; ) {
23526
- await this.#receiptBackoff(delay3, controller.signal);
23539
+ await this.#receiptBackoff(delay4, controller.signal);
23527
23540
  try {
23528
23541
  return await this.#authorizeFresh(identity4, token, controller.signal);
23529
23542
  } catch (failure2) {
@@ -23531,7 +23544,7 @@ var init_custody = __esm({
23531
23544
  if (classifyVaultFailure(failure2) !== "unreachable")
23532
23545
  throw failure2;
23533
23546
  created.error = failure2;
23534
- delay3 = Math.min(delay3 * 2, 1e3);
23547
+ delay4 = Math.min(delay4 * 2, 1e3);
23535
23548
  }
23536
23549
  }
23537
23550
  })
@@ -23585,7 +23598,7 @@ var init_custody = __esm({
23585
23598
  }
23586
23599
  }
23587
23600
  }
23588
- #receiptBackoff(delay3, signal) {
23601
+ #receiptBackoff(delay4, signal) {
23589
23602
  this.#check(signal);
23590
23603
  return new Promise((resolve33, reject) => {
23591
23604
  const abort = () => {
@@ -23596,7 +23609,7 @@ var init_custody = __esm({
23596
23609
  const timer = this.#setTimeout(() => {
23597
23610
  signal.removeEventListener("abort", abort);
23598
23611
  resolve33();
23599
- }, delay3);
23612
+ }, delay4);
23600
23613
  timer.unref?.();
23601
23614
  signal.addEventListener("abort", abort, { once: true });
23602
23615
  if (signal.aborted)
@@ -24620,11 +24633,11 @@ function pendingVaultQuota(path5, roster) {
24620
24633
  function hasPendingVaultQuota(path5) {
24621
24634
  return !!writers.get(resolve11(path5))?.pending.size;
24622
24635
  }
24623
- function schedule(writer, delay3) {
24636
+ function schedule(writer, delay4) {
24624
24637
  if (writer.running || writer.timer || !writer.pending.size || writer.abort.signal.aborted)
24625
24638
  return;
24626
24639
  const remaining = writer.draining ? 0 : (writer.committedAt ?? -Infinity) + QUOTA_COMMIT_INTERVAL_MS - writer.clock.now();
24627
- writer.timer = writer.clock.schedule(Math.max(delay3, remaining), () => {
24640
+ writer.timer = writer.clock.schedule(Math.max(delay4, remaining), () => {
24628
24641
  writer.timer = void 0;
24629
24642
  return flush(writer);
24630
24643
  });
@@ -25061,13 +25074,13 @@ var init_consumer = __esm({
25061
25074
  }
25062
25075
  if (this.#shutdown.signal.aborted)
25063
25076
  return;
25064
- const delay3 = this.#options.pollIntervalMs ?? 5e3;
25065
- if (delay3 <= 0)
25077
+ const delay4 = this.#options.pollIntervalMs ?? 5e3;
25078
+ if (delay4 <= 0)
25066
25079
  return;
25067
25080
  this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
25068
25081
  this.#timer = void 0;
25069
25082
  void this.#track(tick());
25070
- }, delay3);
25083
+ }, delay4);
25071
25084
  this.#timer.unref?.();
25072
25085
  };
25073
25086
  void this.#track(tick());
@@ -26537,13 +26550,13 @@ var init_hub = __esm({
26537
26550
  }
26538
26551
  if (this.#shutdown.signal.aborted)
26539
26552
  return;
26540
- const delay3 = this.#options.pollIntervalMs ?? 5e3;
26541
- if (delay3 <= 0)
26553
+ const delay4 = this.#options.pollIntervalMs ?? 5e3;
26554
+ if (delay4 <= 0)
26542
26555
  return;
26543
26556
  this.#timer = (this.#options.setTimeoutImpl ?? setTimeout)(() => {
26544
26557
  this.#timer = void 0;
26545
26558
  void this.#track(this.#tick());
26546
- }, delay3);
26559
+ }, delay4);
26547
26560
  this.#timer.unref?.();
26548
26561
  }
26549
26562
  /**
@@ -26834,12 +26847,12 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
26834
26847
  if (!released && lastUpdate + RENEWAL_STALE < Date.now())
26835
26848
  compromise();
26836
26849
  }
26837
- function schedule2(delay3 = UPDATE) {
26850
+ function schedule2(delay4 = UPDATE) {
26838
26851
  if (released)
26839
26852
  return;
26840
26853
  timer = setTimeout(() => {
26841
26854
  void update();
26842
- }, delay3);
26855
+ }, delay4);
26843
26856
  timer.unref();
26844
26857
  }
26845
26858
  function retry(error) {
@@ -27622,6 +27635,10 @@ var init_harness_identity = __esm({
27622
27635
  "opencode.ai/docs"
27623
27636
  ];
27624
27637
  HARNESS_IDENTITY_REWRITES = [
27638
+ {
27639
+ pattern: /\btools\.opencode\b/g,
27640
+ replacement: "tools['opencode']"
27641
+ },
27625
27642
  {
27626
27643
  pattern: /You are opencode, /gi,
27627
27644
  replacement: "You are "
@@ -27643,11 +27660,11 @@ var init_harness_identity = __esm({
27643
27660
  replacement: "running inside your development environment"
27644
27661
  },
27645
27662
  {
27646
- pattern: /running inside opencode, a coding agent harness/gi,
27663
+ pattern: /running (?:inside|in) opencode, a coding agent harness/gi,
27647
27664
  replacement: "running inside your development environment"
27648
27665
  },
27649
27666
  {
27650
- pattern: /\brunning inside (?:pi-bolt|pi|opencode)(?!\.\w)(?=$|\s|[.,;:!?])/gi,
27667
+ pattern: /\brunning (?:inside|in) (?:pi-bolt|pi|opencode)(?!\.\w)(?=$|\s|[.,;:!?])/gi,
27651
27668
  replacement: "running inside your development environment"
27652
27669
  }
27653
27670
  ];
@@ -28772,7 +28789,7 @@ function isSchemaObject(value) {
28772
28789
  function describeValue(value) {
28773
28790
  return JSON.stringify(value) ?? String(value);
28774
28791
  }
28775
- function normalizeNullableTypeArray(schema) {
28792
+ function normalizeNullableTypeArray(schema, unionHints) {
28776
28793
  if (!Array.isArray(schema.type))
28777
28794
  return schema;
28778
28795
  if (schema.type.length === 0 || schema.type.some((type) => typeof type !== "string" || !ALLOWED_JSON_SCHEMA_TYPES.has(type.toLowerCase()))) {
@@ -28783,7 +28800,37 @@ function normalizeNullableTypeArray(schema) {
28783
28800
  ];
28784
28801
  const nonNull = types.filter((type) => type !== "null");
28785
28802
  if (nonNull.length > 1) {
28786
- return schema;
28803
+ if (!unionHints)
28804
+ return schema;
28805
+ const { type: _type, ...base } = schema;
28806
+ if (types.includes("null"))
28807
+ base.nullable = true;
28808
+ const coversEveryType = ["object", "array", "string", "boolean"].every((type) => nonNull.includes(type)) && (nonNull.includes("number") || nonNull.includes("integer"));
28809
+ if (!coversEveryType && (Array.isArray(base.anyOf) || Array.isArray(base.oneOf))) {
28810
+ unionHints.push("type: additional union constraints omitted.");
28811
+ return base;
28812
+ }
28813
+ const branches = nonNull.map((type) => {
28814
+ const branch = { type };
28815
+ for (const key of TYPE_ARRAY_BRANCH_FIELDS[type] ?? []) {
28816
+ if (!Object.hasOwn(base, key))
28817
+ continue;
28818
+ if (key === "enum" && (!Array.isArray(base.enum) || !base.enum.every((value) => typeof value === "string")))
28819
+ continue;
28820
+ branch[key] = base[key];
28821
+ }
28822
+ return branch;
28823
+ });
28824
+ for (const key of /* @__PURE__ */ new Set([
28825
+ ...Object.values(TYPE_ARRAY_BRANCH_FIELDS).flat(),
28826
+ "minProperties",
28827
+ "maxProperties"
28828
+ ])) {
28829
+ if (key === "enum" && Array.isArray(base.enum) && !base.enum.every((value) => typeof value === "string"))
28830
+ continue;
28831
+ delete base[key];
28832
+ }
28833
+ return coversEveryType ? base : { ...base, anyOf: branches };
28787
28834
  }
28788
28835
  return {
28789
28836
  ...schema,
@@ -28901,7 +28948,7 @@ function toGeminiSchema(schema, options = {}) {
28901
28948
  return schema;
28902
28949
  }
28903
28950
  const numericConstraintHints = [];
28904
- const inputSchema = normalizeNullableTypeArray(mergeSchemaAllOf(schema, numericConstraintHints));
28951
+ const inputSchema = normalizeNullableTypeArray(mergeSchemaAllOf(schema, numericConstraintHints), options.claudeValidated ? void 0 : numericConstraintHints);
28905
28952
  const schemaType = typeof inputSchema.type === "string" ? inputSchema.type.toUpperCase() : void 0;
28906
28953
  let result = {};
28907
28954
  const propertyNames = /* @__PURE__ */ new Set();
@@ -29252,7 +29299,7 @@ function wrapToolsAsFunctionDeclarations(payload) {
29252
29299
  passthroughToolCount: passthroughTools.length + (hasWebSearchTool && functionDeclarations.length === 0 ? 1 : 0)
29253
29300
  };
29254
29301
  }
29255
- var ALLOWED_SCHEMA_FIELDS, NUMERIC_SCHEMA_CONSTRAINTS, ALLOWED_JSON_SCHEMA_TYPES, CLAUDE_VALIDATED_HINT_FIELDS, VALID_ASPECT_RATIOS;
29302
+ var ALLOWED_SCHEMA_FIELDS, NUMERIC_SCHEMA_CONSTRAINTS, ALLOWED_JSON_SCHEMA_TYPES, TYPE_ARRAY_BRANCH_FIELDS, CLAUDE_VALIDATED_HINT_FIELDS, VALID_ASPECT_RATIOS;
29256
29303
  var init_gemini = __esm({
29257
29304
  "../core/dist/transform/gemini.js"() {
29258
29305
  "use strict";
@@ -29302,6 +29349,30 @@ var init_gemini = __esm({
29302
29349
  "object",
29303
29350
  "null"
29304
29351
  ]);
29352
+ TYPE_ARRAY_BRANCH_FIELDS = {
29353
+ object: [
29354
+ "properties",
29355
+ "required",
29356
+ "propertyOrdering",
29357
+ "additionalProperties"
29358
+ ],
29359
+ array: ["items", "minItems", "maxItems"],
29360
+ string: ["enum", "format", "minLength", "maxLength", "pattern"],
29361
+ number: [
29362
+ "minimum",
29363
+ "maximum",
29364
+ "exclusiveMinimum",
29365
+ "exclusiveMaximum",
29366
+ "multipleOf"
29367
+ ],
29368
+ integer: [
29369
+ "minimum",
29370
+ "maximum",
29371
+ "exclusiveMinimum",
29372
+ "exclusiveMaximum",
29373
+ "multipleOf"
29374
+ ]
29375
+ };
29305
29376
  CLAUDE_VALIDATED_HINT_FIELDS = /* @__PURE__ */ new Set([
29306
29377
  "minLength",
29307
29378
  "maxLength",
@@ -29966,6 +30037,15 @@ function assertRosterBinding(roster, attribution, claustrum) {
29966
30037
  if (!roster || !row?.enabled || row.state !== "active" || row.stale === true || row.unclaimed === true || row.credentialId !== attribution.credentialId || row.accountIdentity !== attribution.accountIdentity || claustrum.isDeclined(roster.declined, attribution.credentialId, attribution.accountIdentity))
29967
30038
  throw new VaultProviderStateError("binding-stale", "the vault route no longer serves the attributed credential and account");
29968
30039
  }
30040
+ function quotaBoundState(current, attribution) {
30041
+ if (current?.quota === void 0 || current.observed.routeId === attribution.routeId && current.observed.credentialId === attribution.credentialId)
30042
+ return current;
30043
+ return Object.freeze({
30044
+ observed: current.observed,
30045
+ ...current.metadata !== void 0 ? { metadata: current.metadata } : {},
30046
+ ...current.extensions !== void 0 ? { extensions: current.extensions } : {}
30047
+ });
30048
+ }
29969
30049
  async function commitVaultProviderState(input2) {
29970
30050
  const { claustrum, fs: fs7, statePath } = input2;
29971
30051
  input2.signal?.throwIfAborted();
@@ -29981,7 +30061,7 @@ async function commitVaultProviderState(input2) {
29981
30061
  const file = await readVaultProviderState(statePath);
29982
30062
  input2.signal?.throwIfAborted();
29983
30063
  const current = vaultAccountState(file, identity4);
29984
- const requested = input2.update(current);
30064
+ const requested = input2.update(quotaBoundState(current, attribution));
29985
30065
  if (isRecord9(requested) && typeof requested.then === "function")
29986
30066
  throw new VaultProviderStateError("invalid-update", "a state update must be synchronous");
29987
30067
  if (requested === void 0)
@@ -30089,7 +30169,7 @@ async function commitVaultProviderStates(input2) {
30089
30169
  const identity4 = entry.attribution.accountIdentity;
30090
30170
  const current = Object.hasOwn(accounts, identity4) ? accounts[identity4] : void 0;
30091
30171
  try {
30092
- const requested = entry.update(current);
30172
+ const requested = entry.update(quotaBoundState(current, entry.attribution));
30093
30173
  if (isRecord9(requested) && typeof requested.then === "function")
30094
30174
  throw new VaultProviderStateError("invalid-update", "a state update must be synchronous");
30095
30175
  if (requested === void 0 || requested === null && !current) {
@@ -30837,12 +30917,12 @@ async function replaceWindowsFile2(from, to, options = {}) {
30837
30917
  const delays = [0, 10, 20, 40, 80, 100];
30838
30918
  let original;
30839
30919
  let attempts2 = 0;
30840
- for (const delay3 of delays) {
30920
+ for (const delay4 of delays) {
30841
30921
  const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
30842
30922
  if (now() >= deadline)
30843
30923
  break;
30844
- if (delay3)
30845
- await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
30924
+ if (delay4)
30925
+ await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay4, Math.max(0, deadline - now())));
30846
30926
  if (now() >= deadline)
30847
30927
  break;
30848
30928
  const fenceStart = now();
@@ -34264,8 +34344,8 @@ function isWindowsSharingError(error, platform) {
34264
34344
  }
34265
34345
  async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile15, unlink: unlink12 }) {
34266
34346
  const started = performance.now();
34267
- for (const delay3 of SHARING_RETRY_DELAYS_MS) {
34268
- if (delay3 > 0) await new Promise((done) => setTimeout(done, delay3));
34347
+ for (const delay4 of SHARING_RETRY_DELAYS_MS) {
34348
+ if (delay4 > 0) await new Promise((done) => setTimeout(done, delay4));
34269
34349
  let same;
34270
34350
  try {
34271
34351
  same = (await io.readFile(file.old)).equals(await io.readFile(file.next));
@@ -38839,7 +38919,7 @@ async function moveSettingsOnce(options) {
38839
38919
  }
38840
38920
 
38841
38921
  // ../core/dist/common-auth-embedded/settings/paths.js
38842
- import { posix, win32 } from "node:path";
38922
+ import { posix, win32 as win322 } from "node:path";
38843
38923
  function isAbsoluteForPlatform(path5, platform) {
38844
38924
  if (platform !== "win32")
38845
38925
  return path5.startsWith("/");
@@ -38850,7 +38930,7 @@ function isAbsoluteForPlatform(path5, platform) {
38850
38930
  return /^[\\/]{2}[^\\/]+[\\/][^\\/]+/.test(path5);
38851
38931
  }
38852
38932
  function cortexkitConfigDir({ env: env3, platform, homedir: homedir17 }) {
38853
- const paths = platform === "win32" ? win32 : posix;
38933
+ const paths = platform === "win32" ? win322 : posix;
38854
38934
  const absolute = (value) => value !== void 0 && isAbsoluteForPlatform(value, platform);
38855
38935
  let base;
38856
38936
  if (absolute(env3.XDG_CONFIG_HOME)) {
@@ -38873,7 +38953,7 @@ function settingsFilePath({ plugin: plugin2, override, ...options }) {
38873
38953
  if (override && isAbsoluteForPlatform(override, options.platform)) {
38874
38954
  return override;
38875
38955
  }
38876
- const paths = options.platform === "win32" ? win32 : posix;
38956
+ const paths = options.platform === "win32" ? win322 : posix;
38877
38957
  return paths.join(cortexkitConfigDir(options), `${plugin2}.jsonc`);
38878
38958
  }
38879
38959
 
@@ -42509,14 +42589,14 @@ var BackgroundVaultQuotaRefresh = class {
42509
42589
  this.abortTick();
42510
42590
  await this.inFlight;
42511
42591
  }
42512
- schedule(delay3, intervalWait = null) {
42592
+ schedule(delay4, intervalWait = null) {
42513
42593
  if (this.disposed || !this.started) return;
42514
42594
  this.intervalWait = intervalWait;
42515
42595
  this.timer = setTimeout(() => {
42516
42596
  this.timer = null;
42517
42597
  this.intervalWait = null;
42518
42598
  void this.tick();
42519
- }, delay3);
42599
+ }, delay4);
42520
42600
  this.timer.unref?.();
42521
42601
  }
42522
42602
  /** One serialized tick; also used by deterministic composition tests. */
@@ -49225,6 +49305,7 @@ function routingHandle(sessionId) {
49225
49305
  var CACHE_WARM_STOP_REASONS = [
49226
49306
  "cost-cap",
49227
49307
  "count-cap",
49308
+ "deadline-missed",
49228
49309
  "outside-hours",
49229
49310
  "session-ended",
49230
49311
  "unsupported"
@@ -50661,11 +50742,23 @@ function createRequestExecutor(deps) {
50661
50742
  };
50662
50743
  }
50663
50744
  const sender = options.transport ?? defaultTransport2;
50664
- const transport = (url, sendInit, sendOptions) => deadline.open(() => {
50745
+ const transport = (url, sendInit, sendOptions, onSenderRejection) => deadline.open(() => {
50665
50746
  waits.resumed();
50666
- return sender(url, sendInit, {
50747
+ const optionsWithSignal = {
50667
50748
  ...sendOptions,
50668
50749
  signal: deadline.signal
50750
+ };
50751
+ if (!onSenderRejection) return sender(url, sendInit, optionsWithSignal);
50752
+ let pending;
50753
+ try {
50754
+ pending = sender(url, sendInit, optionsWithSignal);
50755
+ } catch (error) {
50756
+ onSenderRejection(error);
50757
+ throw error;
50758
+ }
50759
+ return pending.catch((error) => {
50760
+ onSenderRejection(error);
50761
+ throw error;
50669
50762
  });
50670
50763
  });
50671
50764
  const requestSessionIdentity = options.session ?? extractOpenCodeSessionIdentity(init?.headers);
@@ -50714,8 +50807,38 @@ function createRequestExecutor(deps) {
50714
50807
  `[Cache] ${label} model=${cachedStats.model} read=${cachedStats.read} total=${cachedStats.total} hitRate=${cachedStats.hitRate}%`
50715
50808
  );
50716
50809
  }
50717
- let lastFailure = null;
50810
+ let retainedMainAttemptFailure = null;
50718
50811
  let lastError = null;
50812
+ const retainMainTransportFailure = (error) => {
50813
+ retainedMainAttemptFailure = {
50814
+ kind: "transport",
50815
+ error: error instanceof Error ? error : new Error(String(error))
50816
+ };
50817
+ };
50818
+ const terminalMainAttemptFailure = async (fallbackMessage) => {
50819
+ const failure2 = retainedMainAttemptFailure;
50820
+ if (failure2?.kind === "http") {
50821
+ const context = failure2.context;
50822
+ return wire.transformResponse(
50823
+ context.response,
50824
+ context.streaming,
50825
+ context.debugContext,
50826
+ context.requestedModel,
50827
+ context.projectId,
50828
+ context.endpoint,
50829
+ context.effectiveModel,
50830
+ context.sessionId,
50831
+ context.toolDebugMissing,
50832
+ context.toolDebugSummary,
50833
+ debugLines,
50834
+ context.dumpContext
50835
+ );
50836
+ }
50837
+ throw terminalFetchError(
50838
+ lastError ?? (failure2?.kind === "transport" ? failure2.error : null),
50839
+ fallbackMessage
50840
+ );
50841
+ };
50719
50842
  const abortSignal = init?.signal ?? void 0;
50720
50843
  const routingSleep = (ms, reason, attempt) => waits.sleep(
50721
50844
  ms,
@@ -51332,7 +51455,7 @@ function createRequestExecutor(deps) {
51332
51455
  }
51333
51456
  }
51334
51457
  const selected = account;
51335
- const sendPhysical = async (url, sendInit, admission, sendModel, requestKind) => {
51458
+ const sendPhysical = async (url, sendInit, admission, sendModel, requestKind, onMainTransportFailure) => {
51336
51459
  const source = credentials.domain === "local" ? "local" : hasVaultHost2() ? "hosted" : "vault";
51337
51460
  const message = `request-send source=${source} model=${sendModel} account=Account ${account.index + 1}`;
51338
51461
  if (source === "local") log18.info(message);
@@ -51348,10 +51471,15 @@ function createRequestExecutor(deps) {
51348
51471
  abortSignal
51349
51472
  ) : void 0;
51350
51473
  try {
51351
- const response = await transport(url, sendInit, {
51352
- signal: abortSignal,
51353
- onDebug: pushDebug
51354
- });
51474
+ const response = await transport(
51475
+ url,
51476
+ sendInit,
51477
+ {
51478
+ signal: abortSignal,
51479
+ onDebug: pushDebug
51480
+ },
51481
+ onMainTransportFailure
51482
+ );
51355
51483
  return billing?.observe(response) ?? response;
51356
51484
  } catch (error) {
51357
51485
  billing?.end(false);
@@ -51613,6 +51741,12 @@ function createRequestExecutor(deps) {
51613
51741
  toolDebugSummary: prepared.toolDebugSummary,
51614
51742
  dumpContext
51615
51743
  });
51744
+ const retainHttpFailure = (failureResponse) => {
51745
+ retainedMainAttemptFailure = {
51746
+ kind: "http",
51747
+ context: createFailureContext(failureResponse)
51748
+ };
51749
+ };
51616
51750
  await runThinkingWarmup(prepared, sendProjectId);
51617
51751
  await runCacheWarmupProbe(prepared);
51618
51752
  if (config.request_jitter_max_ms > 0) {
@@ -51645,7 +51779,8 @@ function createRequestExecutor(deps) {
51645
51779
  prepared.init,
51646
51780
  sendAdmission,
51647
51781
  prepared.effectiveModel ?? model ?? "unknown",
51648
- kind ?? "primary"
51782
+ kind ?? "primary",
51783
+ retainMainTransportFailure
51649
51784
  );
51650
51785
  if (response.ok) deadline.acceptHeaders();
51651
51786
  apiRequestCount++;
@@ -51773,13 +51908,35 @@ function createRequestExecutor(deps) {
51773
51908
  "UNKNOWN",
51774
51909
  delayMs
51775
51910
  );
51911
+ const now = Date.now();
51912
+ const at = account.cachedQuotaUpdatedAt;
51913
+ const sameQuotaIdentity = credentials.domain === "vault" || account.cachedQuotaAccountId === quotaAccountIdentity(
51914
+ parseRefreshParts(
51915
+ credentials.toAuthDetails(account).refresh
51916
+ ).refreshToken
51917
+ );
51918
+ const emptyUntil = sameQuotaIdentity && at !== void 0 && now - at <= softQuotaCacheTtlMs ? quotaExhaustedUntil(account, family, model, now) : 0;
51919
+ const quotaKey3 = getQuotaKey(family, model);
51920
+ const resets = account.rateLimitResetTimes;
51921
+ if (emptyUntil > (resets[quotaKey3] ?? 0))
51922
+ accountManager.markRateLimited(
51923
+ account,
51924
+ emptyUntil - now,
51925
+ family,
51926
+ model
51927
+ );
51776
51928
  accountManager.requestSaveToDisk();
51929
+ if ((resets[quotaKey3] ?? 0) > now + delayMs) {
51930
+ switchedForUnconfirmed = true;
51931
+ shouldSwitchAccount = true;
51932
+ break;
51933
+ }
51777
51934
  if (unconfirmedRetries >= MAX_UNCONFIRMED_RATE_LIMIT_RETRIES)
51778
51935
  return terminal();
51779
51936
  unconfirmedRetries++;
51780
51937
  const ready = accountManager.getAccounts().some((entry) => {
51781
- const resets = entry.rateLimitResetTimes;
51782
- 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() && (resets[family] ?? 0) <= Date.now() && (resets[getQuotaKey(family, model)] ?? 0) <= Date.now();
51938
+ const resets2 = entry.rateLimitResetTimes;
51939
+ 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();
51783
51940
  });
51784
51941
  if (ready) {
51785
51942
  switchedForUnconfirmed = true;
@@ -51787,6 +51944,11 @@ function createRequestExecutor(deps) {
51787
51944
  break;
51788
51945
  }
51789
51946
  await routingSleep(delayMs, "rate_limited", unconfirmedRetries);
51947
+ if ((resets[quotaKey3] ?? 0) > now + delayMs) {
51948
+ switchedForUnconfirmed = true;
51949
+ shouldSwitchAccount = true;
51950
+ break;
51951
+ }
51790
51952
  i -= 1;
51791
51953
  continue;
51792
51954
  }
@@ -51816,7 +51978,7 @@ function createRequestExecutor(deps) {
51816
51978
  pushDebug(
51817
51979
  `Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted, switching account`
51818
51980
  );
51819
- lastFailure = createFailureContext(response);
51981
+ retainHttpFailure(response);
51820
51982
  shouldSwitchAccount = true;
51821
51983
  break;
51822
51984
  }
@@ -51966,7 +52128,7 @@ function createRequestExecutor(deps) {
51966
52128
  backoff.attempt
51967
52129
  );
51968
52130
  }
51969
- lastFailure = createFailureContext(response);
52131
+ retainHttpFailure(response);
51970
52132
  shouldSwitchAccount = true;
51971
52133
  break;
51972
52134
  }
@@ -52028,7 +52190,7 @@ function createRequestExecutor(deps) {
52028
52190
  `account-ineligible: disabled account ${account.index}`
52029
52191
  );
52030
52192
  trackers.health.recordFailure(account.index);
52031
- lastFailure = createFailureContext(response);
52193
+ retainHttpFailure(response);
52032
52194
  shouldSwitchAccount = true;
52033
52195
  break;
52034
52196
  }
@@ -52063,7 +52225,7 @@ function createRequestExecutor(deps) {
52063
52225
  `verification-required: disabled account ${account.index}`
52064
52226
  );
52065
52227
  trackers.health.recordFailure(account.index);
52066
- lastFailure = createFailureContext(response);
52228
+ retainHttpFailure(response);
52067
52229
  shouldSwitchAccount = true;
52068
52230
  break;
52069
52231
  }
@@ -52071,7 +52233,7 @@ function createRequestExecutor(deps) {
52071
52233
  const shouldRetryEndpoint = response.status === 404 || response.status >= 500;
52072
52234
  if (shouldRetryEndpoint && i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
52073
52235
  await logResponseBody2(debugContext, response, response.status);
52074
- lastFailure = createFailureContext(response);
52236
+ retainHttpFailure(response);
52075
52237
  continue;
52076
52238
  }
52077
52239
  if (response.ok) {
@@ -52342,68 +52504,16 @@ function createRequestExecutor(deps) {
52342
52504
  pushDebug(
52343
52505
  `account-switch-cap: exceeded max_account_switches=${maxAccountSwitches}, giving up`
52344
52506
  );
52345
- if (lastFailure) {
52346
- return wire.transformResponse(
52347
- lastFailure.response,
52348
- lastFailure.streaming,
52349
- lastFailure.debugContext,
52350
- lastFailure.requestedModel,
52351
- lastFailure.projectId,
52352
- lastFailure.endpoint,
52353
- lastFailure.effectiveModel,
52354
- lastFailure.sessionId,
52355
- lastFailure.toolDebugMissing,
52356
- lastFailure.toolDebugSummary,
52357
- debugLines,
52358
- lastFailure.dumpContext
52359
- );
52360
- }
52361
- throw terminalFetchError(
52362
- lastError,
52507
+ return terminalMainAttemptFailure(
52363
52508
  `Exceeded max account switches (${maxAccountSwitches}). All accounts rate-limited.`
52364
52509
  );
52365
52510
  }
52366
52511
  if (accountCount <= 1) {
52367
- if (lastFailure) {
52368
- return wire.transformResponse(
52369
- lastFailure.response,
52370
- lastFailure.streaming,
52371
- lastFailure.debugContext,
52372
- lastFailure.requestedModel,
52373
- lastFailure.projectId,
52374
- lastFailure.endpoint,
52375
- lastFailure.effectiveModel,
52376
- lastFailure.sessionId,
52377
- lastFailure.toolDebugMissing,
52378
- lastFailure.toolDebugSummary,
52379
- debugLines,
52380
- lastFailure.dumpContext
52381
- );
52382
- }
52383
- throw terminalFetchError(
52384
- lastError,
52385
- "All Antigravity endpoints failed"
52386
- );
52512
+ return terminalMainAttemptFailure("All Antigravity endpoints failed");
52387
52513
  }
52388
52514
  continue;
52389
52515
  }
52390
- if (lastFailure) {
52391
- return wire.transformResponse(
52392
- lastFailure.response,
52393
- lastFailure.streaming,
52394
- lastFailure.debugContext,
52395
- lastFailure.requestedModel,
52396
- lastFailure.projectId,
52397
- lastFailure.endpoint,
52398
- lastFailure.effectiveModel,
52399
- lastFailure.sessionId,
52400
- lastFailure.toolDebugMissing,
52401
- lastFailure.toolDebugSummary,
52402
- debugLines,
52403
- lastFailure.dumpContext
52404
- );
52405
- }
52406
- throw terminalFetchError(lastError, "All Antigravity accounts failed");
52516
+ return terminalMainAttemptFailure("All Antigravity accounts failed");
52407
52517
  }
52408
52518
  }
52409
52519
  function drain() {
@@ -52627,9 +52737,9 @@ init_version_fence();
52627
52737
 
52628
52738
  // src/settings/location.ts
52629
52739
  import { realpath as realpath5 } from "node:fs/promises";
52630
- import { posix as posix2, win32 as win322 } from "node:path";
52740
+ import { posix as posix2, win32 as win323 } from "node:path";
52631
52741
  async function folderIdentity(folder, platform) {
52632
- const paths = platform === "win32" ? win322 : posix2;
52742
+ const paths = platform === "win32" ? win323 : posix2;
52633
52743
  try {
52634
52744
  return await realpath5(folder);
52635
52745
  } catch {
@@ -52638,7 +52748,7 @@ async function folderIdentity(folder, platform) {
52638
52748
  }
52639
52749
  async function resolveSettingsLocation(options) {
52640
52750
  const { env: env3, platform, homedir: homedir17 } = options;
52641
- const paths = platform === "win32" ? win322 : posix2;
52751
+ const paths = platform === "win32" ? win323 : posix2;
52642
52752
  const override = env3.OPENCODE_ANTIGRAVITY_AUTH_SETTINGS_FILE;
52643
52753
  const file = settingsFilePath({
52644
52754
  plugin: "antigravity-auth",
@@ -53015,12 +53125,12 @@ function createSettingsRuntime(options) {
53015
53125
  void enqueue(refreshAll);
53016
53126
  });
53017
53127
  };
53018
- const scheduleAttempt = (delay3) => {
53128
+ const scheduleAttempt = (delay4) => {
53019
53129
  if (disposed) return;
53020
53130
  retryTimer = setTimeout(() => {
53021
53131
  retryTimer = void 0;
53022
53132
  void enqueue(attemptMove);
53023
- }, delay3);
53133
+ }, delay4);
53024
53134
  retryTimer.unref?.();
53025
53135
  };
53026
53136
  const attemptMove = async () => {
@@ -61057,12 +61167,12 @@ import { parse } from "jsonc-parser";
61057
61167
 
61058
61168
  // src/common-auth-embedded/setup/paths.js
61059
61169
  import { homedir as homedir11 } from "node:os";
61060
- import { posix as posix3, win32 as win323 } from "node:path";
61170
+ import { posix as posix3, win32 as win324 } from "node:path";
61061
61171
  import { fileURLToPath } from "node:url";
61062
61172
  function setupPaths(io = {}) {
61063
61173
  const env3 = io.env ?? process.env;
61064
61174
  const platform = io.platform ?? process.platform;
61065
- const path5 = platform === "win32" ? win323 : posix3;
61175
+ const path5 = platform === "win32" ? win324 : posix3;
61066
61176
  const home = io.home ?? (platform === "win32" ? env3.USERPROFILE : env3.HOME) ?? homedir11();
61067
61177
  const cwd = io.cwd ?? process.cwd();
61068
61178
  const absolute = (value) => path5.resolve(cwd, value);
@@ -61289,7 +61399,20 @@ import { setTimeout as delay } from "node:timers/promises";
61289
61399
  import { writeEnrollmentTokenFile as writeEnrollmentTokenFile3 } from "@cortexkit/claustrum-client";
61290
61400
 
61291
61401
  // src/common-auth-embedded/setup/process-fence.js
61402
+ import { statSync as statSync7 } from "node:fs";
61403
+ import { win32 as win325 } from "node:path";
61292
61404
  var WINDOWS_CIM_TIMEOUT_MS = 45e3;
61405
+ var WINDOWS_ARM_POWERSHELL_TIMEOUT_MS = 9e4;
61406
+ function isFile(file) {
61407
+ try {
61408
+ return statSync7(file).isFile();
61409
+ } catch {
61410
+ return false;
61411
+ }
61412
+ }
61413
+ function windowsEnv(env3, name) {
61414
+ return Object.entries(env3).find(([key]) => key.toUpperCase() === name.toUpperCase())?.[1];
61415
+ }
61293
61416
  var HOSTS = /* @__PURE__ */ new Set(["opencode", "litecode", "opencode2", "pi"]);
61294
61417
  var RUNTIMES = /* @__PURE__ */ new Set(["node", "bun"]);
61295
61418
  var WINDOWS_FENCE_FILTER = [...HOSTS, ...RUNTIMES].map((name) => `Name LIKE '${name}%'`).join(" OR ");
@@ -61361,6 +61484,7 @@ function hostName(command) {
61361
61484
  var ProcessInspectionError = class extends Error {
61362
61485
  code = "process-inspection-failed";
61363
61486
  step;
61487
+ program;
61364
61488
  exitCode;
61365
61489
  signal;
61366
61490
  timedOut;
@@ -61369,6 +61493,7 @@ var ProcessInspectionError = class extends Error {
61369
61493
  super("Process inspection failed; setup cannot prove hosts are stopped.");
61370
61494
  this.name = "ProcessInspectionError";
61371
61495
  this.step = details.step;
61496
+ this.program = details.program;
61372
61497
  this.exitCode = details.exitCode;
61373
61498
  this.signal = details.signal;
61374
61499
  this.timedOut = details.timedOut;
@@ -61396,6 +61521,8 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);
61396
61521
  };
61397
61522
  async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
61398
61523
  const windows2 = (options.platform ?? process.platform) === "win32";
61524
+ const env3 = options.env ?? process.env;
61525
+ const system32 = windows2 ? win325.resolve(windowsEnv(env3, "SystemRoot") ?? windowsEnv(env3, "windir") ?? "C:\\Windows", "System32") : "";
61399
61526
  const selfPid = options.selfPid ?? process.pid;
61400
61527
  let inspection = {
61401
61528
  step: windows2 ? "tasklist" : "ps",
@@ -61404,10 +61531,11 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
61404
61531
  timedOut: false,
61405
61532
  durationMs: 0
61406
61533
  };
61407
- const inspect = async (step, file, args, timeoutMs) => {
61534
+ const inspect = async (step, file, args, timeoutMs, program) => {
61408
61535
  const started = performance.now();
61409
61536
  inspection = {
61410
61537
  step,
61538
+ ...program && { program },
61411
61539
  exitCode: null,
61412
61540
  signal: null,
61413
61541
  timedOut: false,
@@ -61420,6 +61548,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
61420
61548
  });
61421
61549
  inspection = {
61422
61550
  step,
61551
+ ...program && { program },
61423
61552
  exitCode: result.exitCode,
61424
61553
  signal: result.signal ?? null,
61425
61554
  timedOut: result.timedOut ?? false,
@@ -61432,9 +61561,23 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
61432
61561
  options.onStep?.({ ...inspection });
61433
61562
  }
61434
61563
  };
61564
+ const inspectCim = (args) => {
61565
+ const pwsh = win325.resolve(windowsEnv(env3, "ProgramFiles") ?? "C:\\Program Files", "PowerShell", "7", "pwsh.exe");
61566
+ const program = (options.isFile ?? isFile)(pwsh) ? "pwsh" : "powershell";
61567
+ const arm64 = (windowsEnv(env3, "PROCESSOR_ARCHITEW6432") ?? windowsEnv(env3, "PROCESSOR_ARCHITECTURE"))?.toUpperCase() === "ARM64";
61568
+ const slow = program === "powershell" && arm64;
61569
+ if (slow)
61570
+ options.onProgress?.("Checking that OpenCode and Pi are not running. Without PowerShell 7 this can take up to a minute on Windows ARM; installing PowerShell 7 makes it fast.");
61571
+ return inspect("CIM", program === "pwsh" ? pwsh : win325.resolve(system32, "WindowsPowerShell", "v1.0", "powershell.exe"), args, slow ? WINDOWS_ARM_POWERSHELL_TIMEOUT_MS : WINDOWS_CIM_TIMEOUT_MS, program);
61572
+ };
61435
61573
  try {
61436
61574
  if (windows2 && options.hostImagesOnly) {
61437
- const details = await inspect("CIM", "powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_FENCE_QUERY], WINDOWS_CIM_TIMEOUT_MS);
61575
+ const details = await inspectCim([
61576
+ "-NoProfile",
61577
+ "-NonInteractive",
61578
+ "-Command",
61579
+ WINDOWS_FENCE_QUERY
61580
+ ]);
61438
61581
  if (details.exitCode !== 0)
61439
61582
  throw new ProcessInspectionError(inspection);
61440
61583
  const value = JSON.parse(details.stdout);
@@ -61456,7 +61599,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
61456
61599
  }
61457
61600
  return processes2;
61458
61601
  }
61459
- const result = await inspect(windows2 ? "tasklist" : "ps", windows2 ? "tasklist.exe" : "ps", windows2 ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
61602
+ const result = await inspect(windows2 ? "tasklist" : "ps", windows2 ? win325.resolve(system32, "tasklist.exe") : "ps", windows2 ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
61460
61603
  if (result.exitCode !== 0)
61461
61604
  throw new ProcessInspectionError(inspection);
61462
61605
  const processes = [];
@@ -61490,12 +61633,12 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
61490
61633
  throw new ProcessInspectionError(inspection);
61491
61634
  const runtimes = processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command));
61492
61635
  if (windows2 && runtimes.length && options.inspectRuntimes !== false) {
61493
- const details = await inspect("CIM", "powershell.exe", [
61636
+ const details = await inspectCim([
61494
61637
  "-NoProfile",
61495
61638
  "-NonInteractive",
61496
61639
  "-Command",
61497
61640
  `$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`
61498
- ], WINDOWS_CIM_TIMEOUT_MS);
61641
+ ]);
61499
61642
  if (details.exitCode !== 0)
61500
61643
  throw new ProcessInspectionError(inspection);
61501
61644
  const value = JSON.parse(details.stdout || "null");
@@ -61551,6 +61694,36 @@ async function assertHostsStopped(fence, env3) {
61551
61694
  throw new ProcessFenceViolationError(active2);
61552
61695
  }
61553
61696
 
61697
+ // src/common-auth-embedded/setup/process-guard.js
61698
+ var SetupProcessGuard = class {
61699
+ inspect;
61700
+ now;
61701
+ #checkedAt;
61702
+ constructor(inspect, now = () => performance.now()) {
61703
+ this.inspect = inspect;
61704
+ this.now = now;
61705
+ }
61706
+ async check(options = {}) {
61707
+ if (options.reuse && this.#checkedAt !== void 0) {
61708
+ const age = this.now() - this.#checkedAt;
61709
+ if (age >= 0 && age < 5e3)
61710
+ return;
61711
+ }
61712
+ this.#checkedAt = void 0;
61713
+ await this.inspect();
61714
+ this.#checkedAt = this.now();
61715
+ }
61716
+ /** Callbacks, writes and waits can all make an earlier inspection stale. */
61717
+ async step(run) {
61718
+ this.#checkedAt = void 0;
61719
+ try {
61720
+ return await run();
61721
+ } finally {
61722
+ this.#checkedAt = void 0;
61723
+ }
61724
+ }
61725
+ };
61726
+
61554
61727
  // src/common-auth-embedded/setup/enroll.js
61555
61728
  var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
61556
61729
  var UNSUPPORTED_VAULT_MESSAGE = 'This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.';
@@ -61579,7 +61752,8 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
61579
61752
  throw new Error(VAULT_HOST_CONNECT_REFUSAL2);
61580
61753
  const { name, displayName, requestedGrants, grantFallback, paths: input2 } = plugin2.vault.hosts[host];
61581
61754
  const paths = hostEnrollmentPaths2(input2);
61582
- await fence();
61755
+ const guard = typeof fence === "function" ? new SetupProcessGuard(fence, io.now) : fence;
61756
+ await guard.check({ reuse: true });
61583
61757
  const client = await (io.connect ?? connectClaustrumEnrollmentClient2)({
61584
61758
  connectionFile: plugin2.vault.connectionFile,
61585
61759
  handshakeTimeoutMs: 2e3
@@ -61600,11 +61774,10 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
61600
61774
  // starts PowerShell.
61601
61775
  client,
61602
61776
  writeTokenFile: async (path5, file) => {
61603
- await fence();
61604
- await writeEnrollmentTokenFile3(path5, file);
61777
+ await guard.check();
61778
+ await guard.step(() => writeEnrollmentTokenFile3(path5, file));
61605
61779
  }
61606
61780
  });
61607
- await fence();
61608
61781
  const initial = await manager.status();
61609
61782
  if (initial.state === "approved") {
61610
61783
  printLine2(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
@@ -61621,7 +61794,8 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
61621
61794
  let reportedCode;
61622
61795
  let failedProposals = 0;
61623
61796
  for (; ; ) {
61624
- const status = await manager.reconcile();
61797
+ await guard.check({ reuse: true });
61798
+ const status = await guard.step(() => manager.reconcile());
61625
61799
  if (status.state === "approved") {
61626
61800
  printLine2(terminal, `Connected ${host} to Claustrum.`);
61627
61801
  const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
@@ -61669,8 +61843,8 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
61669
61843
  const remaining = deadline - now();
61670
61844
  if (remaining <= 0)
61671
61845
  break;
61672
- await wait2(Math.min(pause, remaining));
61673
- await fence();
61846
+ await guard.step(() => wait2(Math.min(pause, remaining)));
61847
+ await guard.check();
61674
61848
  }
61675
61849
  if (printedRequest)
61676
61850
  throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
@@ -61820,6 +61994,8 @@ async function selectSetupHosts(terminal, found) {
61820
61994
  }
61821
61995
 
61822
61996
  // src/common-auth-embedded/setup/register.js
61997
+ import { rename as rename15 } from "node:fs/promises";
61998
+ import { setTimeout as delay3 } from "node:timers/promises";
61823
61999
  import { domainToUnicode } from "node:url";
61824
62000
  import { applyEdits as applyEdits2, createScanner as createScanner2, findNodeAtLocation as findNodeAtLocation2, modify as modify2, parse as parse2, parseTree as parseTree2 } from "jsonc-parser";
61825
62001
 
@@ -62029,12 +62205,15 @@ function planOpenCodeRegistration(plugin2, generation, io = {}) {
62029
62205
  });
62030
62206
  }
62031
62207
  async function registerOpenCode(writes, beforeWrite) {
62208
+ const guard = typeof beforeWrite === "function" ? new SetupProcessGuard(beforeWrite) : beforeWrite;
62032
62209
  for (const write of writes) {
62033
62210
  if (!write.changed)
62034
62211
  continue;
62035
- await beforeWrite?.();
62036
62212
  await writeHostConfigAtomic(write.path, write.content, {
62037
- beforeRename: beforeWrite
62213
+ // Only the rename publishes host-readable config; recheck on every retry.
62214
+ beforeRename: guard ? () => guard.check({ reuse: true }) : void 0,
62215
+ rename: guard ? (from, to) => guard.step(() => rename15(from, to)) : void 0,
62216
+ wait: guard ? (ms) => guard.step(() => delay3(ms)) : void 0
62038
62217
  });
62039
62218
  }
62040
62219
  }
@@ -62133,7 +62312,11 @@ async function runSetup(plugin2, argv = [], io = {}) {
62133
62312
  return { hosts, dryRun: options.dryRun, mode: "local", detection };
62134
62313
  }
62135
62314
  const { env: env3, platform } = setupPaths(io);
62136
- const fence = io.fence ?? createProcessFence(io.runner ?? defaultCommandRunner, { platform });
62315
+ const fence = io.fence ?? createProcessFence(io.runner ?? defaultCommandRunner, {
62316
+ platform,
62317
+ isFile: io.fs?.isFile.bind(io.fs),
62318
+ onProgress: (line) => printLine2(terminal, line)
62319
+ });
62137
62320
  const stopped = async () => {
62138
62321
  try {
62139
62322
  await assertHostsStopped(fence, env3);
@@ -62143,6 +62326,7 @@ async function runSetup(plugin2, argv = [], io = {}) {
62143
62326
  throw error;
62144
62327
  }
62145
62328
  };
62329
+ const guard = new SetupProcessGuard(stopped, io.now);
62146
62330
  printLine2(terminal, "Checking that OpenCode and Pi are not running\u2026");
62147
62331
  if (options.dryRun) {
62148
62332
  try {
@@ -62158,16 +62342,17 @@ async function runSetup(plugin2, argv = [], io = {}) {
62158
62342
  if (error instanceof ProcessInspectionError)
62159
62343
  printLine2(terminal, error.refusalText);
62160
62344
  }
62161
- } else
62162
- await stopped();
62345
+ } else {
62346
+ await guard.check();
62347
+ }
62163
62348
  if ((options.claustrum || options.enrollOnly) && !detection.claustrum.available)
62164
62349
  throw new Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");
62165
62350
  let useVault = options.claustrum || options.enrollOnly;
62166
62351
  if (!useVault && !options.login && !options.noClaustrum && !assumeYes && detection.claustrum.available && isInteractive2(terminal)) {
62167
- const choice = await select2(terminal, [
62352
+ const choice = await guard.step(() => select2(terminal, [
62168
62353
  { label: "No", value: false },
62169
62354
  { label: "Yes", value: true }
62170
- ], { message: "Connect these hosts to the Claustrum vault?" });
62355
+ ], { message: "Connect these hosts to the Claustrum vault?" }));
62171
62356
  if (choice === null) {
62172
62357
  printLine2(terminal, "Setup cancelled. Nothing was changed.");
62173
62358
  return { hosts: [], dryRun: options.dryRun, mode: "local", detection };
@@ -62218,13 +62403,14 @@ ${write.content}`);
62218
62403
  const enrollmentAccess = /* @__PURE__ */ new Map();
62219
62404
  try {
62220
62405
  for (const host of hosts) {
62221
- await stopped();
62222
- await plugin2.beforeSignIn?.(host, context);
62223
- await stopped();
62406
+ if (plugin2.beforeSignIn) {
62407
+ await guard.check({ reuse: true });
62408
+ await guard.step(() => plugin2.beforeSignIn?.(host, context));
62409
+ }
62224
62410
  if (useVault) {
62225
62411
  enrollment.set(host, "unknown");
62226
62412
  try {
62227
- const access = await connectSetupHost(plugin2, host, io, terminal, stopped);
62413
+ const access = await connectSetupHost(plugin2, host, io, terminal, guard);
62228
62414
  if (access)
62229
62415
  enrollmentAccess.set(host, access);
62230
62416
  } catch (error) {
@@ -62233,19 +62419,26 @@ ${write.content}`);
62233
62419
  throw error;
62234
62420
  }
62235
62421
  enrollment.set(host, "enrolled");
62236
- } else
62237
- await plugin2.signInLocal(host, context);
62238
- await stopped();
62422
+ } else {
62423
+ await guard.check({ reuse: true });
62424
+ await guard.step(() => plugin2.signInLocal(host, context));
62425
+ }
62239
62426
  if (options.enrollOnly)
62240
62427
  continue;
62241
- await plugin2.beforeRegister?.(host, mode, context);
62242
- await stopped();
62428
+ if (plugin2.beforeRegister) {
62429
+ await guard.check({ reuse: true });
62430
+ await guard.step(() => plugin2.beforeRegister?.(host, mode, context));
62431
+ }
62243
62432
  if (host === "opencode")
62244
- await registerOpenCode(writes, stopped);
62245
- else
62246
- await registerPi(plugin2, detection.pi.executable, io);
62247
- await stopped();
62248
- await plugin2.migrate?.(host, context);
62433
+ await registerOpenCode(writes, guard);
62434
+ else {
62435
+ await guard.check({ reuse: true });
62436
+ await guard.step(() => registerPi(plugin2, detection.pi.executable, io));
62437
+ }
62438
+ if (plugin2.migrate) {
62439
+ await guard.check({ reuse: true });
62440
+ await guard.step(() => plugin2.migrate?.(host, context));
62441
+ }
62249
62442
  }
62250
62443
  } catch (error) {
62251
62444
  if (enrollment.size === 0)
@@ -63908,7 +64101,7 @@ function isSessionId(value) {
63908
64101
  // src/common-auth-embedded/rpc/port-file.js
63909
64102
  init_private_files2();
63910
64103
  import { createHash as createHash21, randomUUID as randomUUID25 } from "node:crypto";
63911
- import { chmod as chmod7, mkdir as mkdir20, open as open13, readdir as readdir7, rename as rename15, rmdir as rmdir3, stat as stat20, unlink as unlink16 } from "node:fs/promises";
64104
+ import { chmod as chmod7, mkdir as mkdir20, open as open13, readdir as readdir7, rename as rename16, rmdir as rmdir3, stat as stat20, unlink as unlink16 } from "node:fs/promises";
63912
64105
  import { uptime as uptime2 } from "node:os";
63913
64106
  import { join as join43, resolve as resolve31 } from "node:path";
63914
64107
  function staleBefore(clock2) {
@@ -63990,7 +64183,7 @@ async function writePortFile(dir, entry, options = {}) {
63990
64183
  await handle.chmod(384);
63991
64184
  await handle.close();
63992
64185
  handle = void 0;
63993
- await rename15(tmp, target);
64186
+ await rename16(tmp, target);
63994
64187
  created = false;
63995
64188
  } finally {
63996
64189
  await handle?.close().catch(() => {