@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/index.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((resolve32, 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
  resolve32();
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) {
@@ -30844,12 +30924,12 @@ async function replaceWindowsFile2(from, to, options = {}) {
30844
30924
  const delays = [0, 10, 20, 40, 80, 100];
30845
30925
  let original;
30846
30926
  let attempts2 = 0;
30847
- for (const delay3 of delays) {
30927
+ for (const delay4 of delays) {
30848
30928
  const deadline = Math.min(retryDeadline ?? Infinity, leaseDeadline);
30849
30929
  if (now() >= deadline)
30850
30930
  break;
30851
- if (delay3)
30852
- await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay3, Math.max(0, deadline - now())));
30931
+ if (delay4)
30932
+ await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay4, Math.max(0, deadline - now())));
30853
30933
  if (now() >= deadline)
30854
30934
  break;
30855
30935
  const fenceStart = now();
@@ -34360,8 +34440,8 @@ function isWindowsSharingError(error, platform) {
34360
34440
  }
34361
34441
  async function unlinkIfIdentical(file, stateDir, guard, io = { platform: process.platform, readFile: readFile12, unlink: unlink11 }) {
34362
34442
  const started = performance.now();
34363
- for (const delay3 of SHARING_RETRY_DELAYS_MS) {
34364
- if (delay3 > 0) await new Promise((done) => setTimeout(done, delay3));
34443
+ for (const delay4 of SHARING_RETRY_DELAYS_MS) {
34444
+ if (delay4 > 0) await new Promise((done) => setTimeout(done, delay4));
34365
34445
  let same;
34366
34446
  try {
34367
34447
  same = (await io.readFile(file.old)).equals(await io.readFile(file.next));
@@ -40712,12 +40792,12 @@ import { parse } from "jsonc-parser";
40712
40792
 
40713
40793
  // src/common-auth-embedded/setup/paths.js
40714
40794
  import { homedir as homedir7 } from "node:os";
40715
- import { posix, win32 } from "node:path";
40795
+ import { posix, win32 as win322 } from "node:path";
40716
40796
  import { fileURLToPath } from "node:url";
40717
40797
  function setupPaths(io = {}) {
40718
40798
  const env3 = io.env ?? process.env;
40719
40799
  const platform = io.platform ?? process.platform;
40720
- const path5 = platform === "win32" ? win32 : posix;
40800
+ const path5 = platform === "win32" ? win322 : posix;
40721
40801
  const home = io.home ?? (platform === "win32" ? env3.USERPROFILE : env3.HOME) ?? homedir7();
40722
40802
  const cwd = io.cwd ?? process.cwd();
40723
40803
  const absolute = (value) => path5.resolve(cwd, value);
@@ -40944,7 +41024,20 @@ import { setTimeout as delay } from "node:timers/promises";
40944
41024
  import { writeEnrollmentTokenFile as writeEnrollmentTokenFile3 } from "@cortexkit/claustrum-client";
40945
41025
 
40946
41026
  // src/common-auth-embedded/setup/process-fence.js
41027
+ import { statSync as statSync6 } from "node:fs";
41028
+ import { win32 as win323 } from "node:path";
40947
41029
  var WINDOWS_CIM_TIMEOUT_MS = 45e3;
41030
+ var WINDOWS_ARM_POWERSHELL_TIMEOUT_MS = 9e4;
41031
+ function isFile(file) {
41032
+ try {
41033
+ return statSync6(file).isFile();
41034
+ } catch {
41035
+ return false;
41036
+ }
41037
+ }
41038
+ function windowsEnv(env3, name) {
41039
+ return Object.entries(env3).find(([key]) => key.toUpperCase() === name.toUpperCase())?.[1];
41040
+ }
40948
41041
  var HOSTS = /* @__PURE__ */ new Set(["opencode", "litecode", "opencode2", "pi"]);
40949
41042
  var RUNTIMES = /* @__PURE__ */ new Set(["node", "bun"]);
40950
41043
  var WINDOWS_FENCE_FILTER = [...HOSTS, ...RUNTIMES].map((name) => `Name LIKE '${name}%'`).join(" OR ");
@@ -41016,6 +41109,7 @@ function hostName(command) {
41016
41109
  var ProcessInspectionError = class extends Error {
41017
41110
  code = "process-inspection-failed";
41018
41111
  step;
41112
+ program;
41019
41113
  exitCode;
41020
41114
  signal;
41021
41115
  timedOut;
@@ -41024,6 +41118,7 @@ var ProcessInspectionError = class extends Error {
41024
41118
  super("Process inspection failed; setup cannot prove hosts are stopped.");
41025
41119
  this.name = "ProcessInspectionError";
41026
41120
  this.step = details.step;
41121
+ this.program = details.program;
41027
41122
  this.exitCode = details.exitCode;
41028
41123
  this.signal = details.signal;
41029
41124
  this.timedOut = details.timedOut;
@@ -41051,6 +41146,8 @@ Please quit all OpenCode, LiteCode, and Pi processes before running setup.`);
41051
41146
  };
41052
41147
  async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
41053
41148
  const windows2 = (options.platform ?? process.platform) === "win32";
41149
+ const env3 = options.env ?? process.env;
41150
+ const system32 = windows2 ? win323.resolve(windowsEnv(env3, "SystemRoot") ?? windowsEnv(env3, "windir") ?? "C:\\Windows", "System32") : "";
41054
41151
  const selfPid = options.selfPid ?? process.pid;
41055
41152
  let inspection = {
41056
41153
  step: windows2 ? "tasklist" : "ps",
@@ -41059,10 +41156,11 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
41059
41156
  timedOut: false,
41060
41157
  durationMs: 0
41061
41158
  };
41062
- const inspect = async (step, file, args, timeoutMs) => {
41159
+ const inspect = async (step, file, args, timeoutMs, program) => {
41063
41160
  const started = performance.now();
41064
41161
  inspection = {
41065
41162
  step,
41163
+ ...program && { program },
41066
41164
  exitCode: null,
41067
41165
  signal: null,
41068
41166
  timedOut: false,
@@ -41075,6 +41173,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
41075
41173
  });
41076
41174
  inspection = {
41077
41175
  step,
41176
+ ...program && { program },
41078
41177
  exitCode: result.exitCode,
41079
41178
  signal: result.signal ?? null,
41080
41179
  timedOut: result.timedOut ?? false,
@@ -41087,9 +41186,23 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
41087
41186
  options.onStep?.({ ...inspection });
41088
41187
  }
41089
41188
  };
41189
+ const inspectCim = (args) => {
41190
+ const pwsh = win323.resolve(windowsEnv(env3, "ProgramFiles") ?? "C:\\Program Files", "PowerShell", "7", "pwsh.exe");
41191
+ const program = (options.isFile ?? isFile)(pwsh) ? "pwsh" : "powershell";
41192
+ const arm64 = (windowsEnv(env3, "PROCESSOR_ARCHITEW6432") ?? windowsEnv(env3, "PROCESSOR_ARCHITECTURE"))?.toUpperCase() === "ARM64";
41193
+ const slow = program === "powershell" && arm64;
41194
+ if (slow)
41195
+ 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.");
41196
+ return inspect("CIM", program === "pwsh" ? pwsh : win323.resolve(system32, "WindowsPowerShell", "v1.0", "powershell.exe"), args, slow ? WINDOWS_ARM_POWERSHELL_TIMEOUT_MS : WINDOWS_CIM_TIMEOUT_MS, program);
41197
+ };
41090
41198
  try {
41091
41199
  if (windows2 && options.hostImagesOnly) {
41092
- const details = await inspect("CIM", "powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_FENCE_QUERY], WINDOWS_CIM_TIMEOUT_MS);
41200
+ const details = await inspectCim([
41201
+ "-NoProfile",
41202
+ "-NonInteractive",
41203
+ "-Command",
41204
+ WINDOWS_FENCE_QUERY
41205
+ ]);
41093
41206
  if (details.exitCode !== 0)
41094
41207
  throw new ProcessInspectionError(inspection);
41095
41208
  const value = JSON.parse(details.stdout);
@@ -41111,7 +41224,7 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
41111
41224
  }
41112
41225
  return processes2;
41113
41226
  }
41114
- const result = await inspect(windows2 ? "tasklist" : "ps", windows2 ? "tasklist.exe" : "ps", windows2 ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
41227
+ const result = await inspect(windows2 ? "tasklist" : "ps", windows2 ? win323.resolve(system32, "tasklist.exe") : "ps", windows2 ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
41115
41228
  if (result.exitCode !== 0)
41116
41229
  throw new ProcessInspectionError(inspection);
41117
41230
  const processes = [];
@@ -41145,12 +41258,12 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
41145
41258
  throw new ProcessInspectionError(inspection);
41146
41259
  const runtimes = processes.filter((entry) => entry.pid !== selfPid && /^(?:node|bun)\.exe$/i.test(entry.command));
41147
41260
  if (windows2 && runtimes.length && options.inspectRuntimes !== false) {
41148
- const details = await inspect("CIM", "powershell.exe", [
41261
+ const details = await inspectCim([
41149
41262
  "-NoProfile",
41150
41263
  "-NonInteractive",
41151
41264
  "-Command",
41152
41265
  `$ErrorActionPreference = 'Stop'; Get-CimInstance Win32_Process -Filter "Name = 'node.exe' OR Name = 'bun.exe'" | Select-Object ProcessId,CommandLine | ConvertTo-Json -Compress`
41153
- ], WINDOWS_CIM_TIMEOUT_MS);
41266
+ ]);
41154
41267
  if (details.exitCode !== 0)
41155
41268
  throw new ProcessInspectionError(inspection);
41156
41269
  const value = JSON.parse(details.stdout || "null");
@@ -41206,6 +41319,36 @@ async function assertHostsStopped(fence, env3) {
41206
41319
  throw new ProcessFenceViolationError(active2);
41207
41320
  }
41208
41321
 
41322
+ // src/common-auth-embedded/setup/process-guard.js
41323
+ var SetupProcessGuard = class {
41324
+ inspect;
41325
+ now;
41326
+ #checkedAt;
41327
+ constructor(inspect, now = () => performance.now()) {
41328
+ this.inspect = inspect;
41329
+ this.now = now;
41330
+ }
41331
+ async check(options = {}) {
41332
+ if (options.reuse && this.#checkedAt !== void 0) {
41333
+ const age = this.now() - this.#checkedAt;
41334
+ if (age >= 0 && age < 5e3)
41335
+ return;
41336
+ }
41337
+ this.#checkedAt = void 0;
41338
+ await this.inspect();
41339
+ this.#checkedAt = this.now();
41340
+ }
41341
+ /** Callbacks, writes and waits can all make an earlier inspection stale. */
41342
+ async step(run) {
41343
+ this.#checkedAt = void 0;
41344
+ try {
41345
+ return await run();
41346
+ } finally {
41347
+ this.#checkedAt = void 0;
41348
+ }
41349
+ }
41350
+ };
41351
+
41209
41352
  // src/common-auth-embedded/setup/enroll.js
41210
41353
  var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
41211
41354
  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.';
@@ -41234,7 +41377,8 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
41234
41377
  throw new Error(VAULT_HOST_CONNECT_REFUSAL2);
41235
41378
  const { name, displayName, requestedGrants, grantFallback, paths: input2 } = plugin.vault.hosts[host];
41236
41379
  const paths = hostEnrollmentPaths2(input2);
41237
- await fence();
41380
+ const guard = typeof fence === "function" ? new SetupProcessGuard(fence, io.now) : fence;
41381
+ await guard.check({ reuse: true });
41238
41382
  const client = await (io.connect ?? connectClaustrumEnrollmentClient2)({
41239
41383
  connectionFile: plugin.vault.connectionFile,
41240
41384
  handshakeTimeoutMs: 2e3
@@ -41255,11 +41399,10 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
41255
41399
  // starts PowerShell.
41256
41400
  client,
41257
41401
  writeTokenFile: async (path5, file) => {
41258
- await fence();
41259
- await writeEnrollmentTokenFile3(path5, file);
41402
+ await guard.check();
41403
+ await guard.step(() => writeEnrollmentTokenFile3(path5, file));
41260
41404
  }
41261
41405
  });
41262
- await fence();
41263
41406
  const initial = await manager.status();
41264
41407
  if (initial.state === "approved") {
41265
41408
  printLine2(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
@@ -41276,7 +41419,8 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
41276
41419
  let reportedCode;
41277
41420
  let failedProposals = 0;
41278
41421
  for (; ; ) {
41279
- const status = await manager.reconcile();
41422
+ await guard.check({ reuse: true });
41423
+ const status = await guard.step(() => manager.reconcile());
41280
41424
  if (status.state === "approved") {
41281
41425
  printLine2(terminal, `Connected ${host} to Claustrum.`);
41282
41426
  const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
@@ -41324,8 +41468,8 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
41324
41468
  const remaining = deadline - now();
41325
41469
  if (remaining <= 0)
41326
41470
  break;
41327
- await wait2(Math.min(pause, remaining));
41328
- await fence();
41471
+ await guard.step(() => wait2(Math.min(pause, remaining)));
41472
+ await guard.check();
41329
41473
  }
41330
41474
  if (printedRequest)
41331
41475
  throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
@@ -41475,6 +41619,8 @@ async function selectSetupHosts(terminal, found) {
41475
41619
  }
41476
41620
 
41477
41621
  // src/common-auth-embedded/setup/register.js
41622
+ import { rename as rename14 } from "node:fs/promises";
41623
+ import { setTimeout as delay3 } from "node:timers/promises";
41478
41624
  import { domainToUnicode } from "node:url";
41479
41625
  import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2, parseTree } from "jsonc-parser";
41480
41626
 
@@ -41684,12 +41830,15 @@ function planOpenCodeRegistration(plugin, generation, io = {}) {
41684
41830
  });
41685
41831
  }
41686
41832
  async function registerOpenCode(writes, beforeWrite) {
41833
+ const guard = typeof beforeWrite === "function" ? new SetupProcessGuard(beforeWrite) : beforeWrite;
41687
41834
  for (const write of writes) {
41688
41835
  if (!write.changed)
41689
41836
  continue;
41690
- await beforeWrite?.();
41691
41837
  await writeHostConfigAtomic(write.path, write.content, {
41692
- beforeRename: beforeWrite
41838
+ // Only the rename publishes host-readable config; recheck on every retry.
41839
+ beforeRename: guard ? () => guard.check({ reuse: true }) : void 0,
41840
+ rename: guard ? (from, to) => guard.step(() => rename14(from, to)) : void 0,
41841
+ wait: guard ? (ms) => guard.step(() => delay3(ms)) : void 0
41693
41842
  });
41694
41843
  }
41695
41844
  }
@@ -41788,7 +41937,11 @@ async function runSetup(plugin, argv = [], io = {}) {
41788
41937
  return { hosts, dryRun: options.dryRun, mode: "local", detection };
41789
41938
  }
41790
41939
  const { env: env3, platform } = setupPaths(io);
41791
- const fence = io.fence ?? createProcessFence(io.runner ?? defaultCommandRunner, { platform });
41940
+ const fence = io.fence ?? createProcessFence(io.runner ?? defaultCommandRunner, {
41941
+ platform,
41942
+ isFile: io.fs?.isFile.bind(io.fs),
41943
+ onProgress: (line) => printLine2(terminal, line)
41944
+ });
41792
41945
  const stopped = async () => {
41793
41946
  try {
41794
41947
  await assertHostsStopped(fence, env3);
@@ -41798,6 +41951,7 @@ async function runSetup(plugin, argv = [], io = {}) {
41798
41951
  throw error;
41799
41952
  }
41800
41953
  };
41954
+ const guard = new SetupProcessGuard(stopped, io.now);
41801
41955
  printLine2(terminal, "Checking that OpenCode and Pi are not running\u2026");
41802
41956
  if (options.dryRun) {
41803
41957
  try {
@@ -41813,16 +41967,17 @@ async function runSetup(plugin, argv = [], io = {}) {
41813
41967
  if (error instanceof ProcessInspectionError)
41814
41968
  printLine2(terminal, error.refusalText);
41815
41969
  }
41816
- } else
41817
- await stopped();
41970
+ } else {
41971
+ await guard.check();
41972
+ }
41818
41973
  if ((options.claustrum || options.enrollOnly) && !detection.claustrum.available)
41819
41974
  throw new Error("Claustrum is not available. Start ck, or omit vault-only flags and use --no-claustrum for local sign-in.");
41820
41975
  let useVault = options.claustrum || options.enrollOnly;
41821
41976
  if (!useVault && !options.login && !options.noClaustrum && !assumeYes && detection.claustrum.available && isInteractive2(terminal)) {
41822
- const choice = await select2(terminal, [
41977
+ const choice = await guard.step(() => select2(terminal, [
41823
41978
  { label: "No", value: false },
41824
41979
  { label: "Yes", value: true }
41825
- ], { message: "Connect these hosts to the Claustrum vault?" });
41980
+ ], { message: "Connect these hosts to the Claustrum vault?" }));
41826
41981
  if (choice === null) {
41827
41982
  printLine2(terminal, "Setup cancelled. Nothing was changed.");
41828
41983
  return { hosts: [], dryRun: options.dryRun, mode: "local", detection };
@@ -41873,13 +42028,14 @@ ${write.content}`);
41873
42028
  const enrollmentAccess = /* @__PURE__ */ new Map();
41874
42029
  try {
41875
42030
  for (const host of hosts) {
41876
- await stopped();
41877
- await plugin.beforeSignIn?.(host, context);
41878
- await stopped();
42031
+ if (plugin.beforeSignIn) {
42032
+ await guard.check({ reuse: true });
42033
+ await guard.step(() => plugin.beforeSignIn?.(host, context));
42034
+ }
41879
42035
  if (useVault) {
41880
42036
  enrollment.set(host, "unknown");
41881
42037
  try {
41882
- const access = await connectSetupHost(plugin, host, io, terminal, stopped);
42038
+ const access = await connectSetupHost(plugin, host, io, terminal, guard);
41883
42039
  if (access)
41884
42040
  enrollmentAccess.set(host, access);
41885
42041
  } catch (error) {
@@ -41888,19 +42044,26 @@ ${write.content}`);
41888
42044
  throw error;
41889
42045
  }
41890
42046
  enrollment.set(host, "enrolled");
41891
- } else
41892
- await plugin.signInLocal(host, context);
41893
- await stopped();
42047
+ } else {
42048
+ await guard.check({ reuse: true });
42049
+ await guard.step(() => plugin.signInLocal(host, context));
42050
+ }
41894
42051
  if (options.enrollOnly)
41895
42052
  continue;
41896
- await plugin.beforeRegister?.(host, mode, context);
41897
- await stopped();
42053
+ if (plugin.beforeRegister) {
42054
+ await guard.check({ reuse: true });
42055
+ await guard.step(() => plugin.beforeRegister?.(host, mode, context));
42056
+ }
41898
42057
  if (host === "opencode")
41899
- await registerOpenCode(writes, stopped);
41900
- else
41901
- await registerPi(plugin, detection.pi.executable, io);
41902
- await stopped();
41903
- await plugin.migrate?.(host, context);
42058
+ await registerOpenCode(writes, guard);
42059
+ else {
42060
+ await guard.check({ reuse: true });
42061
+ await guard.step(() => registerPi(plugin, detection.pi.executable, io));
42062
+ }
42063
+ if (plugin.migrate) {
42064
+ await guard.check({ reuse: true });
42065
+ await guard.step(() => plugin.migrate?.(host, context));
42066
+ }
41904
42067
  }
41905
42068
  } catch (error) {
41906
42069
  if (enrollment.size === 0)
@@ -43563,7 +43726,7 @@ function isSessionId(value) {
43563
43726
  // src/common-auth-embedded/rpc/port-file.js
43564
43727
  init_private_files2();
43565
43728
  import { createHash as createHash15, randomUUID as randomUUID19 } from "node:crypto";
43566
- import { chmod as chmod7, mkdir as mkdir17, open as open12, readdir as readdir6, rename as rename14, rmdir as rmdir3, stat as stat17, unlink as unlink15 } from "node:fs/promises";
43729
+ import { chmod as chmod7, mkdir as mkdir17, open as open12, readdir as readdir6, rename as rename15, rmdir as rmdir3, stat as stat17, unlink as unlink15 } from "node:fs/promises";
43567
43730
  import { uptime as uptime2 } from "node:os";
43568
43731
  import { join as join30, resolve as resolve26 } from "node:path";
43569
43732
  function staleBefore(clock2) {
@@ -43645,7 +43808,7 @@ async function writePortFile(dir, entry, options = {}) {
43645
43808
  await handle.chmod(384);
43646
43809
  await handle.close();
43647
43810
  handle = void 0;
43648
- await rename14(tmp, target);
43811
+ await rename15(tmp, target);
43649
43812
  created = false;
43650
43813
  } finally {
43651
43814
  await handle?.close().catch(() => {
@@ -44920,7 +45083,7 @@ import { join as join33, resolve as resolve28 } from "node:path";
44920
45083
  // ../core/dist/common-auth-embedded/tui-prefs/watcher.js
44921
45084
  init_canonical_file_path();
44922
45085
  init_private_files();
44923
- import { lstatSync, readFileSync as readFileSync8, readlinkSync, realpathSync as realpathSync5, statSync as statSync7, watch } from "node:fs";
45086
+ import { lstatSync, readFileSync as readFileSync8, readlinkSync, realpathSync as realpathSync5, statSync as statSync8, watch } from "node:fs";
44924
45087
  import { readFile as readFile17, stat as stat18 } from "node:fs/promises";
44925
45088
  import { basename as basename10, dirname as dirname24, join as join32, resolve as resolve27 } from "node:path";
44926
45089
  import { clearTimeout as clearTimeout2, setTimeout as setTimeout2 } from "node:timers";
@@ -44964,7 +45127,7 @@ function watchFile(file, onChange, options, settings) {
44964
45127
  let lastSeen = null;
44965
45128
  if (settings || !windowsPrivateFiles)
44966
45129
  try {
44967
- const metadata = identity3((options.fs?.statSync ?? statSync7)(path5), settings);
45130
+ const metadata = identity3((options.fs?.statSync ?? statSync8)(path5), settings);
44968
45131
  lastSeen = (options.fs?.readFileSync ?? ((file2) => readFileSync8(file2, "utf8")))(path5);
44969
45132
  lastMetadata = metadata;
44970
45133
  } catch {
@@ -46308,7 +46471,7 @@ async function moveSettingsOnce(options) {
46308
46471
  }
46309
46472
 
46310
46473
  // ../core/dist/common-auth-embedded/settings/paths.js
46311
- import { posix as posix2, win32 as win322 } from "node:path";
46474
+ import { posix as posix2, win32 as win324 } from "node:path";
46312
46475
  function isAbsoluteForPlatform(path5, platform) {
46313
46476
  if (platform !== "win32")
46314
46477
  return path5.startsWith("/");
@@ -46319,7 +46482,7 @@ function isAbsoluteForPlatform(path5, platform) {
46319
46482
  return /^[\\/]{2}[^\\/]+[\\/][^\\/]+/.test(path5);
46320
46483
  }
46321
46484
  function cortexkitConfigDir({ env: env3, platform, homedir: homedir17 }) {
46322
- const paths = platform === "win32" ? win322 : posix2;
46485
+ const paths = platform === "win32" ? win324 : posix2;
46323
46486
  const absolute = (value) => value !== void 0 && isAbsoluteForPlatform(value, platform);
46324
46487
  let base;
46325
46488
  if (absolute(env3.XDG_CONFIG_HOME)) {
@@ -46342,7 +46505,7 @@ function settingsFilePath({ plugin, override, ...options }) {
46342
46505
  if (override && isAbsoluteForPlatform(override, options.platform)) {
46343
46506
  return override;
46344
46507
  }
46345
- const paths = options.platform === "win32" ? win322 : posix2;
46508
+ const paths = options.platform === "win32" ? win324 : posix2;
46346
46509
  return paths.join(cortexkitConfigDir(options), `${plugin}.jsonc`);
46347
46510
  }
46348
46511
 
@@ -47046,9 +47209,9 @@ init_version_fence();
47046
47209
 
47047
47210
  // src/settings/location.ts
47048
47211
  import { realpath as realpath6 } from "node:fs/promises";
47049
- import { posix as posix3, win32 as win323 } from "node:path";
47212
+ import { posix as posix3, win32 as win325 } from "node:path";
47050
47213
  async function folderIdentity(folder, platform) {
47051
- const paths = platform === "win32" ? win323 : posix3;
47214
+ const paths = platform === "win32" ? win325 : posix3;
47052
47215
  try {
47053
47216
  return await realpath6(folder);
47054
47217
  } catch {
@@ -47057,7 +47220,7 @@ async function folderIdentity(folder, platform) {
47057
47220
  }
47058
47221
  async function resolveSettingsLocation(options) {
47059
47222
  const { env: env3, platform, homedir: homedir17 } = options;
47060
- const paths = platform === "win32" ? win323 : posix3;
47223
+ const paths = platform === "win32" ? win325 : posix3;
47061
47224
  const override = env3.OPENCODE_ANTIGRAVITY_AUTH_SETTINGS_FILE;
47062
47225
  const file = settingsFilePath({
47063
47226
  plugin: "antigravity-auth",
@@ -47434,12 +47597,12 @@ function createSettingsRuntime(options) {
47434
47597
  void enqueue(refreshAll);
47435
47598
  });
47436
47599
  };
47437
- const scheduleAttempt = (delay3) => {
47600
+ const scheduleAttempt = (delay4) => {
47438
47601
  if (disposed) return;
47439
47602
  retryTimer = setTimeout(() => {
47440
47603
  retryTimer = void 0;
47441
47604
  void enqueue(attemptMove);
47442
- }, delay3);
47605
+ }, delay4);
47443
47606
  retryTimer.unref?.();
47444
47607
  };
47445
47608
  const attemptMove = async () => {
@@ -58433,14 +58596,14 @@ var BackgroundVaultQuotaRefresh = class {
58433
58596
  this.abortTick();
58434
58597
  await this.inFlight;
58435
58598
  }
58436
- schedule(delay3, intervalWait = null) {
58599
+ schedule(delay4, intervalWait = null) {
58437
58600
  if (this.disposed || !this.started) return;
58438
58601
  this.intervalWait = intervalWait;
58439
58602
  this.timer = setTimeout(() => {
58440
58603
  this.timer = null;
58441
58604
  this.intervalWait = null;
58442
58605
  void this.tick();
58443
- }, delay3);
58606
+ }, delay4);
58444
58607
  this.timer.unref?.();
58445
58608
  }
58446
58609
  /** One serialized tick; also used by deterministic composition tests. */
@@ -59377,6 +59540,7 @@ function routingHandle(sessionId) {
59377
59540
  var CACHE_WARM_STOP_REASONS = [
59378
59541
  "cost-cap",
59379
59542
  "count-cap",
59543
+ "deadline-missed",
59380
59544
  "outside-hours",
59381
59545
  "session-ended",
59382
59546
  "unsupported"
@@ -60803,11 +60967,23 @@ function createRequestExecutor(deps) {
60803
60967
  };
60804
60968
  }
60805
60969
  const sender = options.transport ?? defaultTransport2;
60806
- const transport = (url, sendInit, sendOptions) => deadline.open(() => {
60970
+ const transport = (url, sendInit, sendOptions, onSenderRejection) => deadline.open(() => {
60807
60971
  waits.resumed();
60808
- return sender(url, sendInit, {
60972
+ const optionsWithSignal = {
60809
60973
  ...sendOptions,
60810
60974
  signal: deadline.signal
60975
+ };
60976
+ if (!onSenderRejection) return sender(url, sendInit, optionsWithSignal);
60977
+ let pending;
60978
+ try {
60979
+ pending = sender(url, sendInit, optionsWithSignal);
60980
+ } catch (error) {
60981
+ onSenderRejection(error);
60982
+ throw error;
60983
+ }
60984
+ return pending.catch((error) => {
60985
+ onSenderRejection(error);
60986
+ throw error;
60811
60987
  });
60812
60988
  });
60813
60989
  const requestSessionIdentity = options.session ?? extractOpenCodeSessionIdentity(init?.headers);
@@ -60856,8 +61032,38 @@ function createRequestExecutor(deps) {
60856
61032
  `[Cache] ${label} model=${cachedStats.model} read=${cachedStats.read} total=${cachedStats.total} hitRate=${cachedStats.hitRate}%`
60857
61033
  );
60858
61034
  }
60859
- let lastFailure = null;
61035
+ let retainedMainAttemptFailure = null;
60860
61036
  let lastError = null;
61037
+ const retainMainTransportFailure = (error) => {
61038
+ retainedMainAttemptFailure = {
61039
+ kind: "transport",
61040
+ error: error instanceof Error ? error : new Error(String(error))
61041
+ };
61042
+ };
61043
+ const terminalMainAttemptFailure = async (fallbackMessage) => {
61044
+ const failure2 = retainedMainAttemptFailure;
61045
+ if (failure2?.kind === "http") {
61046
+ const context = failure2.context;
61047
+ return wire.transformResponse(
61048
+ context.response,
61049
+ context.streaming,
61050
+ context.debugContext,
61051
+ context.requestedModel,
61052
+ context.projectId,
61053
+ context.endpoint,
61054
+ context.effectiveModel,
61055
+ context.sessionId,
61056
+ context.toolDebugMissing,
61057
+ context.toolDebugSummary,
61058
+ debugLines,
61059
+ context.dumpContext
61060
+ );
61061
+ }
61062
+ throw terminalFetchError(
61063
+ lastError ?? (failure2?.kind === "transport" ? failure2.error : null),
61064
+ fallbackMessage
61065
+ );
61066
+ };
60861
61067
  const abortSignal = init?.signal ?? void 0;
60862
61068
  const routingSleep = (ms, reason, attempt) => waits.sleep(
60863
61069
  ms,
@@ -61474,7 +61680,7 @@ function createRequestExecutor(deps) {
61474
61680
  }
61475
61681
  }
61476
61682
  const selected = account;
61477
- const sendPhysical = async (url, sendInit, admission, sendModel, requestKind) => {
61683
+ const sendPhysical = async (url, sendInit, admission, sendModel, requestKind, onMainTransportFailure) => {
61478
61684
  const source = credentials.domain === "local" ? "local" : hasVaultHost2() ? "hosted" : "vault";
61479
61685
  const message = `request-send source=${source} model=${sendModel} account=Account ${account.index + 1}`;
61480
61686
  if (source === "local") log18.info(message);
@@ -61490,10 +61696,15 @@ function createRequestExecutor(deps) {
61490
61696
  abortSignal
61491
61697
  ) : void 0;
61492
61698
  try {
61493
- const response = await transport(url, sendInit, {
61494
- signal: abortSignal,
61495
- onDebug: pushDebug
61496
- });
61699
+ const response = await transport(
61700
+ url,
61701
+ sendInit,
61702
+ {
61703
+ signal: abortSignal,
61704
+ onDebug: pushDebug
61705
+ },
61706
+ onMainTransportFailure
61707
+ );
61497
61708
  return billing?.observe(response) ?? response;
61498
61709
  } catch (error) {
61499
61710
  billing?.end(false);
@@ -61755,6 +61966,12 @@ function createRequestExecutor(deps) {
61755
61966
  toolDebugSummary: prepared.toolDebugSummary,
61756
61967
  dumpContext
61757
61968
  });
61969
+ const retainHttpFailure = (failureResponse) => {
61970
+ retainedMainAttemptFailure = {
61971
+ kind: "http",
61972
+ context: createFailureContext(failureResponse)
61973
+ };
61974
+ };
61758
61975
  await runThinkingWarmup(prepared, sendProjectId);
61759
61976
  await runCacheWarmupProbe(prepared);
61760
61977
  if (config.request_jitter_max_ms > 0) {
@@ -61787,7 +62004,8 @@ function createRequestExecutor(deps) {
61787
62004
  prepared.init,
61788
62005
  sendAdmission,
61789
62006
  prepared.effectiveModel ?? model ?? "unknown",
61790
- kind ?? "primary"
62007
+ kind ?? "primary",
62008
+ retainMainTransportFailure
61791
62009
  );
61792
62010
  if (response.ok) deadline.acceptHeaders();
61793
62011
  apiRequestCount++;
@@ -61915,13 +62133,35 @@ function createRequestExecutor(deps) {
61915
62133
  "UNKNOWN",
61916
62134
  delayMs
61917
62135
  );
62136
+ const now = Date.now();
62137
+ const at = account.cachedQuotaUpdatedAt;
62138
+ const sameQuotaIdentity = credentials.domain === "vault" || account.cachedQuotaAccountId === quotaAccountIdentity(
62139
+ parseRefreshParts(
62140
+ credentials.toAuthDetails(account).refresh
62141
+ ).refreshToken
62142
+ );
62143
+ const emptyUntil = sameQuotaIdentity && at !== void 0 && now - at <= softQuotaCacheTtlMs ? quotaExhaustedUntil(account, family, model, now) : 0;
62144
+ const quotaKey3 = getQuotaKey(family, model);
62145
+ const resets = account.rateLimitResetTimes;
62146
+ if (emptyUntil > (resets[quotaKey3] ?? 0))
62147
+ accountManager.markRateLimited(
62148
+ account,
62149
+ emptyUntil - now,
62150
+ family,
62151
+ model
62152
+ );
61918
62153
  accountManager.requestSaveToDisk();
62154
+ if ((resets[quotaKey3] ?? 0) > now + delayMs) {
62155
+ switchedForUnconfirmed = true;
62156
+ shouldSwitchAccount = true;
62157
+ break;
62158
+ }
61919
62159
  if (unconfirmedRetries >= MAX_UNCONFIRMED_RATE_LIMIT_RETRIES)
61920
62160
  return terminal();
61921
62161
  unconfirmedRetries++;
61922
62162
  const ready = accountManager.getAccounts().some((entry) => {
61923
- const resets = entry.rateLimitResetTimes;
61924
- 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();
62163
+ const resets2 = entry.rateLimitResetTimes;
62164
+ 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();
61925
62165
  });
61926
62166
  if (ready) {
61927
62167
  switchedForUnconfirmed = true;
@@ -61929,6 +62169,11 @@ function createRequestExecutor(deps) {
61929
62169
  break;
61930
62170
  }
61931
62171
  await routingSleep(delayMs, "rate_limited", unconfirmedRetries);
62172
+ if ((resets[quotaKey3] ?? 0) > now + delayMs) {
62173
+ switchedForUnconfirmed = true;
62174
+ shouldSwitchAccount = true;
62175
+ break;
62176
+ }
61932
62177
  i -= 1;
61933
62178
  continue;
61934
62179
  }
@@ -61958,7 +62203,7 @@ function createRequestExecutor(deps) {
61958
62203
  pushDebug(
61959
62204
  `Total capacity retries (${MAX_TOTAL_CAPACITY_RETRIES}) exhausted, switching account`
61960
62205
  );
61961
- lastFailure = createFailureContext(response);
62206
+ retainHttpFailure(response);
61962
62207
  shouldSwitchAccount = true;
61963
62208
  break;
61964
62209
  }
@@ -62108,7 +62353,7 @@ function createRequestExecutor(deps) {
62108
62353
  backoff.attempt
62109
62354
  );
62110
62355
  }
62111
- lastFailure = createFailureContext(response);
62356
+ retainHttpFailure(response);
62112
62357
  shouldSwitchAccount = true;
62113
62358
  break;
62114
62359
  }
@@ -62170,7 +62415,7 @@ function createRequestExecutor(deps) {
62170
62415
  `account-ineligible: disabled account ${account.index}`
62171
62416
  );
62172
62417
  trackers.health.recordFailure(account.index);
62173
- lastFailure = createFailureContext(response);
62418
+ retainHttpFailure(response);
62174
62419
  shouldSwitchAccount = true;
62175
62420
  break;
62176
62421
  }
@@ -62205,7 +62450,7 @@ function createRequestExecutor(deps) {
62205
62450
  `verification-required: disabled account ${account.index}`
62206
62451
  );
62207
62452
  trackers.health.recordFailure(account.index);
62208
- lastFailure = createFailureContext(response);
62453
+ retainHttpFailure(response);
62209
62454
  shouldSwitchAccount = true;
62210
62455
  break;
62211
62456
  }
@@ -62213,7 +62458,7 @@ function createRequestExecutor(deps) {
62213
62458
  const shouldRetryEndpoint = response.status === 404 || response.status >= 500;
62214
62459
  if (shouldRetryEndpoint && i < ANTIGRAVITY_ENDPOINT_FALLBACKS.length - 1) {
62215
62460
  await logResponseBody2(debugContext, response, response.status);
62216
- lastFailure = createFailureContext(response);
62461
+ retainHttpFailure(response);
62217
62462
  continue;
62218
62463
  }
62219
62464
  if (response.ok) {
@@ -62484,68 +62729,16 @@ function createRequestExecutor(deps) {
62484
62729
  pushDebug(
62485
62730
  `account-switch-cap: exceeded max_account_switches=${maxAccountSwitches}, giving up`
62486
62731
  );
62487
- if (lastFailure) {
62488
- return wire.transformResponse(
62489
- lastFailure.response,
62490
- lastFailure.streaming,
62491
- lastFailure.debugContext,
62492
- lastFailure.requestedModel,
62493
- lastFailure.projectId,
62494
- lastFailure.endpoint,
62495
- lastFailure.effectiveModel,
62496
- lastFailure.sessionId,
62497
- lastFailure.toolDebugMissing,
62498
- lastFailure.toolDebugSummary,
62499
- debugLines,
62500
- lastFailure.dumpContext
62501
- );
62502
- }
62503
- throw terminalFetchError(
62504
- lastError,
62732
+ return terminalMainAttemptFailure(
62505
62733
  `Exceeded max account switches (${maxAccountSwitches}). All accounts rate-limited.`
62506
62734
  );
62507
62735
  }
62508
62736
  if (accountCount <= 1) {
62509
- if (lastFailure) {
62510
- return wire.transformResponse(
62511
- lastFailure.response,
62512
- lastFailure.streaming,
62513
- lastFailure.debugContext,
62514
- lastFailure.requestedModel,
62515
- lastFailure.projectId,
62516
- lastFailure.endpoint,
62517
- lastFailure.effectiveModel,
62518
- lastFailure.sessionId,
62519
- lastFailure.toolDebugMissing,
62520
- lastFailure.toolDebugSummary,
62521
- debugLines,
62522
- lastFailure.dumpContext
62523
- );
62524
- }
62525
- throw terminalFetchError(
62526
- lastError,
62527
- "All Antigravity endpoints failed"
62528
- );
62737
+ return terminalMainAttemptFailure("All Antigravity endpoints failed");
62529
62738
  }
62530
62739
  continue;
62531
62740
  }
62532
- if (lastFailure) {
62533
- return wire.transformResponse(
62534
- lastFailure.response,
62535
- lastFailure.streaming,
62536
- lastFailure.debugContext,
62537
- lastFailure.requestedModel,
62538
- lastFailure.projectId,
62539
- lastFailure.endpoint,
62540
- lastFailure.effectiveModel,
62541
- lastFailure.sessionId,
62542
- lastFailure.toolDebugMissing,
62543
- lastFailure.toolDebugSummary,
62544
- debugLines,
62545
- lastFailure.dumpContext
62546
- );
62547
- }
62548
- throw terminalFetchError(lastError, "All Antigravity accounts failed");
62741
+ return terminalMainAttemptFailure("All Antigravity accounts failed");
62549
62742
  }
62550
62743
  }
62551
62744
  function drain() {