@cortexkit/opencode-antigravity-auth 3.0.3 → 3.0.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +7 -7
  2. package/dist/cli.js +1722 -484
  3. package/dist/cli.js.map +4 -4
  4. package/dist/cli.meta.json +440 -120
  5. package/dist/index.js +2157 -803
  6. package/dist/index.js.map +4 -4
  7. package/dist/index.meta.json +476 -141
  8. package/dist/server.js +2188 -834
  9. package/dist/server.js.map +4 -4
  10. package/dist/server.meta.json +1 -1
  11. package/dist/src/common-auth-embedded/claustrum/enrollment.d.ts +3 -2
  12. package/dist/src/common-auth-embedded/claustrum/enrollment.js +84 -42
  13. package/dist/src/common-auth-embedded/claustrum/roster.js +2 -2
  14. package/dist/src/common-auth-embedded/fs/atomic-write.d.ts +5 -0
  15. package/dist/src/common-auth-embedded/fs/atomic-write.js +21 -0
  16. package/dist/src/common-auth-embedded/fs/index.d.ts +2 -0
  17. package/dist/src/common-auth-embedded/fs/index.js +1 -0
  18. package/dist/src/common-auth-embedded/fs/private-files.d.ts +66 -0
  19. package/dist/src/common-auth-embedded/fs/private-files.js +302 -0
  20. package/dist/src/common-auth-embedded/fs/refresh-file-lock.d.ts +1 -1
  21. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +254 -37
  22. package/dist/src/common-auth-embedded/fs/with-lock.d.ts +3 -0
  23. package/dist/src/common-auth-embedded/fs/with-lock.js +4 -0
  24. package/dist/src/common-auth-embedded/logger/engine.d.ts +6 -8
  25. package/dist/src/common-auth-embedded/logger/engine.js +126 -11
  26. package/dist/src/common-auth-embedded/pi-slot/slot.d.ts +2 -0
  27. package/dist/src/common-auth-embedded/pi-slot/slot.js +34 -6
  28. package/dist/src/common-auth-embedded/rpc/port-file.js +30 -8
  29. package/dist/src/common-auth-embedded/rpc/rpc-client.js +15 -1
  30. package/dist/src/common-auth-embedded/rpc/rpc-server.js +8 -3
  31. package/dist/src/common-auth-embedded/source-output.json +92 -76
  32. package/dist/src/common-auth-embedded/store/mutate.js +2 -2
  33. package/dist/src/common-auth-embedded/store/pool.d.ts +1 -0
  34. package/dist/src/common-auth-embedded/store/pool.js +3 -0
  35. package/dist/src/common-auth-embedded/store/refresh-lock.d.ts +4 -0
  36. package/dist/src/common-auth-embedded/store/refresh-lock.js +5 -0
  37. package/dist/src/ga/server/index.d.ts +3 -2
  38. package/dist/src/ga/server/index.d.ts.map +1 -1
  39. package/dist/src/ga/server/index.js +8 -5
  40. package/dist/src/ga/server/index.js.map +1 -1
  41. package/dist/src/plugin/request.d.ts.map +1 -1
  42. package/dist/src/plugin/request.js +8 -14
  43. package/dist/src/plugin/request.js.map +1 -1
  44. package/dist/src/plugin/vault-custody.d.ts +6 -0
  45. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  46. package/dist/src/plugin/vault-custody.js +81 -2
  47. package/dist/src/plugin/vault-custody.js.map +1 -1
  48. package/dist/tui-build-map.json +29 -13
  49. package/dist/tui-ga-build-map.json +1 -1
  50. package/dist/types/src/common-auth-embedded/fs/refresh-file-lock.d.ts +1 -1
  51. package/dist/types/src/common-auth-embedded/logger/engine.d.ts +6 -8
  52. package/dist/types/src/common-auth-embedded/store/pool.d.ts +1 -0
  53. package/dist/types/src/common-auth-embedded/store/refresh-lock.d.ts +4 -0
  54. package/dist/types/src/ga/server/index.d.ts +3 -2
  55. package/dist/types/src/ga/server/index.d.ts.map +1 -1
  56. package/dist/types/src/plugin/request.d.ts.map +1 -1
  57. package/dist/types/src/plugin/vault-custody.d.ts +6 -0
  58. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  59. package/package.json +5 -4
  60. package/src/common-auth-embedded/claustrum/enrollment.d.ts +3 -2
  61. package/src/common-auth-embedded/claustrum/enrollment.js +84 -42
  62. package/src/common-auth-embedded/claustrum/roster.js +2 -2
  63. package/src/common-auth-embedded/fs/atomic-write.d.ts +5 -0
  64. package/src/common-auth-embedded/fs/atomic-write.js +21 -0
  65. package/src/common-auth-embedded/fs/index.d.ts +2 -0
  66. package/src/common-auth-embedded/fs/index.js +1 -0
  67. package/src/common-auth-embedded/fs/private-files.d.ts +66 -0
  68. package/src/common-auth-embedded/fs/private-files.js +302 -0
  69. package/src/common-auth-embedded/fs/refresh-file-lock.d.ts +1 -1
  70. package/src/common-auth-embedded/fs/refresh-file-lock.js +254 -37
  71. package/src/common-auth-embedded/fs/with-lock.d.ts +3 -0
  72. package/src/common-auth-embedded/fs/with-lock.js +4 -0
  73. package/src/common-auth-embedded/logger/engine.d.ts +6 -8
  74. package/src/common-auth-embedded/logger/engine.js +126 -11
  75. package/src/common-auth-embedded/pi-slot/slot.d.ts +2 -0
  76. package/src/common-auth-embedded/pi-slot/slot.js +34 -6
  77. package/src/common-auth-embedded/rpc/port-file.js +30 -8
  78. package/src/common-auth-embedded/rpc/rpc-client.js +15 -1
  79. package/src/common-auth-embedded/rpc/rpc-server.js +8 -3
  80. package/src/common-auth-embedded/source-output.json +92 -76
  81. package/src/common-auth-embedded/store/mutate.js +2 -2
  82. package/src/common-auth-embedded/store/pool.d.ts +1 -0
  83. package/src/common-auth-embedded/store/pool.js +3 -0
  84. package/src/common-auth-embedded/store/refresh-lock.d.ts +4 -0
  85. package/src/common-auth-embedded/store/refresh-lock.js +5 -0
  86. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +302 -0
  87. package/src/tui-compiled/common-auth-embedded/logger/engine.js +126 -11
  88. package/src/tui-compiled/common-auth-embedded/rpc/port-file.js +30 -8
  89. package/src/tui-compiled/common-auth-embedded/rpc/rpc-client.js +15 -1
  90. package/src/tui-raw/common-auth-embedded/fs/private-files.js +302 -0
  91. package/src/tui-raw/common-auth-embedded/logger/engine.js +126 -11
  92. package/src/tui-raw/common-auth-embedded/rpc/port-file.js +30 -8
  93. package/src/tui-raw/common-auth-embedded/rpc/rpc-client.js +15 -1
package/dist/cli.js CHANGED
@@ -540,16 +540,293 @@ var init_identity = __esm({
540
540
  }
541
541
  });
542
542
 
543
- // ../core/dist/common-auth-embedded/fs/atomic-write.js
543
+ // ../core/dist/common-auth-embedded/fs/private-files.js
544
544
  import { randomUUID as randomUUID5 } from "node:crypto";
545
- import { mkdir as mkdir6, open as open3, rename as rename3, rm as rm3 } from "node:fs/promises";
546
- import { dirname as dirname5 } from "node:path";
545
+ import { lstat as lstat2, readFile as readFile4, rename as rename3, unlink as unlink5 } from "node:fs/promises";
546
+ import { dirname as dirname5, resolve as resolve2 } from "node:path";
547
+ function ioCode(detail) {
548
+ if (detail?.reason === "io-error") {
549
+ if (detail.win32Code === 2 || detail.win32Code === 3)
550
+ return "ENOENT";
551
+ if (detail.win32Code === 80 || detail.win32Code === 183)
552
+ return "EEXIST";
553
+ }
554
+ return detail?.code ?? "ERR_PRIVATE_FILE";
555
+ }
556
+ function loadBackend() {
557
+ backend ??= import("@cortexkit/private-files");
558
+ return backend;
559
+ }
560
+ async function privateOperation(path2, stage, operation) {
561
+ try {
562
+ return await operation();
563
+ } catch (cause) {
564
+ if (cause instanceof PrivateFileError)
565
+ throw cause;
566
+ throw new PrivateFileError(path2, stage, cause);
567
+ }
568
+ }
569
+ async function verifySafeDirectory(path2, options) {
570
+ path2 = resolve2(path2);
571
+ options ??= safeParentOptionsForTest;
572
+ await privateOperation(path2, "safe-parent", async () => {
573
+ const result = await (await loadBackend()).verifySafeParent(path2, options);
574
+ if (result.ok === false) {
575
+ if (result.reason === "io-error" || result.reason === "wrong-kind")
576
+ await lstat2(path2);
577
+ throw new PrivateFileError(result.level ?? result.path, "safe-parent", {
578
+ ...result,
579
+ code: "ERR_PRIVATE_FILES_SECURITY"
580
+ });
581
+ }
582
+ });
583
+ }
584
+ async function verifyPrivate(path2, kind, migrate = false) {
585
+ path2 = resolve2(path2);
586
+ if (kind === "directory")
587
+ return verifySafeDirectory(path2);
588
+ await privateOperation(path2, "verify", async () => {
589
+ const api = await loadBackend();
590
+ const result = await api.verifyOwnerOnly(path2);
591
+ let repaired = false;
592
+ if (!result.ok) {
593
+ const { reason } = result.refusal;
594
+ if (reason === "io-error")
595
+ await api.verifyPrivatePath(path2, kind);
596
+ if (migrate && [
597
+ api.EXTRA_ACE,
598
+ api.NOT_PROTECTED,
599
+ api.NULL_DACL,
600
+ api.EMPTY_DACL
601
+ ].includes(reason)) {
602
+ await verifySafeDirectory(dirname5(path2));
603
+ await api.securePrivatePath(path2, kind);
604
+ repaired = true;
605
+ } else {
606
+ throw Object.assign(new Error("Owner-only verification refused"), {
607
+ reason,
608
+ code: "ERR_PRIVATE_FILES_SECURITY"
609
+ });
610
+ }
611
+ }
612
+ await api.verifyPrivatePath(path2, kind);
613
+ if (repaired && !migrationNotices.has(path2)) {
614
+ migrationNotices.add(path2);
615
+ process.emitWarning(`Private permissions tightened: ${path2}. This object may have been readable before; rotate credentials if needed.`, "PrivateFileMigration");
616
+ }
617
+ });
618
+ }
619
+ async function ensurePrivateDirectory(path2, _migrate = false, options) {
620
+ path2 = resolve2(path2);
621
+ await privateOperation(path2, "directory", async () => {
622
+ const api = await loadBackend();
623
+ try {
624
+ await lstat2(path2);
625
+ return await verifySafeDirectory(path2, options);
626
+ } catch (error) {
627
+ if (ioCode(error) !== "ENOENT")
628
+ throw error;
629
+ }
630
+ const parent = dirname5(path2);
631
+ if (parent === path2)
632
+ throw Object.assign(new Error("Missing root"), { code: "ENOENT" });
633
+ await ensurePrivateDirectory(parent, false, options);
634
+ try {
635
+ await api.createOwnerOnly(path2, { kind: "dir" });
636
+ } catch (error) {
637
+ if (ioCode(error) !== "EEXIST")
638
+ throw error;
639
+ }
640
+ await verifySafeDirectory(path2, options);
641
+ });
642
+ }
643
+ async function readPrivateText(path2, migrate = false) {
644
+ if (!windowsPrivateFiles)
645
+ return readFile4(path2, "utf8");
646
+ return (await readPrivateBuffer(path2, migrate)).toString("utf8");
647
+ }
648
+ async function readPrivateBuffer(path2, migrate = false) {
649
+ if (!windowsPrivateFiles)
650
+ return readFile4(path2);
651
+ path2 = resolve2(path2);
652
+ if (migrate) {
653
+ await verifySafeDirectory(dirname5(path2));
654
+ await verifyPrivate(path2, "file", true);
655
+ }
656
+ return privateOperation(path2, "read", async () => (await loadBackend()).readOwnerOnly(path2));
657
+ }
658
+ async function createPrivateBytes(path2, bytes) {
659
+ await verifySafeDirectory(dirname5(resolve2(path2)));
660
+ await privateOperation(path2, "create", async () => {
661
+ await (await loadBackend()).createPrivateFile(resolve2(path2), bytes);
662
+ });
663
+ }
664
+ async function createPrivateDirectoryExclusive(path2) {
665
+ await verifySafeDirectory(dirname5(resolve2(path2)));
666
+ await privateOperation(path2, "directory-create", async () => {
667
+ await (await loadBackend()).createOwnerOnly(resolve2(path2), { kind: "dir" });
668
+ });
669
+ }
670
+ async function replaceWindowsFile(from, to, options = {}) {
671
+ from = resolve2(from);
672
+ to = resolve2(to);
673
+ const now = options.now ?? (() => performance.now());
674
+ const start = now();
675
+ const deadline = Math.min(start + 500, options.deadline ?? Infinity);
676
+ const delays = [0, 10, 20, 40, 80, 100];
677
+ let original;
678
+ let attempts = 0;
679
+ for (const delay of delays) {
680
+ if (now() >= deadline)
681
+ break;
682
+ if (delay)
683
+ await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay, Math.max(0, deadline - now())));
684
+ if (now() >= deadline)
685
+ break;
686
+ await options.beforeRename?.();
687
+ if (now() >= deadline)
688
+ break;
689
+ attempts++;
690
+ try {
691
+ await (options.rename ?? rename3)(from, to);
692
+ return { attempts, elapsedMs: now() - start };
693
+ } catch (error2) {
694
+ original ??= error2;
695
+ const detail = error2;
696
+ const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
697
+ if (!candidate)
698
+ break;
699
+ }
700
+ }
701
+ const error = new PrivateFileError(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
702
+ code: "ETIMEDOUT"
703
+ }));
704
+ error.attempts = attempts;
705
+ error.elapsedMs = now() - start;
706
+ throw error;
707
+ }
708
+ async function writePrivateAtomic(path2, bytes, options = {}) {
709
+ path2 = resolve2(path2);
710
+ await ensurePrivateDirectory(dirname5(path2));
711
+ try {
712
+ await verifyPrivate(path2, "file", true);
713
+ } catch (error) {
714
+ if (error.code !== "ENOENT")
715
+ throw error;
716
+ }
717
+ const stage = resolve2(options.stagePath ?? `${path2}.${randomUUID5()}.tmp`);
718
+ if (dirname5(stage) !== dirname5(path2))
719
+ throw new PrivateFileError(path2, "stage-directory", { code: "EXDEV" });
720
+ let created = false;
721
+ let published = false;
722
+ let outcome = { attempts: 0, elapsedMs: 0 };
723
+ let stageName = "stage-create";
724
+ const reportOutcome = (error) => {
725
+ try {
726
+ options.onOutcome?.({
727
+ path: path2,
728
+ stage: error?.stage ?? "published",
729
+ published,
730
+ fileDurable: published,
731
+ durabilityConfirmed: false,
732
+ attempts: error?.attempts ?? outcome.attempts,
733
+ elapsedMs: error?.elapsedMs ?? outcome.elapsedMs,
734
+ ...error && { code: error.code, win32Code: error.win32Code }
735
+ });
736
+ } catch {
737
+ }
738
+ };
739
+ try {
740
+ await createPrivateBytes(stage, bytes);
741
+ created = true;
742
+ stageName = "before-rename";
743
+ outcome = await replaceWindowsFile(stage, path2, options);
744
+ created = false;
745
+ published = true;
746
+ stageName = "published-callback";
747
+ options.onRenamed?.();
748
+ stageName = "published-verify";
749
+ await verifyPrivate(path2, "file");
750
+ if (options.durable && options.durability !== "file-only-on-windows")
751
+ throw new PrivateFileError(path2, "directory-sync-unsupported", {
752
+ code: "ENOTSUP"
753
+ });
754
+ reportOutcome();
755
+ } catch (cause) {
756
+ const error = cause instanceof PrivateFileError ? cause : new PrivateFileError(path2, stageName, cause);
757
+ error.published = published;
758
+ error.fileDurable = published;
759
+ if (published)
760
+ Object.assign(error, outcome);
761
+ if (created) {
762
+ try {
763
+ await unlink5(stage);
764
+ } catch {
765
+ error.orphanPath = stage;
766
+ }
767
+ created = false;
768
+ }
769
+ reportOutcome(error);
770
+ throw error;
771
+ } finally {
772
+ if (created)
773
+ await unlink5(stage).catch(() => {
774
+ });
775
+ }
776
+ }
777
+ var windowsPrivateFiles, migrationNotices, backend, PrivateFileError, safeParentOptionsForTest;
778
+ var init_private_files = __esm({
779
+ "../core/dist/common-auth-embedded/fs/private-files.js"() {
780
+ "use strict";
781
+ windowsPrivateFiles = process.platform === "win32";
782
+ migrationNotices = /* @__PURE__ */ new Set();
783
+ PrivateFileError = class extends Error {
784
+ path;
785
+ stage;
786
+ code;
787
+ win32Code;
788
+ reason;
789
+ published = false;
790
+ durabilityConfirmed = false;
791
+ fileDurable = false;
792
+ attempts = 0;
793
+ elapsedMs = 0;
794
+ orphanPath;
795
+ constructor(path2, stage, cause) {
796
+ const detail = cause;
797
+ super(`Private file refused at ${stage}: ${path2} (${detail?.reason ?? detail?.code ?? "io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`, { cause });
798
+ this.path = path2;
799
+ this.stage = stage;
800
+ this.name = "PrivateFileError";
801
+ this.code = ioCode(detail);
802
+ this.win32Code = detail?.win32Code;
803
+ this.reason = detail?.reason;
804
+ }
805
+ };
806
+ }
807
+ });
808
+
809
+ // ../core/dist/common-auth-embedded/fs/atomic-write.js
810
+ import { randomUUID as randomUUID6 } from "node:crypto";
811
+ import { mkdir as mkdir6, open as open3, rename as rename4, rm as rm3 } from "node:fs/promises";
812
+ import { dirname as dirname6 } from "node:path";
547
813
  async function writeJsonAtomic2(path2, value, options = {}) {
548
814
  await writeJsonAtomicTracked(path2, value, options);
549
815
  }
550
816
  async function writeJsonAtomicTracked(path2, value, options, onRenamed) {
551
- await mkdir6(dirname5(path2), { recursive: true });
552
- const tempPath = `${path2}.${(options.stageName ?? randomUUID5)()}.tmp`;
817
+ if (windowsPrivateFiles) {
818
+ return writePrivateAtomic(path2, options.serialize ? options.serialize(value) : `${JSON.stringify(value, null, 2)}
819
+ `, {
820
+ beforeRename: options.beforeRename,
821
+ stagePath: `${path2}.${(options.stageName ?? randomUUID6)()}.tmp`,
822
+ onRenamed,
823
+ durable: options.durable,
824
+ durability: options.durability,
825
+ onOutcome: options.onOutcome
826
+ });
827
+ }
828
+ await mkdir6(dirname6(path2), { recursive: true });
829
+ const tempPath = `${path2}.${(options.stageName ?? randomUUID6)()}.tmp`;
553
830
  let handle;
554
831
  let created = false;
555
832
  try {
@@ -568,11 +845,11 @@ async function writeJsonAtomicTracked(path2, value, options, onRenamed) {
568
845
  await handle.close();
569
846
  handle = void 0;
570
847
  await options.beforeRename?.();
571
- await rename3(tempPath, path2);
848
+ await rename4(tempPath, path2);
572
849
  created = false;
573
850
  onRenamed?.();
574
851
  if (options.durable) {
575
- const directory = await open3(dirname5(path2), "r");
852
+ const directory = await open3(dirname6(path2), "r");
576
853
  try {
577
854
  await directory.sync();
578
855
  } catch (cause) {
@@ -590,13 +867,21 @@ async function writeJsonAtomicTracked(path2, value, options, onRenamed) {
590
867
  }
591
868
  }
592
869
  async function syncJsonFile(path2) {
870
+ if (windowsPrivateFiles) {
871
+ await verifyPrivate(path2, "file");
872
+ const error = new PrivateFileError(path2, "directory-sync-unsupported", {
873
+ code: "ENOTSUP"
874
+ });
875
+ error.published = true;
876
+ throw error;
877
+ }
593
878
  const file = await open3(path2, "r");
594
879
  try {
595
880
  await file.sync();
596
881
  } finally {
597
882
  await file.close();
598
883
  }
599
- const directory = await open3(dirname5(path2), "r");
884
+ const directory = await open3(dirname6(path2), "r");
600
885
  try {
601
886
  await directory.sync();
602
887
  } finally {
@@ -607,6 +892,7 @@ var AtomicSyncError;
607
892
  var init_atomic_write = __esm({
608
893
  "../core/dist/common-auth-embedded/fs/atomic-write.js"() {
609
894
  "use strict";
895
+ init_private_files();
610
896
  AtomicSyncError = class extends Error {
611
897
  constructor(cause) {
612
898
  super("file or directory sync failed", { cause });
@@ -617,24 +903,25 @@ var init_atomic_write = __esm({
617
903
  });
618
904
 
619
905
  // ../core/dist/common-auth-embedded/fs/refresh-file-lock.js
620
- import { randomUUID as randomUUID6 } from "node:crypto";
621
- import { mkdir as mkdir7, open as open4, readFile as readFile4, rename as rename4, rm as rm4, stat as stat3, writeFile as writeFile3 } from "node:fs/promises";
622
- import { dirname as dirname6, join as join4 } from "node:path";
906
+ import { randomUUID as randomUUID7 } from "node:crypto";
907
+ import { mkdir as mkdir7, open as open4, readFile as readFile5, rename as rename5, rm as rm4, stat as stat3, writeFile as writeFile3 } from "node:fs/promises";
908
+ import { dirname as dirname7, join as join4 } from "node:path";
623
909
  function isLostMarkerRaceError(error) {
624
910
  const code2 = error?.code;
625
- return code2 === "ENOENT" || code2 === "EINVAL" || code2 === "ENOTDIR";
911
+ return code2 === "ENOENT" || !windowsPrivateFiles && (code2 === "EINVAL" || code2 === "ENOTDIR");
626
912
  }
627
913
  async function acquireRefreshFileLock(options) {
628
914
  const lockPath = lockPathFor(options.path, options.name);
629
915
  const legacyOwnerPath = join4(lockPath, "owner.json");
630
- const ownerId = randomUUID6();
916
+ const ownerId = randomUUID7();
631
917
  const now = options.now ?? Date.now;
632
918
  let renewTimer = null;
633
919
  let released = false;
920
+ let releaseConfirmed = false;
634
921
  let loss;
635
922
  let resolveLoss;
636
- const lostPromise = new Promise((resolve7) => {
637
- resolveLoss = resolve7;
923
+ const lostPromise = new Promise((resolve13) => {
924
+ resolveLoss = resolve13;
638
925
  });
639
926
  function notifyTimerStep(event) {
640
927
  try {
@@ -665,24 +952,53 @@ async function acquireRefreshFileLock(options) {
665
952
  cancelRenewalTimer();
666
953
  resolveLoss(loss);
667
954
  }
955
+ let terminalIOError;
668
956
  let renewalInFlight = null;
669
957
  const evictPath = `${lockPath}.evicting`;
670
958
  const evictOwnerPath = join4(evictPath, "owner.json");
671
- const evictOwnerId = randomUUID6();
959
+ const evictOwnerId = randomUUID7();
672
960
  const EVICT_TTL = 5e3;
673
961
  const MAX_STEAL_ATTEMPTS = 8;
674
962
  async function readOwner() {
963
+ if (windowsPrivateFiles) {
964
+ try {
965
+ return JSON.parse(await readPrivateText(lockPath, true));
966
+ } catch (error) {
967
+ if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
968
+ throw error;
969
+ await verifyPrivate(lockPath, "directory", true);
970
+ return JSON.parse(await readPrivateText(legacyOwnerPath, true));
971
+ }
972
+ }
675
973
  try {
676
- return JSON.parse(await readFile4(lockPath, "utf8"));
974
+ return JSON.parse(await readFile5(lockPath, "utf8"));
677
975
  } catch (error) {
678
976
  const code2 = error.code;
679
977
  if (code2 !== "EISDIR")
680
978
  throw error;
681
- return JSON.parse(await readFile4(legacyOwnerPath, "utf8"));
979
+ return JSON.parse(await readFile5(legacyOwnerPath, "utf8"));
682
980
  }
683
981
  }
684
982
  async function writeOwner() {
685
- const tempPath = `${lockPath}.${randomUUID6()}.tmp`;
983
+ if (windowsPrivateFiles) {
984
+ const owner = await readOwner();
985
+ const remaining = Number(owner?.expiresAt) - now();
986
+ await writePrivateAtomic(lockPath, `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
987
+ `, {
988
+ deadline: performance.now() + Math.max(0, remaining),
989
+ beforeRename: async () => {
990
+ const current = await readOwner();
991
+ if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
992
+ throw new LockOwnershipError({
993
+ target: options.path,
994
+ name: options.name
995
+ });
996
+ }
997
+ }
998
+ });
999
+ return;
1000
+ }
1001
+ const tempPath = `${lockPath}.${randomUUID7()}.tmp`;
686
1002
  let handle;
687
1003
  let created = false;
688
1004
  try {
@@ -693,7 +1009,14 @@ async function acquireRefreshFileLock(options) {
693
1009
  await handle.chmod(384);
694
1010
  await handle.close();
695
1011
  handle = void 0;
696
- await rename4(tempPath, lockPath);
1012
+ const current = await readOwner();
1013
+ if (current?.ownerId !== ownerId || !(Number(current?.expiresAt) > now()) || !await ownsEvictionMarker()) {
1014
+ throw new LockOwnershipError({
1015
+ target: options.path,
1016
+ name: options.name
1017
+ });
1018
+ }
1019
+ await rename5(tempPath, lockPath);
697
1020
  created = false;
698
1021
  } finally {
699
1022
  await handle?.close().catch(() => {
@@ -703,24 +1026,54 @@ async function acquireRefreshFileLock(options) {
703
1026
  });
704
1027
  }
705
1028
  }
1029
+ async function createLease() {
1030
+ const bytes = `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
1031
+ `;
1032
+ if (windowsPrivateFiles)
1033
+ await createPrivateBytes(lockPath, bytes);
1034
+ else
1035
+ await writeFile3(lockPath, bytes, {
1036
+ encoding: "utf8",
1037
+ mode: 384,
1038
+ flag: "wx"
1039
+ });
1040
+ }
1041
+ async function leaseContention(error) {
1042
+ const code2 = error.code;
1043
+ if (code2 === "EEXIST") {
1044
+ if (windowsPrivateFiles)
1045
+ await readOwner();
1046
+ return true;
1047
+ }
1048
+ if (code2 === "EISDIR") {
1049
+ if (windowsPrivateFiles) {
1050
+ await verifyPrivate(lockPath, "directory", true);
1051
+ await readPrivateText(legacyOwnerPath, true);
1052
+ }
1053
+ return true;
1054
+ }
1055
+ return false;
1056
+ }
706
1057
  async function tryAcquire() {
1058
+ if (windowsPrivateFiles)
1059
+ await ensurePrivateDirectory(dirname7(lockPath));
707
1060
  try {
708
- await writeFile3(lockPath, `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
709
- `, { encoding: "utf8", mode: 384, flag: "wx" });
1061
+ await createLease();
710
1062
  return true;
711
1063
  } catch (error) {
712
1064
  const code2 = error.code;
713
- if (code2 === "EEXIST" || code2 === "EISDIR")
1065
+ if (await leaseContention(error))
714
1066
  return false;
715
1067
  if (code2 === "ENOENT") {
716
- await mkdir7(dirname6(lockPath), { recursive: true });
1068
+ if (windowsPrivateFiles)
1069
+ await ensurePrivateDirectory(dirname7(lockPath));
1070
+ else
1071
+ await mkdir7(dirname7(lockPath), { recursive: true });
717
1072
  try {
718
- await writeFile3(lockPath, `${JSON.stringify({ ownerId, expiresAt: now() + options.ttlMs })}
719
- `, { encoding: "utf8", mode: 384, flag: "wx" });
1073
+ await createLease();
720
1074
  return true;
721
1075
  } catch (retryError) {
722
- const retryCode = retryError.code;
723
- if (retryCode === "EEXIST" || retryCode === "EISDIR")
1076
+ if (await leaseContention(retryError))
724
1077
  return false;
725
1078
  throw retryError;
726
1079
  }
@@ -729,40 +1082,98 @@ async function acquireRefreshFileLock(options) {
729
1082
  }
730
1083
  }
731
1084
  async function backoff() {
732
- await new Promise((resolve7) => setTimeout(resolve7, Math.floor(Math.random() * 4)));
1085
+ await new Promise((resolve13) => setTimeout(resolve13, Math.floor(Math.random() * 4)));
733
1086
  }
734
- async function lockIsLive() {
1087
+ async function readLockState(notifyReady = true) {
1088
+ if (notifyReady && options.onStep)
1089
+ await options.onStep("lock-read-ready");
1090
+ let owner;
735
1091
  try {
736
- const currentOwner = await readOwner();
737
- return Number(currentOwner?.expiresAt) > now();
738
- } catch {
739
- try {
740
- const current = await stat3(lockPath);
741
- return current.mtimeMs + options.ttlMs > now();
742
- } catch {
743
- return false;
1092
+ owner = await readOwner();
1093
+ } catch (error) {
1094
+ if (windowsPrivateFiles && error.code !== "ENOENT")
1095
+ throw error;
1096
+ }
1097
+ const expiresAt = Number(owner?.expiresAt);
1098
+ if (Number.isFinite(expiresAt) && expiresAt > now())
1099
+ return { status: "live" };
1100
+ if (typeof owner?.ownerId === "string" && Number.isFinite(expiresAt)) {
1101
+ return {
1102
+ status: "stale",
1103
+ identity: { kind: "owner", ownerId: owner.ownerId, expiresAt }
1104
+ };
1105
+ }
1106
+ try {
1107
+ const current = await stat3(lockPath);
1108
+ const legacyExpiry = Number.isFinite(expiresAt) ? expiresAt : current.mtimeMs + options.ttlMs;
1109
+ if (legacyExpiry > now())
1110
+ return { status: "live" };
1111
+ return {
1112
+ status: "stale",
1113
+ identity: {
1114
+ kind: "stat",
1115
+ dev: current.dev,
1116
+ ino: current.ino,
1117
+ mtimeMs: current.mtimeMs,
1118
+ expiresAt: legacyExpiry
1119
+ }
1120
+ };
1121
+ } catch (error) {
1122
+ if (error.code === "ENOENT") {
1123
+ if (options.onStep)
1124
+ await options.onStep("lock-missing");
1125
+ return { status: "missing" };
744
1126
  }
1127
+ throw error;
1128
+ }
1129
+ }
1130
+ function sameStaleLock(observed, current) {
1131
+ if (current.status !== "stale")
1132
+ return false;
1133
+ const identity = current.identity;
1134
+ if (observed.kind === "owner" && identity.kind === "owner") {
1135
+ return observed.ownerId === identity.ownerId && observed.expiresAt === identity.expiresAt;
745
1136
  }
1137
+ return observed.kind === "stat" && identity.kind === "stat" && observed.dev === identity.dev && observed.ino === identity.ino && observed.mtimeMs === identity.mtimeMs && observed.expiresAt === identity.expiresAt;
746
1138
  }
747
1139
  async function ownsEvictionMarker() {
748
1140
  try {
749
- const owner = JSON.parse(await readFile4(evictOwnerPath, "utf8"));
1141
+ const owner = JSON.parse(await readPrivateText(evictOwnerPath, windowsPrivateFiles));
750
1142
  return owner?.ownerId === evictOwnerId;
751
- } catch {
1143
+ } catch (error) {
1144
+ if (windowsPrivateFiles && error.code !== "ENOENT")
1145
+ throw error;
752
1146
  return false;
753
1147
  }
754
1148
  }
1149
+ async function removeLeaseObject(path2) {
1150
+ if (windowsPrivateFiles)
1151
+ await privateOperation(path2, "remove", () => rm4(path2, { recursive: true, force: true }));
1152
+ else
1153
+ await rm4(path2, { recursive: true, force: true }).catch(() => {
1154
+ });
1155
+ }
755
1156
  async function releaseEvictionMarker() {
756
1157
  if (await ownsEvictionMarker()) {
757
- await rm4(evictPath, { recursive: true, force: true }).catch(() => {
758
- });
1158
+ await removeLeaseObject(evictPath);
759
1159
  }
760
1160
  }
761
1161
  async function tryAcquireEvictionMarker() {
762
- await mkdir7(evictPath);
1162
+ if (windowsPrivateFiles)
1163
+ await createPrivateDirectoryExclusive(evictPath);
1164
+ else
1165
+ await mkdir7(evictPath);
763
1166
  try {
764
- await writeFile3(evictOwnerPath, `${JSON.stringify({ ownerId: evictOwnerId, createdAt: now() })}
765
- `, { encoding: "utf8", mode: 384, flag: "wx" });
1167
+ const bytes = `${JSON.stringify({ ownerId: evictOwnerId, createdAt: now() })}
1168
+ `;
1169
+ if (windowsPrivateFiles)
1170
+ await createPrivateBytes(evictOwnerPath, bytes);
1171
+ else
1172
+ await writeFile3(evictOwnerPath, bytes, {
1173
+ encoding: "utf8",
1174
+ mode: 384,
1175
+ flag: "wx"
1176
+ });
766
1177
  } catch (error) {
767
1178
  if (isLostMarkerRaceError(error))
768
1179
  return false;
@@ -782,13 +1193,15 @@ async function acquireRefreshFileLock(options) {
782
1193
  return "missing";
783
1194
  throw error;
784
1195
  }
1196
+ if (windowsPrivateFiles)
1197
+ await verifyPrivate(evictPath, "directory", true);
785
1198
  if (evictStat.mtimeMs + EVICT_TTL > now())
786
1199
  return "fresh";
787
1200
  if (options.onStep)
788
1201
  await options.onStep("stale-marker-stat");
789
- const claimedPath = `${evictPath}.${randomUUID6()}`;
1202
+ const claimedPath = `${evictPath}.${randomUUID7()}`;
790
1203
  try {
791
- await rename4(evictPath, claimedPath);
1204
+ await rename5(evictPath, claimedPath);
792
1205
  } catch (error) {
793
1206
  if (error.code === "ENOENT")
794
1207
  return "missing";
@@ -796,8 +1209,7 @@ async function acquireRefreshFileLock(options) {
796
1209
  }
797
1210
  if (options.onStep)
798
1211
  await options.onStep("stale-marker-claimed");
799
- await rm4(claimedPath, { recursive: true, force: true }).catch(() => {
800
- });
1212
+ await removeLeaseObject(claimedPath);
801
1213
  return "recovered";
802
1214
  }
803
1215
  async function withEvictionMarker(action) {
@@ -805,8 +1217,18 @@ async function acquireRefreshFileLock(options) {
805
1217
  if (!await tryAcquireEvictionMarker())
806
1218
  return false;
807
1219
  } catch (error) {
808
- if (error.code === "EEXIST")
1220
+ if (error.code === "EEXIST") {
1221
+ if (windowsPrivateFiles) {
1222
+ await verifyPrivate(evictPath, "directory", true);
1223
+ try {
1224
+ await readPrivateText(evictOwnerPath, true);
1225
+ } catch (ownerError) {
1226
+ if (ownerError.code !== "ENOENT")
1227
+ throw ownerError;
1228
+ }
1229
+ }
809
1230
  return false;
1231
+ }
810
1232
  throw error;
811
1233
  }
812
1234
  try {
@@ -823,7 +1245,9 @@ async function acquireRefreshFileLock(options) {
823
1245
  let owner;
824
1246
  try {
825
1247
  owner = await readOwner();
826
- } catch {
1248
+ } catch (error) {
1249
+ if (windowsPrivateFiles)
1250
+ throw error;
827
1251
  return;
828
1252
  }
829
1253
  if (owner?.ownerId !== ownerId)
@@ -831,7 +1255,9 @@ async function acquireRefreshFileLock(options) {
831
1255
  try {
832
1256
  await rm4(lockPath, { recursive: true, force: true });
833
1257
  return;
834
- } catch {
1258
+ } catch (error) {
1259
+ if (windowsPrivateFiles)
1260
+ throw error;
835
1261
  await backoff();
836
1262
  }
837
1263
  }
@@ -885,6 +1311,8 @@ async function acquireRefreshFileLock(options) {
885
1311
  return;
886
1312
  }
887
1313
  await writeOwner();
1314
+ if (options.onStep)
1315
+ await options.onStep("renewal-write-finished");
888
1316
  if (!await ownsEvictionMarker()) {
889
1317
  recordLoss("marker-lost");
890
1318
  shouldReschedule = false;
@@ -895,7 +1323,12 @@ async function acquireRefreshFileLock(options) {
895
1323
  if (!markerAcquired && options.onStep) {
896
1324
  await options.onStep("renewal-marker-unavailable");
897
1325
  }
898
- } catch {
1326
+ } catch (error) {
1327
+ if (windowsPrivateFiles && error instanceof PrivateFileError) {
1328
+ terminalIOError = error;
1329
+ recordLoss("renewal-failed");
1330
+ shouldReschedule = false;
1331
+ }
899
1332
  try {
900
1333
  const owner = await readOwner();
901
1334
  if (owner?.ownerId !== ownerId)
@@ -943,8 +1376,11 @@ async function acquireRefreshFileLock(options) {
943
1376
  acquired = await tryAcquire();
944
1377
  if (acquired)
945
1378
  break;
946
- if (await lockIsLive())
1379
+ const observed = await readLockState();
1380
+ if (observed.status === "live")
947
1381
  return contended();
1382
+ if (observed.status === "missing")
1383
+ continue;
948
1384
  if (options.onStep)
949
1385
  await options.onStep("stale-lock-observed");
950
1386
  try {
@@ -963,16 +1399,21 @@ async function acquireRefreshFileLock(options) {
963
1399
  continue;
964
1400
  }
965
1401
  try {
966
- if (await lockIsLive())
1402
+ const confirmed = await readLockState();
1403
+ if (confirmed.status === "live")
967
1404
  return contended();
1405
+ if (!sameStaleLock(observed.identity, confirmed))
1406
+ continue;
968
1407
  if (!await ownsEvictionMarker())
969
1408
  return null;
970
1409
  if (options.onStep)
971
1410
  await options.onStep("stale-lock-confirmed");
972
1411
  if (!await ownsEvictionMarker())
973
1412
  return null;
974
- await rm4(lockPath, { recursive: true, force: true }).catch(() => {
975
- });
1413
+ const current = await readLockState(false);
1414
+ if (!sameStaleLock(observed.identity, current))
1415
+ continue;
1416
+ await removeLeaseObject(lockPath);
976
1417
  if (!await ownsEvictionMarker())
977
1418
  return null;
978
1419
  if (options.onStep)
@@ -1001,6 +1442,8 @@ async function acquireRefreshFileLock(options) {
1001
1442
  whenLost: () => lostPromise,
1002
1443
  hasLost: () => loss !== void 0,
1003
1444
  assertOwned: async () => {
1445
+ if (terminalIOError)
1446
+ throw terminalIOError;
1004
1447
  let observed;
1005
1448
  try {
1006
1449
  const owner = await readOwner();
@@ -1008,8 +1451,10 @@ async function acquireRefreshFileLock(options) {
1008
1451
  if (!released && !loss && owner?.ownerId === ownerId && Number(owner?.expiresAt) > now())
1009
1452
  return;
1010
1453
  recordLoss(owner?.ownerId !== ownerId ? "taken-over" : "expired", owner);
1011
- } catch {
1454
+ } catch (error) {
1012
1455
  recordLoss("unreadable");
1456
+ if (windowsPrivateFiles && error instanceof PrivateFileError)
1457
+ throw error;
1013
1458
  }
1014
1459
  throw new LockOwnershipError({
1015
1460
  target: options.path,
@@ -1020,30 +1465,56 @@ async function acquireRefreshFileLock(options) {
1020
1465
  });
1021
1466
  },
1022
1467
  release: async () => {
1468
+ if (windowsPrivateFiles && releaseConfirmed)
1469
+ return;
1023
1470
  released = true;
1024
1471
  cancelRenewalTimer();
1025
1472
  await renewalInFlight;
1026
1473
  for (let attempt = 0; attempt < MAX_STEAL_ATTEMPTS; attempt++) {
1027
1474
  try {
1475
+ let removalConfirmed = false;
1028
1476
  const markerAcquired = await withEvictionMarker(async () => {
1029
- const owner = await readOwner();
1030
- if (owner?.ownerId !== ownerId)
1477
+ let owner;
1478
+ try {
1479
+ owner = await readOwner();
1480
+ } catch (error) {
1481
+ if (windowsPrivateFiles && error.code === "ENOENT") {
1482
+ removalConfirmed = true;
1483
+ return;
1484
+ }
1485
+ throw error;
1486
+ }
1487
+ if (owner?.ownerId !== ownerId) {
1488
+ removalConfirmed = true;
1031
1489
  return;
1490
+ }
1032
1491
  if (options.onStep)
1033
1492
  await options.onStep("release-owner-confirmed");
1034
1493
  if (!await ownsEvictionMarker())
1035
1494
  return;
1036
- await rm4(lockPath, { recursive: true, force: true }).catch(() => {
1037
- });
1495
+ await removeLeaseObject(lockPath);
1496
+ removalConfirmed = true;
1038
1497
  });
1039
- if (markerAcquired)
1498
+ if (markerAcquired) {
1499
+ if (windowsPrivateFiles && !removalConfirmed)
1500
+ throw new PrivateFileError(lockPath, "release-not-confirmed", {
1501
+ code: "EIO"
1502
+ });
1503
+ releaseConfirmed = removalConfirmed;
1040
1504
  return;
1505
+ }
1041
1506
  await recoverStaleEvictionMarker();
1042
- } catch {
1507
+ } catch (error) {
1508
+ if (windowsPrivateFiles)
1509
+ throw error;
1043
1510
  return;
1044
1511
  }
1045
1512
  await backoff();
1046
1513
  }
1514
+ if (windowsPrivateFiles)
1515
+ throw new PrivateFileError(lockPath, "release-not-confirmed", {
1516
+ code: "ETIMEDOUT"
1517
+ });
1047
1518
  }
1048
1519
  };
1049
1520
  }
@@ -1051,6 +1522,7 @@ var setRefreshLockRenewalTimeout, clearRefreshLockRenewalTimeout;
1051
1522
  var init_refresh_file_lock = __esm({
1052
1523
  "../core/dist/common-auth-embedded/fs/refresh-file-lock.js"() {
1053
1524
  "use strict";
1525
+ init_private_files();
1054
1526
  init_with_lock();
1055
1527
  setRefreshLockRenewalTimeout = globalThis.setTimeout.bind(globalThis);
1056
1528
  clearRefreshLockRenewalTimeout = globalThis.clearTimeout.bind(globalThis);
@@ -1068,7 +1540,9 @@ async function withLock(target, options, fn) {
1068
1540
  path: target,
1069
1541
  name: options.name,
1070
1542
  ttlMs: options.ttlMs,
1071
- renew: options.renew ?? false
1543
+ renew: options.renew ?? false,
1544
+ ...options.onStep ? { onStep: options.onStep } : {},
1545
+ ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
1072
1546
  });
1073
1547
  if (lock) {
1074
1548
  try {
@@ -1085,7 +1559,7 @@ async function withLock(target, options, fn) {
1085
1559
  timeoutMs: options.timeoutMs
1086
1560
  });
1087
1561
  }
1088
- await new Promise((resolve7) => setTimeout(resolve7, Math.min(25, Math.ceil(remaining))));
1562
+ await new Promise((resolve13) => setTimeout(resolve13, Math.min(25, Math.ceil(remaining))));
1089
1563
  }
1090
1564
  }
1091
1565
  var LockContentionError, LockOwnershipError;
@@ -1169,6 +1643,9 @@ async function acquirePoolLock(spec, defaults, env3) {
1169
1643
  now: env3.now,
1170
1644
  renew: options.renew,
1171
1645
  onContended: () => emit("contended"),
1646
+ ...env3.onRenewalTimer ? {
1647
+ onRenewalTimer: (event) => env3.onRenewalTimer?.({ name: spec.name, path: spec.path }, event)
1648
+ } : {},
1172
1649
  ...options.renewIntervalMs !== void 0 ? { renewIntervalMs: options.renewIntervalMs } : {},
1173
1650
  ...env3.onLockStep ? {
1174
1651
  onStep: (step) => env3.onLockStep?.({ name: spec.name, path: spec.path }, step)
@@ -1202,7 +1679,7 @@ async function acquirePoolLock(spec, defaults, env3) {
1202
1679
  });
1203
1680
  }
1204
1681
  const jitter = Math.floor(Math.random() * (options.retryMs + 1));
1205
- await new Promise((resolve7) => setTimeout(resolve7, Math.min(options.retryMs + jitter, remaining)));
1682
+ await new Promise((resolve13) => setTimeout(resolve13, Math.min(options.retryMs + jitter, remaining)));
1206
1683
  }
1207
1684
  }
1208
1685
  function definedOnly(spec) {
@@ -1961,11 +2438,10 @@ var init_torn = __esm({
1961
2438
  });
1962
2439
 
1963
2440
  // ../core/dist/common-auth-embedded/store/mutate.js
1964
- import { readFile as readFile5 } from "node:fs/promises";
1965
2441
  import { setTimeout as snapshotDelay } from "node:timers/promises";
1966
2442
  async function readText(path2) {
1967
2443
  try {
1968
- return await readFile5(path2, "utf8");
2444
+ return await readPrivateText(path2, windowsPrivateFiles);
1969
2445
  } catch (error) {
1970
2446
  if (error.code === "ENOENT")
1971
2447
  return void 0;
@@ -2173,6 +2649,7 @@ var init_mutate = __esm({
2173
2649
  "../core/dist/common-auth-embedded/store/mutate.js"() {
2174
2650
  "use strict";
2175
2651
  init_atomic_write();
2652
+ init_private_files();
2176
2653
  init_with_lock();
2177
2654
  init_errors();
2178
2655
  init_hooks();
@@ -2665,7 +3142,7 @@ var init_provider_state = __esm({
2665
3142
  });
2666
3143
 
2667
3144
  // ../core/dist/common-auth-embedded/store/rows.js
2668
- import { randomUUID as randomUUID7 } from "node:crypto";
3145
+ import { randomUUID as randomUUID8 } from "node:crypto";
2669
3146
  async function protectIn(tx, id, protect) {
2670
3147
  if (!protect)
2671
3148
  return;
@@ -3300,7 +3777,7 @@ async function transitionRow(rt, operation, id, flag, options) {
3300
3777
  await tx.commitState();
3301
3778
  return result;
3302
3779
  }
3303
- const transition = flag.enabled ? { mark: randomUUID7(), enabled: true } : { mark: randomUUID7(), enabled: false, reason: flag.reason };
3780
+ const transition = flag.enabled ? { mark: randomUUID8(), enabled: true } : { mark: randomUUID8(), enabled: false, reason: flag.reason };
3304
3781
  const stamp = plan.account[CREDENTIAL_STAMP_KEY];
3305
3782
  tx.setStateAccount(id, {
3306
3783
  ...plan.account,
@@ -3937,7 +4414,7 @@ var init_pull = __esm({
3937
4414
  });
3938
4415
 
3939
4416
  // ../core/dist/common-auth-embedded/store/refresh.js
3940
- import { randomUUID as randomUUID8 } from "node:crypto";
4417
+ import { randomUUID as randomUUID9 } from "node:crypto";
3941
4418
  function requireRefreshable(id, row) {
3942
4419
  assertNotReserved("refresh", id, row?.staged);
3943
4420
  if (!row)
@@ -4054,7 +4531,7 @@ async function refreshRow(rt, id, provider, options = {}) {
4054
4531
  returnedIdentity: result.identity
4055
4532
  } : void 0;
4056
4533
  const transition = contradiction ? {
4057
- mark: randomUUID8(),
4534
+ mark: randomUUID9(),
4058
4535
  enabled: false,
4059
4536
  reason: `${IDENTITY_CONTRADICTED_REASON_PREFIX}${JSON.stringify(contradiction)}`
4060
4537
  } : void 0;
@@ -4280,7 +4757,8 @@ function openPoolStore(options) {
4280
4757
  lockEnv: {
4281
4758
  now: options.now ?? Date.now,
4282
4759
  ...options.onLockEvent ? { onLockEvent: options.onLockEvent } : {},
4283
- ...options.onLockStep ? { onLockStep: options.onLockStep } : {}
4760
+ ...options.onLockStep ? { onLockStep: options.onLockStep } : {},
4761
+ ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
4284
4762
  },
4285
4763
  removedIds: memory.removedIds,
4286
4764
  requireCredentialStamps: options.requireCredentialStamps === true,
@@ -4412,6 +4890,7 @@ var fs_exports = {};
4412
4890
  __export(fs_exports, {
4413
4891
  LockContentionError: () => LockContentionError,
4414
4892
  LockOwnershipError: () => LockOwnershipError,
4893
+ PrivateFileError: () => PrivateFileError,
4415
4894
  WRITER_LOCK_CONSTANTS: () => WRITER_LOCK_CONSTANTS,
4416
4895
  acquireRefreshFileLock: () => acquireRefreshFileLock,
4417
4896
  isLostMarkerRaceError: () => isLostMarkerRaceError,
@@ -4424,6 +4903,7 @@ var init_fs = __esm({
4424
4903
  "use strict";
4425
4904
  init_atomic_write();
4426
4905
  init_lock_constants();
4906
+ init_private_files();
4427
4907
  init_refresh_file_lock();
4428
4908
  init_with_lock();
4429
4909
  }
@@ -4496,7 +4976,7 @@ function admit(input) {
4496
4976
  const scope = input.scope ?? ALL_SCOPE;
4497
4977
  const requiredLabels = input.requiredLabels ?? DEFAULT_REQUIRED_LABELS;
4498
4978
  const excluded = [];
4499
- const refused = [];
4979
+ const refused2 = [];
4500
4980
  const survivors = [];
4501
4981
  for (const row of input.rows) {
4502
4982
  const exclusion = exclusionFor(row.id, input, input.now);
@@ -4509,9 +4989,9 @@ function admit(input) {
4509
4989
  continue;
4510
4990
  }
4511
4991
  const projection = projectQuota(row.quota, scope);
4512
- const refusal3 = judgeStageOne(row.id, projection, requiredLabels, input.now);
4513
- if (refusal3) {
4514
- refused.push(refusal3);
4992
+ const refusal4 = judgeStageOne(row.id, projection, requiredLabels, input.now);
4993
+ if (refusal4) {
4994
+ refused2.push(refusal4);
4515
4995
  continue;
4516
4996
  }
4517
4997
  survivors.push({ id: row.id, kind: row.kind, projection });
@@ -4529,16 +5009,16 @@ function admit(input) {
4529
5009
  } else if (lastPath) {
4530
5010
  admitted.push({ ...row, lastPath: true });
4531
5011
  } else {
4532
- refused.push({ id: row.id, stage: 2, reason: "budget-spent", ...reset });
5012
+ refused2.push({ id: row.id, stage: 2, reason: "budget-spent", ...reset });
4533
5013
  }
4534
5014
  }
4535
5015
  const order = new Map(input.rows.map((row, index) => [row.id, index]));
4536
5016
  const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
4537
- refused.sort(byInput);
4538
- const pulls = refused.filter((refusal3) => "pullRequested" in refusal3).map((refusal3) => refusal3.id);
5017
+ refused2.sort(byInput);
5018
+ const pulls = refused2.filter((refusal4) => "pullRequested" in refusal4).map((refusal4) => refusal4.id);
4539
5019
  for (const id of pulls)
4540
5020
  input.requestPull?.(id);
4541
- return { admitted, refused, excluded, pulls };
5021
+ return { admitted, refused: refused2, excluded, pulls };
4542
5022
  }
4543
5023
  var init_admission = __esm({
4544
5024
  "../core/dist/common-auth-embedded/routing/admission.js"() {
@@ -4809,9 +5289,9 @@ function routeSticky(input) {
4809
5289
  });
4810
5290
  if (!selection)
4811
5291
  break;
4812
- const refusal3 = refusals.get(selection.accountId);
4813
- if (refusal3) {
4814
- refusedSelections.push(refusal3);
5292
+ const refusal4 = refusals.get(selection.accountId);
5293
+ if (refusal4) {
5294
+ refusedSelections.push(refusal4);
4815
5295
  candidates = candidates.filter((candidate) => candidate.accountId !== selection.accountId);
4816
5296
  continue;
4817
5297
  }
@@ -4888,15 +5368,15 @@ var init_routing = __esm({
4888
5368
 
4889
5369
  // ../core/dist/common-auth-embedded/logger/capture-sink.js
4890
5370
  function createCaptureSink() {
4891
- const records2 = [];
5371
+ const records = [];
4892
5372
  const sink = (record2) => {
4893
- records2.push(record2);
5373
+ records.push(record2);
4894
5374
  };
4895
5375
  return {
4896
- records: records2,
5376
+ records,
4897
5377
  sink,
4898
5378
  clear: () => {
4899
- records2.length = 0;
5379
+ records.length = 0;
4900
5380
  }
4901
5381
  };
4902
5382
  }
@@ -4978,6 +5458,8 @@ var init_redact = __esm({
4978
5458
 
4979
5459
  // ../core/dist/common-auth-embedded/logger/engine.js
4980
5460
  import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
5461
+ import { open as open5 } from "node:fs/promises";
5462
+ import { dirname as dirname8, resolve as resolve3 } from "node:path";
4981
5463
  function chmodPrivate(path2) {
4982
5464
  try {
4983
5465
  chmodSync(path2, 384);
@@ -5001,6 +5483,69 @@ function rotateIfNeeded(f) {
5001
5483
  } catch {
5002
5484
  }
5003
5485
  }
5486
+ async function closeWindowsFile(sink) {
5487
+ const { file, handle } = sink;
5488
+ sink.file = void 0;
5489
+ sink.handle = void 0;
5490
+ if (file && handle)
5491
+ await privateOperation(file, "log-close", () => handle.close());
5492
+ }
5493
+ async function openWindowsFile(sink, file) {
5494
+ await ensurePrivateDirectory(dirname8(file));
5495
+ try {
5496
+ await verifyPrivate(file, "file", true);
5497
+ } catch (error) {
5498
+ if (error.code !== "ENOENT")
5499
+ throw error;
5500
+ try {
5501
+ await createPrivateBytes(file, "");
5502
+ } catch (creationError) {
5503
+ if (creationError.code !== "EEXIST")
5504
+ throw creationError;
5505
+ await verifyPrivate(file, "file", true);
5506
+ }
5507
+ }
5508
+ sink.handle = await privateOperation(file, "log-open", () => open5(file, "a"));
5509
+ sink.file = file;
5510
+ return sink.handle;
5511
+ }
5512
+ async function flushWindowsFile(sink, file, text2) {
5513
+ file = resolve3(file);
5514
+ try {
5515
+ if (sink.file !== file)
5516
+ await closeWindowsFile(sink);
5517
+ let handle = sink.handle ?? await openWindowsFile(sink, file);
5518
+ const info = await privateOperation(file, "log-stat", () => handle.stat());
5519
+ if (info.size >= MAX_BYTES) {
5520
+ await closeWindowsFile(sink);
5521
+ for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
5522
+ const source = i === 0 ? file : `${file}.${i}`;
5523
+ const target = `${file}.${i + 1}`;
5524
+ try {
5525
+ await verifyPrivate(source, "file", true);
5526
+ } catch (error) {
5527
+ if (error.code === "ENOENT")
5528
+ continue;
5529
+ throw error;
5530
+ }
5531
+ try {
5532
+ await verifyPrivate(target, "file", true);
5533
+ } catch (error) {
5534
+ if (error.code !== "ENOENT")
5535
+ throw error;
5536
+ }
5537
+ await replaceWindowsFile(source, target);
5538
+ await verifyPrivate(target, "file");
5539
+ }
5540
+ handle = await openWindowsFile(sink, file);
5541
+ }
5542
+ await privateOperation(file, "log-append", () => handle.appendFile(text2, "utf8"));
5543
+ } catch (error) {
5544
+ await closeWindowsFile(sink).catch(() => {
5545
+ });
5546
+ throw error;
5547
+ }
5548
+ }
5004
5549
  function safeSerialize(data) {
5005
5550
  try {
5006
5551
  return ` ${JSON.stringify(data)}`;
@@ -5016,7 +5561,20 @@ function createEngine(options) {
5016
5561
  let captureSink;
5017
5562
  let buffer = [];
5018
5563
  let timer;
5564
+ let orderedSink = Promise.resolve();
5565
+ let sinkError;
5566
+ const windowsFile = {};
5567
+ function queueWindows(operation) {
5568
+ const next = orderedSink.then(operation);
5569
+ orderedSink = next.catch((error) => {
5570
+ sinkError = error;
5571
+ });
5572
+ return next;
5573
+ }
5019
5574
  function configure(next) {
5575
+ if (windowsPrivateFiles && next.file !== logFileSource)
5576
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
5577
+ });
5020
5578
  logFileSource = next.file;
5021
5579
  initLevelSource = next.level;
5022
5580
  redactor = createRedactor(next);
@@ -5040,24 +5598,47 @@ function createEngine(options) {
5040
5598
  return floor;
5041
5599
  return "info";
5042
5600
  }
5043
- function flushLogs3() {
5601
+ function flushLogs3(close = true) {
5044
5602
  if (timer) {
5045
5603
  clearTimeout(timer);
5046
5604
  timer = void 0;
5047
5605
  }
5048
- if (!buffer.length)
5606
+ if (!buffer.length) {
5607
+ if (windowsPrivateFiles)
5608
+ return queueWindows(async () => {
5609
+ if (close)
5610
+ await closeWindowsFile(windowsFile);
5611
+ if (sinkError)
5612
+ throw sinkError;
5613
+ });
5049
5614
  return;
5615
+ }
5050
5616
  let file;
5051
5617
  try {
5052
5618
  file = logFilePath();
5053
5619
  } catch {
5054
5620
  buffer = [];
5621
+ if (windowsPrivateFiles && close)
5622
+ return queueWindows(() => closeWindowsFile(windowsFile));
5055
5623
  return;
5056
5624
  }
5057
5625
  const text2 = buffer.join("");
5058
5626
  buffer = [];
5059
- if (!file)
5627
+ if (!file) {
5628
+ if (windowsPrivateFiles && close)
5629
+ return queueWindows(() => closeWindowsFile(windowsFile));
5060
5630
  return;
5631
+ }
5632
+ if (windowsPrivateFiles) {
5633
+ return queueWindows(async () => {
5634
+ try {
5635
+ await flushWindowsFile(windowsFile, file, text2);
5636
+ } finally {
5637
+ if (close)
5638
+ await closeWindowsFile(windowsFile);
5639
+ }
5640
+ });
5641
+ }
5061
5642
  try {
5062
5643
  rotateIfNeeded(file);
5063
5644
  if (existsSync(file))
@@ -5070,7 +5651,10 @@ function createEngine(options) {
5070
5651
  if (!timer)
5071
5652
  timer = setTimeout(() => {
5072
5653
  timer = void 0;
5073
- flushLogs3();
5654
+ const flushed = flushLogs3(false);
5655
+ if (flushed instanceof Promise)
5656
+ void flushed.catch(() => {
5657
+ });
5074
5658
  }, 500);
5075
5659
  }
5076
5660
  function emit(channel, level, message, data) {
@@ -5099,9 +5683,12 @@ function createEngine(options) {
5099
5683
  if (logFileSource === void 0)
5100
5684
  return;
5101
5685
  buffer.push(line);
5102
- if (buffer.length >= 50)
5103
- flushLogs3();
5104
- else
5686
+ if (buffer.length >= 50) {
5687
+ const flushed = flushLogs3(false);
5688
+ if (flushed instanceof Promise)
5689
+ void flushed.catch(() => {
5690
+ });
5691
+ } else
5105
5692
  schedule();
5106
5693
  } catch {
5107
5694
  }
@@ -5116,6 +5703,10 @@ function createEngine(options) {
5116
5703
  };
5117
5704
  }
5118
5705
  function reset() {
5706
+ if (windowsPrivateFiles)
5707
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
5708
+ });
5709
+ sinkError = void 0;
5119
5710
  buffer = [];
5120
5711
  if (timer) {
5121
5712
  clearTimeout(timer);
@@ -5144,13 +5735,13 @@ function setLogLevel(l) {
5144
5735
  defaultEngine.setLogLevel(l);
5145
5736
  }
5146
5737
  function flushLogs() {
5147
- defaultEngine.flushLogs();
5738
+ return defaultEngine.flushLogs();
5148
5739
  }
5149
5740
  function createLogger2(channel) {
5150
5741
  return defaultEngine.createLogger(channel);
5151
5742
  }
5152
5743
  async function flushForTest() {
5153
- defaultEngine.flushLogs();
5744
+ return defaultEngine.flushLogs();
5154
5745
  }
5155
5746
  function resetLoggerForTest() {
5156
5747
  defaultEngine.reset();
@@ -5159,6 +5750,7 @@ var ORDER, MAX_BYTES, ROTATE_KEEP, defaultEngine;
5159
5750
  var init_engine = __esm({
5160
5751
  "../core/dist/common-auth-embedded/logger/engine.js"() {
5161
5752
  "use strict";
5753
+ init_private_files();
5162
5754
  init_redact();
5163
5755
  ORDER = {
5164
5756
  error: 0,
@@ -6695,7 +7287,7 @@ async function select(terminal, items, options) {
6695
7287
  writeLine("");
6696
7288
  renderedLines = lines;
6697
7289
  };
6698
- return new Promise((resolve7) => {
7290
+ return new Promise((resolve13) => {
6699
7291
  const wasRaw = stdin.isRaw ?? false;
6700
7292
  const cleanup2 = () => {
6701
7293
  if (cleaned)
@@ -6715,7 +7307,7 @@ async function select(terminal, items, options) {
6715
7307
  };
6716
7308
  const finish = (value) => {
6717
7309
  cleanup2();
6718
- resolve7(value);
7310
+ resolve13(value);
6719
7311
  };
6720
7312
  const onSignal = () => finish(null);
6721
7313
  const onKey = (data) => {
@@ -6755,7 +7347,7 @@ async function select(terminal, items, options) {
6755
7347
  stdin.setRawMode(true);
6756
7348
  } catch {
6757
7349
  cleanup2();
6758
- resolve7(null);
7350
+ resolve13(null);
6759
7351
  return;
6760
7352
  }
6761
7353
  stdin.resume();
@@ -7523,7 +8115,7 @@ var init_socket = __esm({
7523
8115
  return this.sock.localPort ?? null;
7524
8116
  }
7525
8117
  static connect(host, port, deadlineMs) {
7526
- return new Promise((resolve7, reject) => {
8118
+ return new Promise((resolve13, reject) => {
7527
8119
  const sock = net2.connect({ host, port });
7528
8120
  sock.setNoDelay(true);
7529
8121
  const timer = setTimeout(() => {
@@ -7532,7 +8124,7 @@ var init_socket = __esm({
7532
8124
  }, Math.max(0, deadlineMs - Date.now()));
7533
8125
  sock.once("connect", () => {
7534
8126
  clearTimeout(timer);
7535
- resolve7(new _SubcSocket(sock));
8127
+ resolve13(new _SubcSocket(sock));
7536
8128
  });
7537
8129
  sock.once("error", (err) => {
7538
8130
  clearTimeout(timer);
@@ -7579,7 +8171,7 @@ var init_socket = __esm({
7579
8171
  }
7580
8172
  if (n === 0)
7581
8173
  return Promise.resolve(new Uint8Array(0));
7582
- return new Promise((resolve7, reject) => {
8174
+ return new Promise((resolve13, reject) => {
7583
8175
  let timer = null;
7584
8176
  if (Number.isFinite(deadlineMs)) {
7585
8177
  const remaining = deadlineMs - Date.now();
@@ -7592,7 +8184,7 @@ var init_socket = __esm({
7592
8184
  reject(new SocketTimeoutError(`timed out waiting for ${n} bytes`));
7593
8185
  }, remaining);
7594
8186
  }
7595
- this.waiter = { need: n, resolve: resolve7, reject, timer };
8187
+ this.waiter = { need: n, resolve: resolve13, reject, timer };
7596
8188
  this.tryServe();
7597
8189
  });
7598
8190
  }
@@ -7628,7 +8220,7 @@ var init_socket = __esm({
7628
8220
  let queued = false;
7629
8221
  let settled = false;
7630
8222
  let timer = null;
7631
- const completed = new Promise((resolve7, reject) => {
8223
+ const completed = new Promise((resolve13, reject) => {
7632
8224
  const settle = (run) => {
7633
8225
  if (settled)
7634
8226
  return;
@@ -7652,7 +8244,7 @@ var init_socket = __esm({
7652
8244
  if (err) {
7653
8245
  reject(new SocketWriteQueuedError("subc socket reported a write error after bytes were handed to the socket", err instanceof Error ? err : new Error(String(err))));
7654
8246
  } else {
7655
- resolve7();
8247
+ resolve13();
7656
8248
  }
7657
8249
  });
7658
8250
  });
@@ -7818,8 +8410,8 @@ function validate(info) {
7818
8410
  async function verifyOwnerOnly(path2) {
7819
8411
  if (process.platform === "win32")
7820
8412
  return;
7821
- const stat7 = await fs.stat(path2);
7822
- const mode = stat7.mode & 511;
8413
+ const stat8 = await fs.stat(path2);
8414
+ const mode = stat8.mode & 511;
7823
8415
  if ((mode & 63) !== 0) {
7824
8416
  throw new ConnectionFileError(`connection file ${path2} has insecure permissions 0o${mode.toString(8)}; expected owner-only 0600`);
7825
8417
  }
@@ -8009,7 +8601,7 @@ function normalizeConnectOptions(opts) {
8009
8601
  identity: opts.identity,
8010
8602
  targetKind: opts.targetKind ?? DEFAULT_MANAGED_TARGET_KIND,
8011
8603
  reconnectBackoff: opts.reconnectBackoff ?? DEFAULT_RECONNECT_BACKOFF,
8012
- sleep: opts.sleep ?? ((ms) => new Promise((resolve7) => setTimeout(resolve7, ms))),
8604
+ sleep: opts.sleep ?? ((ms) => new Promise((resolve13) => setTimeout(resolve13, ms))),
8013
8605
  routeOpenRetryDeadlineMs: opts.routeOpenRetryDeadlineMs ?? ROUTE_OPEN_RETRY_DEADLINE_MS,
8014
8606
  timeoutArbitrationGraceMs: opts.timeoutArbitrationGraceMs ?? TIMEOUT_ARBITRATION_GRACE_MS,
8015
8607
  livenessProbeWindowMs: opts.livenessProbeWindowMs ?? LIVENESS_PROBE_WINDOW_MS,
@@ -8323,15 +8915,15 @@ var init_client = __esm({
8323
8915
  const key = pendingKey(handle, corr);
8324
8916
  let subscriptionPending = null;
8325
8917
  let resolveClosed = null;
8326
- const closed = new Promise((resolve7, reject) => {
8918
+ const closed = new Promise((resolve13, reject) => {
8327
8919
  if (this.closedErr) {
8328
8920
  reject(this.closedErr);
8329
8921
  return;
8330
8922
  }
8331
- resolveClosed = resolve7;
8923
+ resolveClosed = resolve13;
8332
8924
  subscriptionPending = {
8333
8925
  handle,
8334
- resolve: () => resolve7(),
8926
+ resolve: () => resolve13(),
8335
8927
  reject,
8336
8928
  onProgress: onEvent,
8337
8929
  timer: null,
@@ -8457,11 +9049,11 @@ var init_client = __esm({
8457
9049
  const waiters = [];
8458
9050
  for (const pending of this.pending.values()) {
8459
9051
  if (pending.handle === handle && !pending.subscription) {
8460
- waiters.push(new Promise((resolve7) => {
9052
+ waiters.push(new Promise((resolve13) => {
8461
9053
  const previous = pending.onSettle;
8462
9054
  pending.onSettle = () => {
8463
9055
  previous?.();
8464
- resolve7();
9056
+ resolve13();
8465
9057
  };
8466
9058
  }));
8467
9059
  }
@@ -8515,11 +9107,11 @@ var init_client = __esm({
8515
9107
  const channel = handle?.channel ?? 0;
8516
9108
  const epoch = handle?.epoch ?? 0;
8517
9109
  const frame = buildFrame(FrameType.Request, buildFlags(binary, priority, false, admission), channel, epoch, corr, body);
8518
- return new Promise((resolve7, reject) => {
9110
+ return new Promise((resolve13, reject) => {
8519
9111
  const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
8520
9112
  const pending = {
8521
9113
  handle,
8522
- resolve: resolve7,
9114
+ resolve: resolve13,
8523
9115
  reject,
8524
9116
  onProgress,
8525
9117
  timer: null,
@@ -8606,11 +9198,11 @@ var init_client = __esm({
8606
9198
  }
8607
9199
  return this.outcomeUnknownCallError("connection dropped before the managed call returned a response", error);
8608
9200
  };
8609
- return new Promise((resolve7, reject) => {
9201
+ return new Promise((resolve13, reject) => {
8610
9202
  const ms = timeoutMs ?? DEFAULT_REQUEST_TIMEOUT_MS;
8611
9203
  const pending = {
8612
9204
  handle,
8613
- resolve: resolve7,
9205
+ resolve: resolve13,
8614
9206
  reject,
8615
9207
  onProgress,
8616
9208
  timer: null,
@@ -9185,7 +9777,7 @@ var init_dist = __esm({
9185
9777
  }
9186
9778
  });
9187
9779
 
9188
- // ../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/detect.js
9780
+ // ../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/detect.js
9189
9781
  import { readdirSync, statSync as statSync2 } from "node:fs";
9190
9782
  import { tmpdir, userInfo } from "node:os";
9191
9783
  import { join as join5 } from "node:path";
@@ -9265,7 +9857,7 @@ function listSubcConnectionFiles(dir) {
9265
9857
  }
9266
9858
  var PRODUCTION_FILE_NAME, TEMP_PREFIX, TEMP_SUFFIX;
9267
9859
  var init_detect = __esm({
9268
- "../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/detect.js"() {
9860
+ "../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/detect.js"() {
9269
9861
  init_dist();
9270
9862
  PRODUCTION_FILE_NAME = "subc-connection.json";
9271
9863
  TEMP_PREFIX = "subc-";
@@ -9273,89 +9865,395 @@ var init_detect = __esm({
9273
9865
  }
9274
9866
  });
9275
9867
 
9276
- // ../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/identity.js
9277
- import { createHash as createHash5 } from "node:crypto";
9278
- import { existsSync as existsSync2, realpathSync } from "node:fs";
9279
- import { dirname as dirname7, relative, resolve as resolve2 } from "node:path";
9280
- function storageFingerprint(storagePath) {
9281
- const absolutePath = storagePath;
9282
- let canonicalPath;
9868
+ // ../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/identity.js
9869
+ import { createHash as createHash5 } from "node:crypto";
9870
+ import { existsSync as existsSync2, realpathSync } from "node:fs";
9871
+ import { dirname as dirname9, relative, resolve as resolve4 } from "node:path";
9872
+ function storageFingerprint(storagePath) {
9873
+ const absolutePath = storagePath;
9874
+ let canonicalPath;
9875
+ try {
9876
+ canonicalPath = realpathSync(absolutePath);
9877
+ } catch (error) {
9878
+ if (error.code !== "ENOENT")
9879
+ throw error;
9880
+ let ancestor = absolutePath;
9881
+ while (!existsSync2(ancestor)) {
9882
+ const parent = dirname9(ancestor);
9883
+ if (parent === ancestor)
9884
+ break;
9885
+ ancestor = parent;
9886
+ }
9887
+ canonicalPath = resolve4(realpathSync(ancestor), relative(ancestor, absolutePath));
9888
+ }
9889
+ return createHash5("sha256").update(canonicalPath).digest("hex");
9890
+ }
9891
+ function storeIdentity(projectRoot, storagePath) {
9892
+ return {
9893
+ project_root: projectRoot,
9894
+ harness: "opencode",
9895
+ session: `store-${storageFingerprint(storagePath)}`
9896
+ };
9897
+ }
9898
+ var init_identity2 = __esm({
9899
+ "../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/identity.js"() {
9900
+ }
9901
+ });
9902
+
9903
+ // ../../node_modules/.bun/@cortexkit+store@0.2.2/node_modules/@cortexkit/store/dist/descriptor.js
9904
+ var init_descriptor = __esm({
9905
+ "../../node_modules/.bun/@cortexkit+store@0.2.2/node_modules/@cortexkit/store/dist/descriptor.js"() {
9906
+ }
9907
+ });
9908
+
9909
+ // ../../node_modules/.bun/@cortexkit+store@0.2.2/node_modules/@cortexkit/store/dist/derivation.js
9910
+ var textEncoder;
9911
+ var init_derivation = __esm({
9912
+ "../../node_modules/.bun/@cortexkit+store@0.2.2/node_modules/@cortexkit/store/dist/derivation.js"() {
9913
+ textEncoder = new TextEncoder();
9914
+ }
9915
+ });
9916
+
9917
+ // ../../node_modules/.bun/@cortexkit+store@0.2.2/node_modules/@cortexkit/store/dist/windows-private-files.js
9918
+ async function withWindowsPrivateFiles(operation) {
9919
+ let api;
9920
+ try {
9921
+ api = await import("@cortexkit/private-files");
9922
+ } catch (cause) {
9923
+ throw new Error("@cortexkit/private-files is unavailable; refusing the Windows private operation", { cause });
9924
+ }
9925
+ try {
9926
+ return await operation(api);
9927
+ } catch (cause) {
9928
+ if (cause instanceof api.PrivateFilesUnavailableError) {
9929
+ throw new Error(`@cortexkit/private-files native addon is unavailable; refusing the Windows private operation: ${cause.message}`, { cause });
9930
+ }
9931
+ throw cause;
9932
+ }
9933
+ }
9934
+ var init_windows_private_files = __esm({
9935
+ "../../node_modules/.bun/@cortexkit+store@0.2.2/node_modules/@cortexkit/store/dist/windows-private-files.js"() {
9936
+ }
9937
+ });
9938
+
9939
+ // ../../node_modules/.bun/@cortexkit+store@0.2.2/node_modules/@cortexkit/store/dist/owner-only-path.js
9940
+ import * as fsAsync from "node:fs/promises";
9941
+ import { posix, win32 } from "node:path";
9942
+ function* realpath4(path2) {
9943
+ return yield { kind: "realpath", path: path2 };
9944
+ }
9945
+ function* metadata(kind, path2) {
9946
+ return yield { kind, path: path2 };
9947
+ }
9948
+ function* accountFile(path2) {
9949
+ return yield { kind: "readFile", path: path2 };
9950
+ }
9951
+ function refused(path2, reason) {
9952
+ return { ok: false, reason, path: path2 };
9953
+ }
9954
+ function isMissing(error) {
9955
+ return error?.code === "ENOENT";
9956
+ }
9957
+ function* resolveTarget(input, paths) {
9958
+ if (!input || input.includes("\0"))
9959
+ throw new Error("invalid path");
9960
+ let candidate = paths.isAbsolute(input) ? input : `${process.cwd()}${paths.sep}${input}`;
9961
+ const suffix = [];
9962
+ for (; ; ) {
9963
+ try {
9964
+ const existing = yield* realpath4(candidate);
9965
+ if (suffix.length && !(yield* metadata("stat", existing)).isDirectory()) {
9966
+ throw new Error("nearest existing ancestor is not a directory");
9967
+ }
9968
+ return { resolved: paths.join(existing, ...suffix), existing, missing: suffix.length > 0 };
9969
+ } catch (error) {
9970
+ if (!isMissing(error))
9971
+ throw error;
9972
+ try {
9973
+ yield* metadata("lstat", candidate);
9974
+ } catch (linkError) {
9975
+ if (!isMissing(linkError))
9976
+ throw linkError;
9977
+ const parent = paths.dirname(candidate);
9978
+ if (parent === candidate)
9979
+ throw error;
9980
+ suffix.unshift(paths.basename(candidate));
9981
+ candidate = parent;
9982
+ continue;
9983
+ }
9984
+ throw error;
9985
+ }
9986
+ }
9987
+ }
9988
+ async function checkWindows(input, io) {
9989
+ let candidate = input;
9990
+ let missing = false;
9991
+ try {
9992
+ if (!input || input.includes("\0") || !win32.isAbsolute(input))
9993
+ throw new Error("expected an absolute Windows path");
9994
+ for (; ; ) {
9995
+ let entry;
9996
+ try {
9997
+ entry = await io.lstat(candidate);
9998
+ } catch (error) {
9999
+ if (!isMissing(error))
10000
+ throw error;
10001
+ const parent = win32.dirname(candidate);
10002
+ if (parent === candidate)
10003
+ throw error;
10004
+ candidate = parent;
10005
+ missing = true;
10006
+ continue;
10007
+ }
10008
+ if (missing && !entry.isDirectory())
10009
+ throw new Error("nearest existing ancestor is not a directory");
10010
+ await withWindowsPrivateFiles((api) => api.verifyPrivatePath(candidate, entry.isDirectory() ? "directory" : "file"));
10011
+ return { ok: true };
10012
+ }
10013
+ } catch (error) {
10014
+ return refused(candidate, `Windows private-path verification refused: ${error instanceof Error ? error.message : String(error)}`);
10015
+ }
10016
+ }
10017
+ function accountRecords(bytes, count3) {
10018
+ const text2 = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
10019
+ const id = (value) => value !== void 0 && /^\d+$/.test(value) && Number.isSafeInteger(Number(value)) && Number(value) <= 4294967295;
10020
+ return text2.split("\n").filter((line) => line.trim() !== "" && !line.trimStart().startsWith("#")).map((line) => {
10021
+ const fields = line.split(":");
10022
+ if (fields.length !== count3 || !fields[0] || /\s/.test(fields[0]) || !id(fields[2]) || count3 === 7 && !id(fields[3]))
10023
+ throw new Error("malformed account record");
10024
+ if (count3 === 4 && fields[3] !== "" && fields[3].split(",").some((name) => !name || /\s/.test(name))) {
10025
+ throw new Error("malformed group members");
10026
+ }
10027
+ return fields;
10028
+ });
10029
+ }
10030
+ function* privateGroupReason(euid, egid) {
10031
+ const records = [];
10032
+ for (const [path2, count3] of [["/etc/passwd", 7], ["/etc/group", 4]]) {
10033
+ let bytes;
10034
+ try {
10035
+ bytes = yield* accountFile(path2);
10036
+ } catch {
10037
+ return `could not read ${path2} to establish a user-private group`;
10038
+ }
10039
+ try {
10040
+ records.push(accountRecords(bytes, count3));
10041
+ } catch {
10042
+ return `could not parse ${path2} to establish a user-private group`;
10043
+ }
10044
+ }
10045
+ const [passwd, groups] = records;
10046
+ const users = passwd.filter((entry) => Number(entry[2]) === euid);
10047
+ const matchingGroups = groups.filter((entry) => Number(entry[2]) === egid);
10048
+ if (users.length !== 1 || matchingGroups.length !== 1) {
10049
+ return "group-writable ancestor (effective user or group is absent or ambiguous in account files)";
10050
+ }
10051
+ const name = users[0][0];
10052
+ if (matchingGroups[0][3] !== "" && matchingGroups[0][3].split(",").some((member) => member !== name)) {
10053
+ return "group-writable ancestor (other group members)";
10054
+ }
10055
+ if (passwd.some((entry) => Number(entry[2]) !== euid && Number(entry[3]) === egid)) {
10056
+ return "group-writable ancestor (another user's primary group)";
10057
+ }
10058
+ return void 0;
10059
+ }
10060
+ function* checkUnix(input, euid, egid) {
10061
+ if (euid == null)
10062
+ return refused(input, "could not determine effective uid");
10063
+ let current;
10064
+ try {
10065
+ const target = yield* resolveTarget(input, posix);
10066
+ current = target.missing || (yield* metadata("stat", target.existing)).isDirectory() ? target.existing : posix.dirname(target.existing);
10067
+ } catch {
10068
+ return refused(input, "could not resolve target or its nearest existing ancestor");
10069
+ }
10070
+ let child;
10071
+ let groupProof;
10072
+ let groupChecked = false;
10073
+ for (; ; ) {
10074
+ let entries;
10075
+ try {
10076
+ entries = [yield* metadata("lstat", current), yield* metadata("stat", current)];
10077
+ } catch {
10078
+ return refused(current, "could not inspect ancestor");
10079
+ }
10080
+ for (const entry of entries) {
10081
+ if (!entry.isDirectory())
10082
+ return refused(current, "ancestor is not a directory");
10083
+ if (entry.uid !== euid && entry.uid !== 0)
10084
+ return refused(current, "foreign owner");
10085
+ if ((entry.mode & 18) === 0)
10086
+ continue;
10087
+ if (entry.uid === 0 && (entry.mode & 512) !== 0) {
10088
+ if (child?.every((value) => value.uid === euid && (value.mode & 18) === 0))
10089
+ continue;
10090
+ return refused(current, "sticky ancestor without an owner-only child");
10091
+ }
10092
+ if ((entry.mode & 2) !== 0)
10093
+ return refused(current, "world-writable ancestor");
10094
+ if ((entry.mode & 512) !== 0 || entry.uid !== euid || egid == null || entry.gid !== egid) {
10095
+ return refused(current, "group-writable ancestor (not a non-sticky user-private group)");
10096
+ }
10097
+ if (!groupChecked) {
10098
+ groupProof = yield* privateGroupReason(euid, egid);
10099
+ groupChecked = true;
10100
+ }
10101
+ if (groupProof)
10102
+ return refused(current, groupProof);
10103
+ }
10104
+ const parent = posix.dirname(current);
10105
+ if (parent === current)
10106
+ return { ok: true };
10107
+ child = entries;
10108
+ current = parent;
10109
+ }
10110
+ }
10111
+ function policy(input, options) {
10112
+ return checkUnix(input, options.euid === void 0 ? process.geteuid?.() : options.euid, options.egid === void 0 ? process.getegid?.() : options.egid);
10113
+ }
10114
+ async function checkOwnerOnlyPathAsync(input, options = {}) {
10115
+ const io = {
10116
+ realpath: fsAsync.realpath,
10117
+ lstat: fsAsync.lstat,
10118
+ stat: fsAsync.stat,
10119
+ readFile: fsAsync.readFile,
10120
+ ...options.fs
10121
+ };
10122
+ if ((options.platform ?? process.platform) === "win32")
10123
+ return checkWindows(input, io);
10124
+ const check = policy(input, options);
10125
+ let step = check.next();
10126
+ while (!step.done) {
10127
+ const { kind, path: path2 } = step.value;
10128
+ let value;
10129
+ try {
10130
+ value = await io[kind](path2);
10131
+ } catch (error) {
10132
+ step = check.throw(error);
10133
+ continue;
10134
+ }
10135
+ step = check.next(value);
10136
+ }
10137
+ return step.value;
10138
+ }
10139
+ var init_owner_only_path = __esm({
10140
+ "../../node_modules/.bun/@cortexkit+store@0.2.2/node_modules/@cortexkit/store/dist/owner-only-path.js"() {
10141
+ init_windows_private_files();
10142
+ }
10143
+ });
10144
+
10145
+ // ../../node_modules/.bun/@cortexkit+store@0.2.2/node_modules/@cortexkit/store/dist/private-write.js
10146
+ import { mkdir as mkdir8, open as open6, realpath as realpath5, rmdir } from "node:fs/promises";
10147
+ import { dirname as dirname10 } from "node:path";
10148
+ function refusal3(result) {
10149
+ return new Error(`Private creation refused: ${result.reason}: ${result.path}`);
10150
+ }
10151
+ async function checkUnixParent(path2) {
10152
+ const result = await checkOwnerOnlyPathAsync(dirname10(path2));
10153
+ if (!result.ok)
10154
+ throw refusal3(result);
10155
+ }
10156
+ async function createPrivateFile(path2, bytes = "") {
10157
+ if (process.platform === "win32") {
10158
+ return withWindowsPrivateFiles((api) => api.createPrivateFile(path2, bytes));
10159
+ }
10160
+ await checkUnixParent(path2);
10161
+ const handle = await open6(path2, "wx", 384);
9283
10162
  try {
9284
- canonicalPath = realpathSync(absolutePath);
9285
- } catch (error) {
9286
- if (error.code !== "ENOENT")
9287
- throw error;
9288
- let ancestor = absolutePath;
9289
- while (!existsSync2(ancestor)) {
9290
- const parent = dirname7(ancestor);
9291
- if (parent === ancestor)
9292
- break;
9293
- ancestor = parent;
9294
- }
9295
- canonicalPath = resolve2(realpathSync(ancestor), relative(ancestor, absolutePath));
10163
+ await handle.writeFile(bytes);
10164
+ } finally {
10165
+ await handle.close();
9296
10166
  }
9297
- return createHash5("sha256").update(canonicalPath).digest("hex");
9298
10167
  }
9299
- function storeIdentity(projectRoot, storagePath) {
9300
- return {
9301
- project_root: projectRoot,
9302
- harness: "opencode",
9303
- session: `store-${storageFingerprint(storagePath)}`
9304
- };
10168
+ async function createPrivateDirectory(path2) {
10169
+ if (process.platform === "win32") {
10170
+ return withWindowsPrivateFiles((api) => api.createPrivateDirectory(path2));
10171
+ }
10172
+ const parent = await checkOwnerOnlyPathAsync(dirname10(path2));
10173
+ let stickyParent = false;
10174
+ if (!parent.ok) {
10175
+ stickyParent = parent.reason === STICKY_WITHOUT_CHILD && parent.path === await realpath5(dirname10(path2)).catch(() => void 0);
10176
+ if (!stickyParent)
10177
+ throw refusal3(parent);
10178
+ }
10179
+ await mkdir8(path2, { mode: 448 });
10180
+ if (!stickyParent)
10181
+ return;
10182
+ const created = await checkOwnerOnlyPathAsync(path2);
10183
+ if (!created.ok) {
10184
+ await rmdir(path2).catch(() => void 0);
10185
+ throw refusal3(created);
10186
+ }
9305
10187
  }
9306
- var init_identity2 = __esm({
9307
- "../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/identity.js"() {
10188
+ var STICKY_WITHOUT_CHILD;
10189
+ var init_private_write = __esm({
10190
+ "../../node_modules/.bun/@cortexkit+store@0.2.2/node_modules/@cortexkit/store/dist/private-write.js"() {
10191
+ init_owner_only_path();
10192
+ init_windows_private_files();
10193
+ STICKY_WITHOUT_CHILD = "sticky ancestor without an owner-only child";
10194
+ }
10195
+ });
10196
+
10197
+ // ../../node_modules/.bun/@cortexkit+store@0.2.2/node_modules/@cortexkit/store/dist/index.js
10198
+ var init_dist2 = __esm({
10199
+ "../../node_modules/.bun/@cortexkit+store@0.2.2/node_modules/@cortexkit/store/dist/index.js"() {
10200
+ init_descriptor();
10201
+ init_derivation();
10202
+ init_owner_only_path();
10203
+ init_private_write();
9308
10204
  }
9309
10205
  });
9310
10206
 
9311
- // ../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/ancestor-permissions.js
10207
+ // ../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/private-path.js
9312
10208
  import { AsyncLocalStorage as AsyncLocalStorage2 } from "node:async_hooks";
9313
- import { readFile as readFile6 } from "node:fs/promises";
9314
- function records(source, count3) {
9315
- return source.split("\n").filter((line) => line.trim() !== "" && !line.trimStart().startsWith("#")).map((line) => {
9316
- const fields = line.split(":");
9317
- if (fields.length !== count3 || !fields[0] || /\s/.test(fields[0]) || !/^\d+$/.test(fields[2]) || !Number.isSafeInteger(Number(fields[2])) || Number(fields[2]) > 4294967295 || count3 === 7 && (!/^\d+$/.test(fields[3]) || !Number.isSafeInteger(Number(fields[3])) || Number(fields[3]) > 4294967295)) {
9318
- throw new Error("malformed account record");
9319
- }
9320
- if (count3 === 4 && fields[3] !== "" && fields[3].split(",").some((name) => name === "" || /\s/.test(name)))
9321
- throw new Error("malformed group members");
9322
- return fields;
9323
- });
9324
- }
9325
- async function acceptsAncestor(metadata, identity = ancestorIdentityContext.getStore() ?? {
9326
- euid: process.geteuid?.(),
9327
- egid: process.getegid?.(),
9328
- passwdPath: "/etc/passwd",
9329
- groupPath: "/etc/group"
9330
- }) {
9331
- if ((metadata.mode & 18) === 0 || (metadata.mode & 512) !== 0)
9332
- return true;
9333
- if ((metadata.mode & 2) !== 0 || identity.euid === void 0 || identity.egid === void 0 || metadata.uid !== identity.euid || metadata.gid !== identity.egid)
9334
- return false;
10209
+ import { stat as stat5 } from "node:fs/promises";
10210
+ import { dirname as dirname11, resolve as resolve5 } from "node:path";
10211
+ function notPrivate(subject, result) {
10212
+ return `${subject} ${result.path} is not private: ${result.reason}`;
10213
+ }
10214
+ function privateCreationCode(error) {
10215
+ const value = error;
10216
+ if (value?.code === "ERR_PRIVATE_FILES_SECURITY" && value.reason === "io-error") {
10217
+ if (value.win32Code === 80 || value.win32Code === 183)
10218
+ return "EEXIST";
10219
+ if (value.win32Code === 2 || value.win32Code === 3)
10220
+ return "ENOENT";
10221
+ }
10222
+ return value?.code;
10223
+ }
10224
+ async function createPrivateParents(path2) {
9335
10225
  try {
9336
- const passwd = records(new TextDecoder("utf-8", { fatal: true }).decode(await readFile6(identity.passwdPath)), 7);
9337
- const groups = records(new TextDecoder("utf-8", { fatal: true }).decode(await readFile6(identity.groupPath)), 4);
9338
- const users = passwd.filter((entry) => Number(entry[2]) === identity.euid);
9339
- const matchingGroups = groups.filter((entry) => Number(entry[2]) === identity.egid);
9340
- if (users.length !== 1 || matchingGroups.length !== 1)
9341
- return false;
9342
- const name = users[0][0];
9343
- return (matchingGroups[0][3] === "" || matchingGroups[0][3].split(",").every((member) => member === name)) && !passwd.some((entry) => Number(entry[2]) !== identity.euid && Number(entry[3]) === identity.egid);
9344
- } catch {
9345
- return false;
10226
+ await stat5(path2);
10227
+ return;
10228
+ } catch (error) {
10229
+ if (error.code !== "ENOENT")
10230
+ throw error;
10231
+ }
10232
+ const parent = dirname11(path2);
10233
+ if (parent !== path2)
10234
+ await createPrivateParents(parent);
10235
+ try {
10236
+ await createPrivateDirectory(path2);
10237
+ } catch (error) {
10238
+ if (privateCreationCode(error) !== "EEXIST")
10239
+ throw error;
10240
+ if (!(await stat5(path2)).isDirectory())
10241
+ throw error;
9346
10242
  }
9347
10243
  }
9348
- var ancestorIdentityContext;
9349
- var init_ancestor_permissions = __esm({
9350
- "../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/ancestor-permissions.js"() {
9351
- ancestorIdentityContext = new AsyncLocalStorage2();
10244
+ var privatePathContext, checkPrivatePath;
10245
+ var init_private_path = __esm({
10246
+ "../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/private-path.js"() {
10247
+ init_dist2();
10248
+ privatePathContext = new AsyncLocalStorage2();
10249
+ checkPrivatePath = (path2, options) => checkOwnerOnlyPathAsync(resolve5(path2), privatePathContext.getStore() ?? options);
9352
10250
  }
9353
10251
  });
9354
10252
 
9355
- // ../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/enrollment.js
10253
+ // ../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/enrollment.js
9356
10254
  import { randomBytes as randomBytes3 } from "node:crypto";
9357
- import { chmod as chmod2, mkdir as mkdir8, open as open5, realpath as realpath3, rename as rename5, stat as stat4, unlink as unlink5 } from "node:fs/promises";
9358
- import { basename as basename3, dirname as dirname8, join as join6 } from "node:path";
10255
+ import { open as open7, rename as rename6, unlink as unlink6 } from "node:fs/promises";
10256
+ import { basename as basename3, dirname as dirname12, join as join6, resolve as resolve6 } from "node:path";
9359
10257
  function validateTokenFile(value) {
9360
10258
  if (!TOKEN_RE.test(value.token))
9361
10259
  throw new Error("enrollment token must be exactly 64 lowercase hex characters");
@@ -9364,61 +10262,57 @@ function validateTokenFile(value) {
9364
10262
  }
9365
10263
  }
9366
10264
  async function refuseWritableAncestor(parent) {
9367
- let component;
9368
- try {
9369
- component = await realpath3(parent);
9370
- } catch {
9371
- return;
9372
- }
9373
- for (; ; ) {
9374
- const metadata = await stat4(component).catch(() => void 0);
9375
- if (metadata && !await acceptsAncestor(metadata)) {
9376
- throw new Error(`enrollment token ancestor ${component} is group- or world-writable without sticky bit`);
9377
- }
9378
- const next = dirname8(component);
9379
- if (next === component)
9380
- return;
9381
- component = next;
9382
- }
10265
+ const result = await checkPrivatePath(parent);
10266
+ if (!result.ok)
10267
+ throw new Error(notPrivate("enrollment token folder", result));
9383
10268
  }
9384
10269
  async function writeEnrollmentTokenFile(path2, value) {
9385
10270
  validateTokenFile(value);
9386
- const parent = dirname8(path2);
9387
- await mkdir8(parent, { recursive: true, mode: 448 });
10271
+ path2 = resolve6(path2);
10272
+ const parent = dirname12(path2);
10273
+ if (process.platform !== "win32")
10274
+ await refuseWritableAncestor(parent);
10275
+ await createPrivateParents(parent);
9388
10276
  await refuseWritableAncestor(parent);
9389
10277
  const temporary = join6(parent, `.${basename3(path2)}.${process.pid}.${randomBytes3(12).toString("hex")}.tmp`);
9390
10278
  let created = false;
9391
10279
  try {
9392
- const descriptor = await open5(temporary, "wx", 384);
9393
10280
  created = true;
9394
10281
  try {
9395
- await descriptor.writeFile(`${JSON.stringify(value)}
9396
- `, "utf8");
10282
+ await createPrivateFile(temporary, `${JSON.stringify(value)}
10283
+ `);
10284
+ } catch (error) {
10285
+ if (privateCreationCode(error) === "EEXIST")
10286
+ created = false;
10287
+ throw error;
10288
+ }
10289
+ const descriptor = await open7(temporary, "r+");
10290
+ try {
9397
10291
  await descriptor.sync();
9398
- await chmod2(temporary, 384);
9399
10292
  } finally {
9400
10293
  await descriptor.close();
9401
10294
  }
9402
- await rename5(temporary, path2);
10295
+ await rename6(temporary, path2);
9403
10296
  created = false;
9404
10297
  } finally {
9405
10298
  if (created)
9406
- await unlink5(temporary).catch(() => void 0);
10299
+ await unlink6(temporary).catch(() => void 0);
9407
10300
  }
9408
10301
  }
9409
10302
  var TOKEN_RE;
9410
10303
  var init_enrollment = __esm({
9411
- "../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/enrollment.js"() {
9412
- init_ancestor_permissions();
10304
+ "../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/enrollment.js"() {
10305
+ init_dist2();
10306
+ init_private_path();
9413
10307
  TOKEN_RE = /^[0-9a-f]{64}$/;
9414
10308
  }
9415
10309
  });
9416
10310
 
9417
- // ../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/handles.js
10311
+ // ../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/handles.js
9418
10312
  var HANDLE_FILE_CONTRACT;
9419
10313
  var init_handles = __esm({
9420
- "../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/handles.js"() {
9421
- init_ancestor_permissions();
10314
+ "../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/handles.js"() {
10315
+ init_private_path();
9422
10316
  HANDLE_FILE_CONTRACT = {
9423
10317
  maxBytes: 256 * 1024,
9424
10318
  mode: 384,
@@ -9430,15 +10324,16 @@ var init_handles = __esm({
9430
10324
  }
9431
10325
  });
9432
10326
 
9433
- // ../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/manifest-lock.js
10327
+ // ../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/manifest-lock.js
9434
10328
  var init_manifest_lock = __esm({
9435
- "../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/manifest-lock.js"() {
9436
- init_ancestor_permissions();
10329
+ "../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/manifest-lock.js"() {
10330
+ init_dist2();
10331
+ init_private_path();
9437
10332
  init_handles();
9438
10333
  }
9439
10334
  });
9440
10335
 
9441
- // ../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/errors.js
10336
+ // ../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/errors.js
9442
10337
  function isRecord6(value) {
9443
10338
  return typeof value === "object" && value !== null && !Array.isArray(value);
9444
10339
  }
@@ -9475,7 +10370,7 @@ function hasCredentialError(response) {
9475
10370
  }
9476
10371
  var ERROR_CLASS_WIRE_SET, ClaustrumCredentialError;
9477
10372
  var init_errors2 = __esm({
9478
- "../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/errors.js"() {
10373
+ "../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/errors.js"() {
9479
10374
  ERROR_CLASS_WIRE_SET = [
9480
10375
  "transient",
9481
10376
  "permanent",
@@ -9497,7 +10392,7 @@ var init_errors2 = __esm({
9497
10392
  }
9498
10393
  });
9499
10394
 
9500
- // ../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/wire.js
10395
+ // ../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/wire.js
9501
10396
  function isRecord7(value) {
9502
10397
  return typeof value === "object" && value !== null && !Array.isArray(value);
9503
10398
  }
@@ -9598,7 +10493,15 @@ function decodeScopedInventory(response, logUnknownClass) {
9598
10493
  const createdAtMs = row.created_at_ms === void 0 || row.created_at_ms === null ? null : typeof row.created_at_ms === "number" && Number.isFinite(row.created_at_ms) ? row.created_at_ms : void 0;
9599
10494
  if (createdAtMs === void 0)
9600
10495
  throw asCredentialError(response, "invalid_response", logUnknownClass);
10496
+ const planTier = row.plan_tier;
10497
+ if (planTier !== void 0 && (typeof planTier !== "string" || !/^[a-z][a-z0-9_]{0,31}(?![\s\S])/.test(planTier))) {
10498
+ throw asCredentialError(response, "invalid_response", logUnknownClass);
10499
+ }
9601
10500
  const authMethod = row.auth_method;
10501
+ const planTierSource = row.plan_tier_source;
10502
+ if (planTierSource !== void 0 && planTierSource !== "operator" && planTierSource !== "detected") {
10503
+ throw asCredentialError(response, "invalid_response", logUnknownClass);
10504
+ }
9602
10505
  if (authMethod !== void 0 && authMethod !== "apikey" && authMethod !== "chatgpt" && authMethod !== "antigravity" && authMethod !== "oauth") {
9603
10506
  throw asCredentialError(response, "invalid_response", logUnknownClass);
9604
10507
  }
@@ -9619,6 +10522,8 @@ function decodeScopedInventory(response, logUnknownClass) {
9619
10522
  // no ids set. A present non-array is a malformed reply and still refuses.
9620
10523
  providerIds: row.provider_ids === void 0 ? [] : strings(row.provider_ids),
9621
10524
  authMethod,
10525
+ planTier,
10526
+ planTierSource,
9622
10527
  state: row.state,
9623
10528
  refreshAdapter: row.refresh_adapter,
9624
10529
  recordVersion,
@@ -9656,7 +10561,7 @@ function decodeEnrollmentPoll(response, logUnknownClass) {
9656
10561
  }
9657
10562
  var CLAUSTRUM_MODULE_ID, RECONNECT_BACKOFF_MS, ClaustrumClient;
9658
10563
  var init_wire = __esm({
9659
- "../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/wire.js"() {
10564
+ "../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/wire.js"() {
9660
10565
  init_dist();
9661
10566
  init_detect();
9662
10567
  init_errors2();
@@ -9902,9 +10807,9 @@ var init_wire = __esm({
9902
10807
  }
9903
10808
  });
9904
10809
 
9905
- // ../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/index.js
9906
- var init_dist2 = __esm({
9907
- "../../node_modules/.bun/@cortexkit+claustrum-client@0.6.2/node_modules/@cortexkit/claustrum-client/dist/index.js"() {
10810
+ // ../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/index.js
10811
+ var init_dist3 = __esm({
10812
+ "../../node_modules/.bun/@cortexkit+claustrum-client@0.9.0/node_modules/@cortexkit/claustrum-client/dist/index.js"() {
9908
10813
  init_detect();
9909
10814
  init_identity2();
9910
10815
  init_enrollment();
@@ -9974,10 +10879,10 @@ var init_errors3 = __esm({
9974
10879
  });
9975
10880
 
9976
10881
  // ../core/dist/common-auth-embedded/claustrum/enrollment.js
9977
- import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID9 } from "node:crypto";
10882
+ import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID10 } from "node:crypto";
9978
10883
  import { constants as fsConstants } from "node:fs";
9979
- import { chmod as chmod3, mkdir as mkdir9, open as open6, readFile as readFile7, realpath as realpath4, rename as rename6, stat as stat5, unlink as unlink6 } from "node:fs/promises";
9980
- import { basename as basename4, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join7, resolve as resolve3 } from "node:path";
10884
+ import { chmod as chmod2, mkdir as mkdir9, open as open8, readFile as readFile7, realpath as realpath6, rename as rename7, stat as stat6, unlink as unlink7 } from "node:fs/promises";
10885
+ import { basename as basename4, dirname as dirname13, extname, isAbsolute as isAbsolute2, join as join7, resolve as resolve7 } from "node:path";
9981
10886
  function classifyEnrollmentError(error) {
9982
10887
  if (!(error instanceof ClaustrumCredentialError))
9983
10888
  return void 0;
@@ -10002,7 +10907,7 @@ function getClaustrumEnrollmentPaths(tokenPath) {
10002
10907
  const extension = extname(tokenPath) || ".json";
10003
10908
  const stem = basename4(tokenPath, extname(tokenPath));
10004
10909
  return {
10005
- statePath: join7(dirname9(tokenPath), `${stem}-state${extension}`),
10910
+ statePath: join7(dirname13(tokenPath), `${stem}-state${extension}`),
10006
10911
  tokenPath
10007
10912
  };
10008
10913
  }
@@ -10010,7 +10915,7 @@ function hostEnrollmentPaths(input) {
10010
10915
  const override = input.override?.trim();
10011
10916
  if (override && !isAbsolute2(override) && !input.cwd)
10012
10917
  throw new ClaustrumConsumerError("invalid-state", "A relative Claustrum enrollment override needs a base directory");
10013
- const tokenPath = override ? isAbsolute2(override) ? override : resolve3(input.cwd, override) : join7(input.stateDir, `${input.host}-enrollment.json`);
10918
+ const tokenPath = override ? isAbsolute2(override) ? override : resolve7(input.cwd, override) : join7(input.stateDir, `${input.host}-enrollment.json`);
10014
10919
  return getClaustrumEnrollmentPaths(tokenPath);
10015
10920
  }
10016
10921
  function isRecord8(value) {
@@ -10085,15 +10990,15 @@ function decodeTokenFile(value) {
10085
10990
  token_generation: value.token_generation
10086
10991
  };
10087
10992
  }
10088
- function validateReadableSecretFile(metadata) {
10089
- if (!metadata.isFile()) {
10993
+ function validateReadableSecretFile(metadata2) {
10994
+ if (!metadata2.isFile()) {
10090
10995
  throw new ClaustrumConsumerError("unsafe-file", "Claustrum enrollment file must be a regular file");
10091
10996
  }
10092
- if ((metadata.mode & 63) !== 0) {
10997
+ if ((metadata2.mode & 63) !== 0) {
10093
10998
  throw new ClaustrumConsumerError("unsafe-file", "Claustrum enrollment file must be owner-only");
10094
10999
  }
10095
11000
  const expectedUid = process.geteuid?.();
10096
- if (expectedUid !== void 0 && metadata.uid !== expectedUid) {
11001
+ if (expectedUid !== void 0 && metadata2.uid !== expectedUid) {
10097
11002
  throw new ClaustrumConsumerError("unsafe-file", "Claustrum enrollment file must be owned by the current user");
10098
11003
  }
10099
11004
  }
@@ -10105,9 +11010,23 @@ function parseSecretJson(text2) {
10105
11010
  }
10106
11011
  }
10107
11012
  async function readBoundedJson(path2) {
11013
+ if (windowsPrivateFiles) {
11014
+ try {
11015
+ await ensurePrivateDirectory(dirname13(path2));
11016
+ const text2 = await readPrivateText(path2, true);
11017
+ if (Buffer.byteLength(text2) > ENROLLMENT_FILE_MAX_BYTES) {
11018
+ throw new ClaustrumConsumerError("unsafe-file", "Claustrum enrollment file is too large");
11019
+ }
11020
+ return parseSecretJson(text2);
11021
+ } catch (error) {
11022
+ if (error.code === "ENOENT")
11023
+ return void 0;
11024
+ throw error;
11025
+ }
11026
+ }
10108
11027
  let descriptor;
10109
11028
  try {
10110
- descriptor = await open6(path2, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
11029
+ descriptor = await open8(path2, fsConstants.O_RDONLY | fsConstants.O_NOFOLLOW);
10111
11030
  } catch (error) {
10112
11031
  if (error.code === "ENOENT")
10113
11032
  return void 0;
@@ -10125,17 +11044,17 @@ async function readBoundedJson(path2) {
10125
11044
  await descriptor.close();
10126
11045
  }
10127
11046
  }
10128
- function accountRecords(text2, fields) {
10129
- const records2 = [];
11047
+ function accountRecords2(text2, fields) {
11048
+ const records = [];
10130
11049
  for (const line of text2.split("\n")) {
10131
11050
  if (line.trim() === "" || line.startsWith("#"))
10132
11051
  continue;
10133
11052
  const parts = line.split(":");
10134
11053
  if (parts.length !== fields || !/^[^\s:,]+$/.test(parts[0] ?? "") || !/^\d+$/.test(parts[2] ?? "") || !Number.isSafeInteger(Number(parts[2])) || fields === 7 && (!/^\d+$/.test(parts[3] ?? "") || !Number.isSafeInteger(Number(parts[3]))) || fields === 4 && parts[3] !== "" && !/^[^\s:,]+(?:,[^\s:,]+)*$/.test(parts[3] ?? ""))
10135
11054
  return void 0;
10136
- records2.push(parts);
11055
+ records.push(parts);
10137
11056
  }
10138
- return records2;
11057
+ return records;
10139
11058
  }
10140
11059
  async function isPrivateGroup(uid, gid, options) {
10141
11060
  try {
@@ -10143,8 +11062,8 @@ async function isPrivateGroup(uid, gid, options) {
10143
11062
  readFile7(options.passwdPath ?? "/etc/passwd", "utf8"),
10144
11063
  readFile7(options.groupPath ?? "/etc/group", "utf8")
10145
11064
  ]);
10146
- const users = accountRecords(passwdText, 7);
10147
- const groups = accountRecords(groupText, 4);
11065
+ const users = accountRecords2(passwdText, 7);
11066
+ const groups = accountRecords2(groupText, 4);
10148
11067
  if (!users || !groups)
10149
11068
  return false;
10150
11069
  const owners = users.filter((user) => Number(user[2]) === uid);
@@ -10158,71 +11077,95 @@ async function isPrivateGroup(uid, gid, options) {
10158
11077
  return false;
10159
11078
  }
10160
11079
  }
11080
+ function ancestorPolicyOptions(options) {
11081
+ if (!options.passwdPath && !options.groupPath)
11082
+ return void 0;
11083
+ return {
11084
+ fs: {
11085
+ readFile: (path2) => readFile7(path2 === "/etc/passwd" ? options.passwdPath ?? path2 : path2 === "/etc/group" ? options.groupPath ?? path2 : path2)
11086
+ }
11087
+ };
11088
+ }
10161
11089
  async function refuseWritableAncestor2(parent, options = {}) {
10162
- const uid = process.geteuid?.();
10163
- if (uid === void 0)
10164
- return;
10165
- const gid = process.getegid?.();
10166
- let component;
10167
- try {
10168
- component = await realpath4(parent);
10169
- } catch {
10170
- return;
10171
- }
10172
- let privateGroup;
10173
- for (; ; ) {
10174
- const metadata = await stat5(component).catch(() => void 0);
10175
- if (metadata && (metadata.mode & 18) !== 0 && (metadata.mode & 512) === 0) {
10176
- if (privateGroup === void 0) {
10177
- privateGroup = gid !== void 0 && await isPrivateGroup(uid, gid, options);
10178
- }
10179
- if ((metadata.mode & 2) !== 0 || metadata.uid !== uid || metadata.gid !== gid || !privateGroup) {
10180
- throw new ClaustrumConsumerError("unsafe-file", `Claustrum enrollment path has a writable ancestor: ${component}. Another user could replace it. Run: chmod g-w,o-w ${component}`);
11090
+ if (!windowsPrivateFiles) {
11091
+ const uid = process.geteuid?.();
11092
+ if (uid === void 0)
11093
+ return;
11094
+ const gid = process.getegid?.();
11095
+ let component;
11096
+ try {
11097
+ component = await realpath6(parent);
11098
+ } catch {
11099
+ return;
11100
+ }
11101
+ let privateGroup;
11102
+ for (; ; ) {
11103
+ const metadata2 = await stat6(component).catch(() => void 0);
11104
+ if (metadata2 && (metadata2.mode & 18) !== 0 && (metadata2.mode & 512) === 0) {
11105
+ if (privateGroup === void 0) {
11106
+ privateGroup = gid !== void 0 && await isPrivateGroup(uid, gid, options);
11107
+ }
11108
+ if ((metadata2.mode & 2) !== 0 || metadata2.uid !== uid || metadata2.gid !== gid || !privateGroup) {
11109
+ throw new ClaustrumConsumerError("unsafe-file", `Claustrum enrollment path has a writable ancestor: ${component}. Another user could replace it. Run: chmod g-w,o-w ${component}`);
11110
+ }
10181
11111
  }
11112
+ const next = dirname13(component);
11113
+ if (next === component)
11114
+ return;
11115
+ component = next;
10182
11116
  }
10183
- const next = dirname9(component);
10184
- if (next === component)
10185
- return;
10186
- component = next;
11117
+ }
11118
+ try {
11119
+ await verifySafeDirectory(parent, ancestorPolicyOptions(options));
11120
+ } catch (error) {
11121
+ if (!(error instanceof PrivateFileError))
11122
+ throw error;
11123
+ throw new ClaustrumConsumerError("unsafe-file", `Claustrum enrollment parent refused: ${error.path} (${error.reason ?? error.code}). Use a folder that other users cannot write or replace.`);
10187
11124
  }
10188
11125
  }
10189
- async function ensurePrivateDirectory(directory) {
11126
+ async function ensurePrivateDirectory2(directory, options = {}) {
11127
+ if (windowsPrivateFiles) {
11128
+ await ensurePrivateDirectory(directory, false, ancestorPolicyOptions(options));
11129
+ return;
11130
+ }
10190
11131
  await mkdir9(directory, { recursive: true, mode: 448 });
10191
- const metadata = await stat5(directory);
11132
+ const metadata2 = await stat6(directory);
10192
11133
  const uid = process.geteuid?.();
10193
- if (uid !== void 0 && metadata.uid !== uid) {
11134
+ if (uid !== void 0 && metadata2.uid !== uid) {
10194
11135
  throw new ClaustrumConsumerError("unsafe-file", "Claustrum enrollment directory must be owned by the current user");
10195
11136
  }
10196
- if ((metadata.mode & 63) !== 0)
10197
- await chmod3(directory, 448);
11137
+ if ((metadata2.mode & 63) !== 0)
11138
+ await chmod2(directory, 448);
10198
11139
  }
10199
11140
  async function writeStateAtomic(path2, state, ancestorOptions = {}) {
10200
- const parent = dirname9(path2);
10201
- await ensurePrivateDirectory(parent);
11141
+ const parent = dirname13(path2);
11142
+ await ensurePrivateDirectory2(parent, ancestorOptions);
10202
11143
  await refuseWritableAncestor2(parent, ancestorOptions);
10203
11144
  const bytes = `${JSON.stringify(state)}
10204
11145
  `;
10205
11146
  if (Buffer.byteLength(bytes) > ENROLLMENT_FILE_MAX_BYTES) {
10206
11147
  throw new ClaustrumConsumerError("invalid-state", "Claustrum enrollment state is too large");
10207
11148
  }
10208
- const temporary = join7(parent, `.${basename4(path2)}.${process.pid}.${randomUUID9()}.tmp`);
11149
+ if (windowsPrivateFiles)
11150
+ return writePrivateAtomic(path2, bytes);
11151
+ const temporary = join7(parent, `.${basename4(path2)}.${process.pid}.${randomUUID10()}.tmp`);
10209
11152
  let descriptor;
10210
11153
  let created = false;
10211
11154
  try {
10212
- descriptor = await open6(temporary, "wx", 384);
11155
+ descriptor = await open8(temporary, "wx", 384);
10213
11156
  created = true;
10214
11157
  await descriptor.writeFile(bytes, "utf8");
10215
11158
  await descriptor.chmod(384);
10216
11159
  await descriptor.sync();
10217
11160
  await descriptor.close();
10218
11161
  descriptor = void 0;
10219
- await rename6(temporary, path2);
11162
+ await rename7(temporary, path2);
10220
11163
  created = false;
10221
11164
  } finally {
10222
11165
  await descriptor?.close().catch(() => {
10223
11166
  });
10224
11167
  if (created)
10225
- await unlink6(temporary).catch(() => {
11168
+ await unlink7(temporary).catch(() => {
10226
11169
  });
10227
11170
  }
10228
11171
  }
@@ -10313,7 +11256,7 @@ function wrongConsumer() {
10313
11256
  return new ClaustrumConsumerError("wrong-consumer", "Claustrum enrollment state belongs to a different consumer");
10314
11257
  }
10315
11258
  async function resetClaustrumEnrollmentState(paths, proposedName) {
10316
- await ensurePrivateDirectory(dirname9(paths.statePath));
11259
+ await ensurePrivateDirectory2(dirname13(paths.statePath));
10317
11260
  const lock = await acquireRefreshFileLock({
10318
11261
  name: "ceremony",
10319
11262
  path: paths.statePath,
@@ -10334,7 +11277,7 @@ async function resetClaustrumEnrollmentState(paths, proposedName) {
10334
11277
  if (state.phase === "pending")
10335
11278
  return "refused-pending";
10336
11279
  await lock.assertOwned();
10337
- await unlink6(paths.statePath);
11280
+ await unlink7(paths.statePath);
10338
11281
  return "reset";
10339
11282
  } finally {
10340
11283
  await lock.release();
@@ -10342,7 +11285,7 @@ async function resetClaustrumEnrollmentState(paths, proposedName) {
10342
11285
  }
10343
11286
  async function removeIfPresent(path2) {
10344
11287
  try {
10345
- await unlink6(path2);
11288
+ await unlink7(path2);
10346
11289
  return true;
10347
11290
  } catch (error) {
10348
11291
  if (error.code === "ENOENT")
@@ -10351,7 +11294,7 @@ async function removeIfPresent(path2) {
10351
11294
  }
10352
11295
  }
10353
11296
  async function disconnectClaustrumEnrollment(paths, proposedName) {
10354
- await ensurePrivateDirectory(dirname9(paths.statePath));
11297
+ await ensurePrivateDirectory2(dirname13(paths.statePath));
10355
11298
  const lock = await acquireRefreshFileLock({
10356
11299
  // The same lock as the ceremony, so a token written by a concurrent
10357
11300
  // reconcile() can never land after this removes the files.
@@ -10386,8 +11329,9 @@ var ENROLLMENT_SCHEMA, ENROLLMENT_FILE_MAX_BYTES, ENROLLMENT_LOCK_TTL_MS, TOKEN_
10386
11329
  var init_enrollment2 = __esm({
10387
11330
  "../core/dist/common-auth-embedded/claustrum/enrollment.js"() {
10388
11331
  "use strict";
10389
- init_dist2();
11332
+ init_dist3();
10390
11333
  init_fs();
11334
+ init_private_files();
10391
11335
  init_errors3();
10392
11336
  ENROLLMENT_SCHEMA = 1;
10393
11337
  ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
@@ -10439,7 +11383,7 @@ var init_enrollment2 = __esm({
10439
11383
  return statusFromState(blocked);
10440
11384
  }
10441
11385
  async reconcile() {
10442
- await ensurePrivateDirectory(dirname9(this.#paths.statePath));
11386
+ await ensurePrivateDirectory2(dirname13(this.#paths.statePath), this.#ancestorOptions);
10443
11387
  const lock = await acquireRefreshFileLock({
10444
11388
  name: "ceremony",
10445
11389
  path: this.#paths.statePath,
@@ -10517,17 +11461,17 @@ var init_enrollment2 = __esm({
10517
11461
  };
10518
11462
  await writeStateAtomic(this.#paths.statePath, state, this.#ancestorOptions);
10519
11463
  } catch (error) {
10520
- const refusal3 = classifyEnrollmentError(error);
10521
- if (!refusal3)
11464
+ const refusal4 = classifyEnrollmentError(error);
11465
+ if (!refusal4)
10522
11466
  throw error;
10523
- if (refusal3.disposition === "retry") {
11467
+ if (refusal4.disposition === "retry") {
10524
11468
  return {
10525
11469
  state: "pending",
10526
11470
  proposedName: state.proposedName,
10527
- retryCode: refusal3.code
11471
+ retryCode: refusal4.code
10528
11472
  };
10529
11473
  }
10530
- return this.#block(state, refusal3.code);
11474
+ return this.#block(state, refusal4.code);
10531
11475
  }
10532
11476
  }
10533
11477
  const requestId = state.requestId;
@@ -10550,8 +11494,8 @@ var init_enrollment2 = __esm({
10550
11494
  await writeStateAtomic(this.#paths.statePath, denied, this.#ancestorOptions);
10551
11495
  return statusFromState(denied);
10552
11496
  }
10553
- await ensurePrivateDirectory(dirname9(this.#paths.tokenPath));
10554
- await refuseWritableAncestor2(dirname9(this.#paths.tokenPath), this.#ancestorOptions);
11497
+ await ensurePrivateDirectory2(dirname13(this.#paths.tokenPath), this.#ancestorOptions);
11498
+ await refuseWritableAncestor2(dirname13(this.#paths.tokenPath), this.#ancestorOptions);
10555
11499
  await this.#writeTokenFile(this.#paths.tokenPath, {
10556
11500
  token: outcome.token,
10557
11501
  token_generation: outcome.tokenGeneration
@@ -10567,18 +11511,18 @@ var init_enrollment2 = __esm({
10567
11511
  await writeStateAtomic(this.#paths.statePath, approved, this.#ancestorOptions);
10568
11512
  return statusFromState(approved);
10569
11513
  } catch (error) {
10570
- const refusal3 = classifyEnrollmentError(error);
10571
- if (!refusal3)
11514
+ const refusal4 = classifyEnrollmentError(error);
11515
+ if (!refusal4)
10572
11516
  throw error;
10573
- if (refusal3.disposition === "retry") {
11517
+ if (refusal4.disposition === "retry") {
10574
11518
  return {
10575
11519
  state: "pending",
10576
11520
  proposedName: state.proposedName,
10577
11521
  requestId,
10578
- retryCode: refusal3.code
11522
+ retryCode: refusal4.code
10579
11523
  };
10580
11524
  }
10581
- return this.#block(state, refusal3.code);
11525
+ return this.#block(state, refusal4.code);
10582
11526
  }
10583
11527
  } finally {
10584
11528
  await lock.release();
@@ -10706,7 +11650,7 @@ var defaultLogger, SERVING_MARGIN_MS, ClaustrumScopedCustody;
10706
11650
  var init_custody = __esm({
10707
11651
  "../core/dist/common-auth-embedded/claustrum/custody.js"() {
10708
11652
  "use strict";
10709
- init_dist2();
11653
+ init_dist3();
10710
11654
  init_logger();
10711
11655
  init_enrollment2();
10712
11656
  init_errors3();
@@ -10975,7 +11919,6 @@ var init_interlock = __esm({
10975
11919
 
10976
11920
  // ../core/dist/common-auth-embedded/claustrum/roster.js
10977
11921
  import { createHash as createHash7 } from "node:crypto";
10978
- import { readFile as readFile8 } from "node:fs/promises";
10979
11922
  function hash(value) {
10980
11923
  return createHash7("sha256").update(value).digest("hex");
10981
11924
  }
@@ -11138,13 +12081,13 @@ function decodeRow(value) {
11138
12081
  function decodeRejected(value) {
11139
12082
  if (!Array.isArray(value))
11140
12083
  return void 0;
11141
- const records2 = [];
12084
+ const records = [];
11142
12085
  for (const entry of value) {
11143
12086
  if (!isRecord10(entry) || !optionalString2(entry.credentialId) || typeof entry.reason !== "string" || !SKIPPED_REASONS.has(entry.reason))
11144
12087
  return void 0;
11145
- records2.push(entry);
12088
+ records.push(entry);
11146
12089
  }
11147
- return records2;
12090
+ return records;
11148
12091
  }
11149
12092
  function decodeRoster(value) {
11150
12093
  if (!isRecord10(value) || value.version !== 1 || !optionalString2(value.view) || !Array.isArray(value.rows) || !Array.isArray(value.declined) || value.complete !== void 0 && typeof value.complete !== "boolean" || value.rejected !== void 0 && !decodeRejected(value.rejected))
@@ -11177,7 +12120,7 @@ function decodeRoster(value) {
11177
12120
  async function readVaultRoster(path2) {
11178
12121
  let text2;
11179
12122
  try {
11180
- text2 = await readFile8(path2, "utf8");
12123
+ text2 = await readPrivateText(path2, windowsPrivateFiles);
11181
12124
  } catch (error) {
11182
12125
  if (error.code === "ENOENT")
11183
12126
  return void 0;
@@ -11339,6 +12282,7 @@ var init_roster = __esm({
11339
12282
  "../core/dist/common-auth-embedded/claustrum/roster.js"() {
11340
12283
  "use strict";
11341
12284
  init_fs();
12285
+ init_private_files();
11342
12286
  init_quota();
11343
12287
  init_errors3();
11344
12288
  init_interlock();
@@ -11394,7 +12338,7 @@ var init_consumer = __esm({
11394
12338
  this.#shutdown.signal,
11395
12339
  ...signal ? [signal] : []
11396
12340
  ]);
11397
- return new Promise((resolve7, reject) => {
12341
+ return new Promise((resolve13, reject) => {
11398
12342
  const cleanup2 = () => {
11399
12343
  combined.signal.removeEventListener("abort", abort);
11400
12344
  combined.dispose();
@@ -11409,7 +12353,7 @@ var init_consumer = __esm({
11409
12353
  if (combined.signal.aborted)
11410
12354
  reject(combined.signal.reason);
11411
12355
  else
11412
- resolve7(value);
12356
+ resolve13(value);
11413
12357
  }, (error) => {
11414
12358
  cleanup2();
11415
12359
  reject(error);
@@ -11688,8 +12632,8 @@ function connectClaustrumScopedClient(options) {
11688
12632
  var init_claustrum = __esm({
11689
12633
  "../core/dist/common-auth-embedded/claustrum/index.js"() {
11690
12634
  "use strict";
11691
- init_dist2();
11692
- init_dist2();
12635
+ init_dist3();
12636
+ init_dist3();
11693
12637
  init_consumer();
11694
12638
  init_custody();
11695
12639
  init_enrollment2();
@@ -11702,7 +12646,7 @@ var init_claustrum = __esm({
11702
12646
 
11703
12647
  // ../core/dist/common-auth-embedded/pi-slot/lock.js
11704
12648
  import { rmdirSync, statSync as statSync3 } from "node:fs";
11705
- import { mkdir as mkdir10, rmdir, stat as stat6, utimes } from "node:fs/promises";
12649
+ import { mkdir as mkdir10, rmdir as rmdir2, stat as stat7, utimes } from "node:fs/promises";
11706
12650
  function sameDirectory(observed, identity) {
11707
12651
  return observed.dev === identity.dev && observed.ino === identity.ino;
11708
12652
  }
@@ -11714,7 +12658,7 @@ function held() {
11714
12658
  }
11715
12659
  async function remove(path2) {
11716
12660
  try {
11717
- await rmdir(path2);
12661
+ await rmdir2(path2);
11718
12662
  } catch (error) {
11719
12663
  if (errorCode2(error) !== "ENOENT")
11720
12664
  throw error;
@@ -11730,7 +12674,7 @@ async function acquire(path2, stale) {
11730
12674
  throw held();
11731
12675
  let mtime;
11732
12676
  try {
11733
- mtime = (await stat6(path2)).mtime.getTime();
12677
+ mtime = (await stat7(path2)).mtime.getTime();
11734
12678
  } catch (error2) {
11735
12679
  if (errorCode2(error2) === "ENOENT")
11736
12680
  return acquire(path2, 0);
@@ -11746,7 +12690,7 @@ async function acquire(path2, stale) {
11746
12690
  const probe = new Date(Math.ceil(Date.now() / 1e3) * 1e3 + 5);
11747
12691
  await utimes(path2, probe, probe);
11748
12692
  }
11749
- const observed = await stat6(path2);
12693
+ const observed = await stat7(path2);
11750
12694
  const mtime = observed.mtime.getTime();
11751
12695
  precision ??= mtime % 1e3 === 0 ? "s" : "ms";
11752
12696
  return { dev: observed.dev, ino: observed.ino, mtime };
@@ -11797,7 +12741,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
11797
12741
  return;
11798
12742
  let observed;
11799
12743
  try {
11800
- observed = await stat6(path2);
12744
+ observed = await stat7(path2);
11801
12745
  } catch (error) {
11802
12746
  retry(error);
11803
12747
  return;
@@ -11845,7 +12789,7 @@ async function acquirePiLock(authPath, onCompromised, onRenew) {
11845
12789
  }
11846
12790
  let observed;
11847
12791
  try {
11848
- observed = await stat6(path2);
12792
+ observed = await stat7(path2);
11849
12793
  } catch (error) {
11850
12794
  if (errorCode2(error) !== "ENOENT")
11851
12795
  throw error;
@@ -11886,8 +12830,8 @@ var init_lock = __esm({
11886
12830
  // ../core/dist/common-auth-embedded/pi-slot/slot.js
11887
12831
  import { createHash as createHash8 } from "node:crypto";
11888
12832
  import { constants as constants2 } from "node:fs";
11889
- import { lstat as lstat2, mkdir as mkdir11, open as open7, unlink as unlink7 } from "node:fs/promises";
11890
- import { dirname as dirname10, resolve as resolve4 } from "node:path";
12833
+ import { lstat as lstat4, mkdir as mkdir11, open as open9, unlink as unlink8 } from "node:fs/promises";
12834
+ import { dirname as dirname14, resolve as resolve8 } from "node:path";
11891
12835
  import { setTimeout as sleep2 } from "node:timers/promises";
11892
12836
  function rootSpans(text2) {
11893
12837
  let i = text2.indexOf("{") + 1;
@@ -11967,16 +12911,30 @@ function code(error) {
11967
12911
  return object2(error) ? error.code : void 0;
11968
12912
  }
11969
12913
  async function safeRead(path2, privateFile = false, afterReadCheck) {
12914
+ if (windowsPrivateFiles) {
12915
+ try {
12916
+ await afterReadCheck?.(path2);
12917
+ const bytes = await readPrivateBuffer(path2, true);
12918
+ const text2 = bytes.toString("utf8");
12919
+ if (!bytes.equals(Buffer.from(text2)))
12920
+ throw new PiSlotError(privateFile ? "invalid-stash" : "invalid-auth");
12921
+ return text2;
12922
+ } catch (error) {
12923
+ if (code(error) === "ENOENT")
12924
+ return void 0;
12925
+ throw error;
12926
+ }
12927
+ }
11970
12928
  let file;
11971
12929
  try {
11972
- file = await open7(path2, constants2.O_RDONLY | constants2.O_NOFOLLOW);
11973
- const stat7 = await file.stat();
11974
- if (!stat7.isFile() || privateFile && (stat7.mode & 511) !== 384) {
12930
+ file = await open9(path2, constants2.O_RDONLY | constants2.O_NOFOLLOW);
12931
+ const stat8 = await file.stat();
12932
+ if (!stat8.isFile() || privateFile && (stat8.mode & 511) !== 384) {
11975
12933
  throw new PiSlotError("unsafe-path");
11976
12934
  }
11977
12935
  await afterReadCheck?.(path2);
11978
- const current = await lstat2(path2);
11979
- if (!current.isFile() || current.dev !== stat7.dev || current.ino !== stat7.ino) {
12936
+ const current = await lstat4(path2);
12937
+ if (!current.isFile() || current.dev !== stat8.dev || current.ino !== stat8.ino) {
11980
12938
  throw new PiSlotError("unsafe-path");
11981
12939
  }
11982
12940
  const bytes = await file.readFile();
@@ -12045,7 +13003,9 @@ function replaceEntry(auth, provider, next) {
12045
13003
  return `${text2.slice(0, offset)}${last ? "," : ""}${JSON.stringify(provider)}:${next}${text2.slice(offset)}`;
12046
13004
  }
12047
13005
  async function syncDir(path2) {
12048
- const dir = await open7(path2, "r");
13006
+ if (windowsPrivateFiles)
13007
+ return;
13008
+ const dir = await open9(path2, "r");
12049
13009
  try {
12050
13010
  await dir.sync();
12051
13011
  } finally {
@@ -12056,6 +13016,7 @@ async function atomicWrite(path2, text2, assertLock, beforeRename) {
12056
13016
  await writeJsonAtomic2(path2, null, {
12057
13017
  serialize: () => text2,
12058
13018
  durable: true,
13019
+ durability: windowsPrivateFiles ? "file-only-on-windows" : void 0,
12059
13020
  beforeRename: async () => {
12060
13021
  await beforeRename?.(path2);
12061
13022
  assertLock();
@@ -12071,8 +13032,8 @@ function createPiSlot(options, onStep, hooks) {
12071
13032
  if (!provider || !options.authPath || !options.stashPath || !placeholderKey || placeholderKey.startsWith("!") || placeholderKey.includes("$") || !Number.isFinite(timeout) || timeout < 0) {
12072
13033
  throw new PiSlotError("invalid-options");
12073
13034
  }
12074
- const authPath = resolve4(options.authPath);
12075
- const stashPath = resolve4(options.stashPath);
13035
+ const authPath = resolve8(options.authPath);
13036
+ const stashPath = resolve8(options.stashPath);
12076
13037
  if (authPath === stashPath || stashPath === `${authPath}.lock`) {
12077
13038
  throw new PiSlotError("invalid-options");
12078
13039
  }
@@ -12104,7 +13065,10 @@ function createPiSlot(options, onStep, hooks) {
12104
13065
  throw new PiSlotError("lock-compromised");
12105
13066
  };
12106
13067
  try {
12107
- await mkdir11(dirname10(authPath), { recursive: true, mode: 448 });
13068
+ if (windowsPrivateFiles)
13069
+ await ensurePrivateDirectory(dirname14(authPath));
13070
+ else
13071
+ await mkdir11(dirname14(authPath), { recursive: true, mode: 448 });
12108
13072
  const deadline = Date.now() + timeout;
12109
13073
  let retry = 0;
12110
13074
  while (!release) {
@@ -12128,7 +13092,7 @@ function createPiSlot(options, onStep, hooks) {
12128
13092
  assertLock();
12129
13093
  return result;
12130
13094
  } catch (error) {
12131
- if (error instanceof PiSlotError)
13095
+ if (error instanceof PiSlotError || error instanceof PrivateFileError)
12132
13096
  throw error;
12133
13097
  throw new PiSlotError("io");
12134
13098
  } finally {
@@ -12144,8 +13108,8 @@ function createPiSlot(options, onStep, hooks) {
12144
13108
  }
12145
13109
  async function deleteStash(assertLock) {
12146
13110
  assertLock();
12147
- await unlink7(stashPath);
12148
- await syncDir(dirname10(stashPath));
13111
+ await unlink8(stashPath);
13112
+ await syncDir(dirname14(stashPath));
12149
13113
  onStep?.("stash-deleted");
12150
13114
  }
12151
13115
  return {
@@ -12164,10 +13128,14 @@ function createPiSlot(options, onStep, hooks) {
12164
13128
  if (stash && digest2(auth.entry) !== stash.sha256)
12165
13129
  throw new PiSlotError("conflict");
12166
13130
  if (!stash) {
12167
- await mkdir11(dirname10(stashPath), { recursive: true, mode: 448 });
12168
- const dir = await lstat2(dirname10(stashPath));
12169
- if (!dir.isDirectory() || (dir.mode & 511) !== 448)
12170
- throw new PiSlotError("unsafe-path");
13131
+ if (windowsPrivateFiles)
13132
+ await ensurePrivateDirectory(dirname14(stashPath));
13133
+ else {
13134
+ await mkdir11(dirname14(stashPath), { recursive: true, mode: 448 });
13135
+ const dir = await lstat4(dirname14(stashPath));
13136
+ if (!dir.isDirectory() || (dir.mode & 511) !== 448)
13137
+ throw new PiSlotError("unsafe-path");
13138
+ }
12171
13139
  const saved = {
12172
13140
  version: 1,
12173
13141
  provider,
@@ -12206,6 +13174,7 @@ var init_slot = __esm({
12206
13174
  "../core/dist/common-auth-embedded/pi-slot/slot.js"() {
12207
13175
  "use strict";
12208
13176
  init_atomic_write();
13177
+ init_private_files();
12209
13178
  init_lock();
12210
13179
  PiSlotError = class extends Error {
12211
13180
  code;
@@ -12233,7 +13202,7 @@ var init_pi_slot = __esm({
12233
13202
 
12234
13203
  // src/cli.ts
12235
13204
  import { execFile } from "node:child_process";
12236
- import { resolve as resolve6 } from "node:path";
13205
+ import { resolve as resolve12 } from "node:path";
12237
13206
  import { createInterface } from "node:readline/promises";
12238
13207
  import { promisify } from "node:util";
12239
13208
 
@@ -12495,10 +13464,10 @@ var optional = (codec) => ({
12495
13464
  required: false
12496
13465
  });
12497
13466
  var EXTENSIONS = "extensions";
12498
- function buildRecord(shape, open8, options) {
13467
+ function buildRecord(shape, open11, options) {
12499
13468
  const forbidden = options.forbidden ?? {};
12500
13469
  const knownField = (key) => Object.hasOwn(shape, key) ? shape[key] : void 0;
12501
- const refusal3 = (key) => Object.hasOwn(forbidden, key) ? forbidden[key] : void 0;
13470
+ const refusal4 = (key) => Object.hasOwn(forbidden, key) ? forbidden[key] : void 0;
12502
13471
  const requireFields = (present2, path2) => {
12503
13472
  for (const [key, field] of Object.entries(shape)) {
12504
13473
  if (field.required && !Object.hasOwn(present2, key)) {
@@ -12517,10 +13486,10 @@ function buildRecord(shape, open8, options) {
12517
13486
  out[key] = field.codec.decode(value, at);
12518
13487
  continue;
12519
13488
  }
12520
- const reason = refusal3(key);
13489
+ const reason = refusal4(key);
12521
13490
  if (reason !== void 0)
12522
13491
  fail(at, reason);
12523
- if (!open8)
13492
+ if (!open11)
12524
13493
  fail(at, "is not a known field");
12525
13494
  extensions ??= {};
12526
13495
  extensions[key] = jsonValue.decode(value, at);
@@ -12535,13 +13504,13 @@ function buildRecord(shape, open8, options) {
12535
13504
  let extensions;
12536
13505
  for (const [key, item] of objectEntries(value, path2)) {
12537
13506
  const at = childPath(path2, key);
12538
- if (open8 && key === EXTENSIONS) {
13507
+ if (open11 && key === EXTENSIONS) {
12539
13508
  extensions = item;
12540
13509
  continue;
12541
13510
  }
12542
13511
  const field = knownField(key);
12543
13512
  if (!field) {
12544
- fail(at, open8 ? "is not a known field; unknown data belongs in extensions" : "is not a known field");
13513
+ fail(at, open11 ? "is not a known field; unknown data belongs in extensions" : "is not a known field");
12545
13514
  }
12546
13515
  if (item === void 0) {
12547
13516
  fail(at, "is undefined; leave the key out to keep it absent");
@@ -12555,7 +13524,7 @@ function buildRecord(shape, open8, options) {
12555
13524
  const at = childPath(extensionsPath, key);
12556
13525
  if (knownField(key))
12557
13526
  fail(at, "collides with a known field");
12558
- const reason = refusal3(key);
13527
+ const reason = refusal4(key);
12559
13528
  if (reason !== void 0)
12560
13529
  fail(at, reason);
12561
13530
  out[key] = jsonValue.encode(item, at);
@@ -12745,10 +13714,10 @@ function isValidProviderState(raw) {
12745
13714
  }
12746
13715
  function providerStateCredentialBound(raw) {
12747
13716
  const stored = encodeProviderState(decodeProviderState(raw));
12748
- const metadata = asObject(stored.metadata ?? null);
13717
+ const metadata2 = asObject(stored.metadata ?? null);
12749
13718
  const bound = {};
12750
13719
  for (const key of CREDENTIAL_BOUND_METADATA_FIELDS) {
12751
- const value = metadata[key];
13720
+ const value = metadata2[key];
12752
13721
  if (value !== void 0)
12753
13722
  bound[key] = value;
12754
13723
  }
@@ -12779,12 +13748,12 @@ function decodeRoutingSettings(raw) {
12779
13748
  function encodeRoutingSettings(value) {
12780
13749
  return asObject(routingCodec.encode(value, "$"));
12781
13750
  }
12782
- function createProviderStateCodec(policy) {
12783
- if (policy === null || typeof policy !== "object") {
13751
+ function createProviderStateCodec(policy2) {
13752
+ if (policy2 === null || typeof policy2 !== "object") {
12784
13753
  fail("policy", "must be an object with merge and onReplace rules");
12785
13754
  }
12786
13755
  for (const rule of ["merge", "onReplace"]) {
12787
- if (typeof policy[rule] !== "function") {
13756
+ if (typeof policy2[rule] !== "function") {
12788
13757
  fail(`policy.${rule}`, "must be a function; the store's default would bypass the repository's rule");
12789
13758
  }
12790
13759
  }
@@ -12792,10 +13761,10 @@ function createProviderStateCodec(policy) {
12792
13761
  validate: isValidProviderState,
12793
13762
  credentialBound: providerStateCredentialBound,
12794
13763
  merge(onDisk, incoming) {
12795
- return encodeProviderState(policy.merge(decodeProviderState(onDisk), decodeProviderState(incoming)));
13764
+ return encodeProviderState(policy2.merge(decodeProviderState(onDisk), decodeProviderState(incoming)));
12796
13765
  },
12797
13766
  onReplace(previous, replacement) {
12798
- const next = policy.onReplace(previous === void 0 ? void 0 : decodeProviderState(previous), {
13767
+ const next = policy2.onReplace(previous === void 0 ? void 0 : decodeProviderState(previous), {
12799
13768
  id: replacement.id,
12800
13769
  credentialEpoch: replacement.credentialEpoch,
12801
13770
  ...replacement.previousIdentity !== void 0 ? { previousIdentity: replacement.previousIdentity } : {},
@@ -12991,11 +13960,11 @@ function parseAccount(value, ordinal, version, clock) {
12991
13960
  delete normalized.fingerprint;
12992
13961
  delete normalized.fingerprintHistory;
12993
13962
  }
12994
- const metadata = decodeProviderMetadata(normalized);
13963
+ const metadata2 = decodeProviderMetadata(normalized);
12995
13964
  return {
12996
13965
  ordinal,
12997
13966
  refreshToken: source.refreshToken,
12998
- metadata,
13967
+ metadata: metadata2,
12999
13968
  ...quota === void 0 ? {} : { quota }
13000
13969
  };
13001
13970
  }
@@ -13442,10 +14411,10 @@ async function privateDirectory(path2) {
13442
14411
  if (errno(error) !== "EEXIST")
13443
14412
  throw error;
13444
14413
  }
13445
- const stat7 = await lstat(path2);
13446
- if (!stat7.isDirectory() || stat7.isSymbolicLink())
14414
+ const stat8 = await lstat(path2);
14415
+ if (!stat8.isDirectory() || stat8.isSymbolicLink())
13447
14416
  throw new AccountMigrationError("successor directory is not a regular directory");
13448
- privateMode(stat7.mode, 448);
14417
+ privateMode(stat8.mode, 448);
13449
14418
  if (!sameFilesystemPath(await realpath(path2), path2))
13450
14419
  throw new AccountMigrationError("successor directory traverses a symbolic link");
13451
14420
  }
@@ -13657,8 +14626,8 @@ function assertImportedRow(row, manifest, id) {
13657
14626
  healthyRow(row);
13658
14627
  if (row.id !== id || row.identity !== void 0 || rowRef(row).credentialEpoch !== 1 || row.credential?.type !== "oauth" || row.credential.refresh !== manifest.refreshToken || row.credential.access !== void 0 || row.credential.expires !== void 0 || row.enabled !== (manifest.metadata.enabled !== false))
13659
14628
  throw new AccountMigrationError("successor credential, lineage, identity or enabled flag differs from manifest");
13660
- const metadata = decodeProviderState(row.providerState);
13661
- if (!isDeepStrictEqual(encodeProviderState(metadata), encodeProviderState({ schemaVersion: 1, metadata: manifest.metadata })) || !isDeepStrictEqual(row.quota, manifest.quota === void 0 ? void 0 : encodeQuotaState(manifest.quota)))
14629
+ const metadata2 = decodeProviderState(row.providerState);
14630
+ if (!isDeepStrictEqual(encodeProviderState(metadata2), encodeProviderState({ schemaVersion: 1, metadata: manifest.metadata })) || !isDeepStrictEqual(row.quota, manifest.quota === void 0 ? void 0 : encodeQuotaState(manifest.quota)))
13662
14631
  throw new AccountMigrationError("successor full metadata, quota or presence differs from manifest");
13663
14632
  }
13664
14633
  async function verifyImported(store, journal) {
@@ -14301,13 +15270,13 @@ async function exportCurrent(store) {
14301
15270
  healthyRow(row);
14302
15271
  if (row.credential?.type !== "oauth")
14303
15272
  throw new AccountMigrationError("rollback cannot export a non-OAuth row");
14304
- const metadata = decodeProviderState(row.providerState).metadata;
14305
- if (metadata.enabled !== false !== row.enabled)
15273
+ const metadata2 = decodeProviderState(row.providerState).metadata;
15274
+ if (metadata2.enabled !== false !== row.enabled)
14306
15275
  throw new AccountMigrationError("current enabled encoding differs from native row");
14307
15276
  return {
14308
15277
  ordinal,
14309
15278
  refreshToken: row.credential.refresh,
14310
- metadata,
15279
+ metadata: metadata2,
14311
15280
  ...row.quota === void 0 ? {} : { quota: decodeQuotaState(row.quota) }
14312
15281
  };
14313
15282
  });
@@ -14842,8 +15811,8 @@ function latest(...times) {
14842
15811
  }
14843
15812
  return result;
14844
15813
  }
14845
- function accessEvidenceAt(metadata) {
14846
- return latest(metadata.verificationRequiredAt, metadata.accountIneligibleAt, metadata.eligibilityStateUpdatedAt);
15814
+ function accessEvidenceAt(metadata2) {
15815
+ return latest(metadata2.verificationRequiredAt, metadata2.accountIneligibleAt, metadata2.eligibilityStateUpdatedAt);
14847
15816
  }
14848
15817
  function mergeExtensions(a, b) {
14849
15818
  if (a === void 0 && b === void 0)
@@ -14922,19 +15891,19 @@ var ACCOUNT_STATE_POLICY = {
14922
15891
  };
14923
15892
  },
14924
15893
  onReplace(previous, replacement) {
14925
- const metadata = replacementMetadata(previous?.metadata, replacement);
14926
- if (metadata === void 0)
15894
+ const metadata2 = replacementMetadata(previous?.metadata, replacement);
15895
+ if (metadata2 === void 0)
14927
15896
  return void 0;
14928
15897
  const extensions = mergeExtensions(previous?.extensions, replacement.incoming?.extensions);
14929
15898
  return {
14930
15899
  schemaVersion: PROVIDER_STATE_SCHEMA_VERSION,
14931
- metadata,
15900
+ metadata: metadata2,
14932
15901
  ...extensions !== void 0 ? { extensions } : {}
14933
15902
  };
14934
15903
  }
14935
15904
  };
14936
- function applyProjectObservation(metadata, observation) {
14937
- const next = { ...metadata };
15905
+ function applyProjectObservation(metadata2, observation) {
15906
+ const next = { ...metadata2 };
14938
15907
  if (observation.projectId !== void 0)
14939
15908
  next.projectId = observation.projectId;
14940
15909
  if (observation.managedProjectId !== void 0) {
@@ -14942,27 +15911,27 @@ function applyProjectObservation(metadata, observation) {
14942
15911
  }
14943
15912
  return next;
14944
15913
  }
14945
- function applyFingerprintObservation(metadata, observation) {
15914
+ function applyFingerprintObservation(metadata2, observation) {
14946
15915
  return {
14947
- ...metadata,
15916
+ ...metadata2,
14948
15917
  fingerprint: observation.fingerprint,
14949
15918
  fingerprintHistory: [...observation.history]
14950
15919
  };
14951
15920
  }
14952
- function applyTierObservation(metadata, observation) {
14953
- if (typeof metadata.capturedTierAt === "number" && observation.observedAt < metadata.capturedTierAt) {
14954
- return metadata;
15921
+ function applyTierObservation(metadata2, observation) {
15922
+ if (typeof metadata2.capturedTierAt === "number" && observation.observedAt < metadata2.capturedTierAt) {
15923
+ return metadata2;
14955
15924
  }
14956
15925
  return {
14957
- ...metadata,
15926
+ ...metadata2,
14958
15927
  capturedTierId: observation.tierId,
14959
15928
  capturedPaidTierId: observation.paidTierId,
14960
15929
  capturedTierAt: observation.observedAt,
14961
15930
  capturedTierSchemaVersion: observation.schemaVersion
14962
15931
  };
14963
15932
  }
14964
- function applyCooldownObservation(metadata, observation) {
14965
- const next = { ...metadata };
15933
+ function applyCooldownObservation(metadata2, observation) {
15934
+ const next = { ...metadata2 };
14966
15935
  if (observation === null) {
14967
15936
  delete next.coolingDownUntil;
14968
15937
  delete next.cooldownReason;
@@ -14972,32 +15941,32 @@ function applyCooldownObservation(metadata, observation) {
14972
15941
  }
14973
15942
  return next;
14974
15943
  }
14975
- function applyRateLimitObservation(metadata, resets) {
15944
+ function applyRateLimitObservation(metadata2, resets) {
14976
15945
  return {
14977
- ...metadata,
14978
- rateLimitResetTimes: mergeRateLimitResets(metadata.rateLimitResetTimes, resets)
15946
+ ...metadata2,
15947
+ rateLimitResetTimes: mergeRateLimitResets(metadata2.rateLimitResetTimes, resets)
14979
15948
  };
14980
15949
  }
14981
- function applySwitch(metadata, reason) {
14982
- return { ...metadata, lastSwitchReason: reason };
15950
+ function applySwitch(metadata2, reason) {
15951
+ return { ...metadata2, lastSwitchReason: reason };
14983
15952
  }
14984
- function applyUsage(metadata, observation, now) {
15953
+ function applyUsage(metadata2, observation, now) {
14985
15954
  const today = utcDay(now);
14986
- const stored = metadata.dailyRequestCounts;
15955
+ const stored = metadata2.dailyRequestCounts;
14987
15956
  const counts = stored != null && stored.date === today ? { ...stored } : { date: today, claude: 0, gemini: 0 };
14988
15957
  counts[observation.family] += 1;
14989
15958
  return {
14990
- ...metadata,
14991
- lastUsed: Math.max(metadata.lastUsed, observation.at),
15959
+ ...metadata2,
15960
+ lastUsed: Math.max(metadata2.lastUsed, observation.at),
14992
15961
  dailyRequestCounts: counts
14993
15962
  };
14994
15963
  }
14995
- function applyAccessVerdict(metadata, verdict) {
14996
- const evidenceAt = accessEvidenceAt(metadata);
15964
+ function applyAccessVerdict(metadata2, verdict) {
15965
+ const evidenceAt = accessEvidenceAt(metadata2);
14997
15966
  if (evidenceAt !== void 0 && verdict.observedAt < evidenceAt) {
14998
15967
  return void 0;
14999
15968
  }
15000
- const next = { ...metadata };
15969
+ const next = { ...metadata2 };
15001
15970
  switch (verdict.kind) {
15002
15971
  case "verification-required": {
15003
15972
  next.verificationRequired = true;
@@ -15030,8 +15999,8 @@ function applyAccessVerdict(metadata, verdict) {
15030
15999
  return { metadata: next, transition: "disable" };
15031
16000
  }
15032
16001
  case "cleared": {
15033
- const wasBlocked = metadata.verificationRequired === true || metadata.accountIneligible === true;
15034
- const hadEligibility = metadata.accountIneligible === true || metadata.eligibilityStateUpdatedAt != null;
16002
+ const wasBlocked = metadata2.verificationRequired === true || metadata2.accountIneligible === true;
16003
+ const hadEligibility = metadata2.accountIneligible === true || metadata2.eligibilityStateUpdatedAt != null;
15035
16004
  next.verificationRequired = false;
15036
16005
  delete next.verificationRequiredAt;
15037
16006
  delete next.verificationRequiredReason;
@@ -15060,10 +16029,10 @@ function shownEnvelope(operation, current, row) {
15060
16029
  function metadataOrBase(envelope, row, now) {
15061
16030
  return envelope?.metadata ?? { addedAt: row.addedAt ?? now, lastUsed: 0 };
15062
16031
  }
15063
- function encodeEnvelope(prior, metadata) {
16032
+ function encodeEnvelope(prior, metadata2) {
15064
16033
  return encodeProviderState({
15065
16034
  schemaVersion: PROVIDER_STATE_SCHEMA_VERSION,
15066
- metadata,
16035
+ metadata: metadata2,
15067
16036
  ...prior?.extensions !== void 0 ? { extensions: prior.extensions } : {}
15068
16037
  });
15069
16038
  }
@@ -15821,14 +16790,14 @@ var StoreAccountRepository = class {
15821
16790
  if (row.providerStateDropped !== void 0)
15822
16791
  return void 0;
15823
16792
  const envelope = envelopeOf(row.providerState);
15824
- const metadata = {
16793
+ const metadata2 = {
15825
16794
  ...metadataOrBase(envelope, row, this.now())
15826
16795
  };
15827
16796
  for (const [key, value] of Object.entries(learnt)) {
15828
16797
  if (value !== void 0)
15829
- Object.assign(metadata, { [key]: value });
16798
+ Object.assign(metadata2, { [key]: value });
15830
16799
  }
15831
- return encodeEnvelope(envelope, metadata);
16800
+ return encodeEnvelope(envelope, metadata2);
15832
16801
  }
15833
16802
  recordIdentity(ref, identity) {
15834
16803
  return this.run("recordIdentity", ref.id, async () => {
@@ -15868,10 +16837,10 @@ var StoreAccountRepository = class {
15868
16837
  return this.decline;
15869
16838
  if (transition.kind === "clear")
15870
16839
  return void 0;
15871
- const metadata = transition.kind === "set" ? transition.metadata : envelope?.metadata;
15872
- if (metadata === void 0)
16840
+ const metadata2 = transition.kind === "set" ? transition.metadata : envelope?.metadata;
16841
+ if (metadata2 === void 0)
15873
16842
  return void 0;
15874
- return encodeEnvelope(envelope, { ...metadata, enabled: input.enabled });
16843
+ return encodeEnvelope(envelope, { ...metadata2, enabled: input.enabled });
15875
16844
  };
15876
16845
  const options = seen.providerStateDropped !== void 0 && input.metadata === void 0 ? { attribution: credentialFenceOf(ref) } : { attribution: credentialFenceOf(ref), providerState: mutator };
15877
16846
  const result = input.enabled ? await this.store.enable(ref.id, options) : await this.store.disable(ref.id, input.reason ?? (input.actor === "user" ? "disabled-by-user" : "disabled"), options);
@@ -15881,11 +16850,11 @@ var StoreAccountRepository = class {
15881
16850
  transitionResult(ref, result) {
15882
16851
  if (result.declined)
15883
16852
  return { ref, declined: true };
15884
- const metadata = metadataOfStored(result.providerState);
16853
+ const metadata2 = metadataOfStored(result.providerState);
15885
16854
  return {
15886
16855
  ref,
15887
16856
  ...result.providerStateOutcome !== void 0 ? { metadataOutcome: result.providerStateOutcome } : {},
15888
- ...metadata !== void 0 ? { metadata } : {}
16857
+ ...metadata2 !== void 0 ? { metadata: metadata2 } : {}
15889
16858
  };
15890
16859
  }
15891
16860
  recordAccessVerdict(ref, verdict) {
@@ -15940,11 +16909,11 @@ var StoreAccountRepository = class {
15940
16909
  });
15941
16910
  if (stale)
15942
16911
  return { ref, declined: true };
15943
- const metadata = metadataOfStored(result.providerState);
16912
+ const metadata2 = metadataOfStored(result.providerState);
15944
16913
  return {
15945
16914
  ref,
15946
16915
  metadataOutcome: result.outcome,
15947
- ...metadata !== void 0 ? { metadata } : {}
16916
+ ...metadata2 !== void 0 ? { metadata: metadata2 } : {}
15948
16917
  };
15949
16918
  });
15950
16919
  }
@@ -15966,11 +16935,11 @@ var StoreAccountRepository = class {
15966
16935
  });
15967
16936
  }
15968
16937
  metadataResult(ref, result) {
15969
- const metadata = metadataOfStored(result.providerState);
16938
+ const metadata2 = metadataOfStored(result.providerState);
15970
16939
  return {
15971
16940
  ref,
15972
16941
  outcome: result.outcome,
15973
- ...metadata !== void 0 ? { metadata } : {}
16942
+ ...metadata2 !== void 0 ? { metadata: metadata2 } : {}
15974
16943
  };
15975
16944
  }
15976
16945
  /**
@@ -16024,8 +16993,8 @@ var StoreAccountRepository = class {
16024
16993
  retryable: failure.failure.ambiguous ? false : failure.failure.retryable
16025
16994
  }, { cause: error });
16026
16995
  }
16027
- const metadata = metadataOfStored(result.providerState);
16028
- if (metadata?.dailyRequestCounts == null) {
16996
+ const metadata2 = metadataOfStored(result.providerState);
16997
+ if (metadata2?.dailyRequestCounts == null) {
16029
16998
  throw refusal("recordUsage", "unexpected", `row ${ref.id} shows no request counts after the increment`, {
16030
16999
  rowId: ref.id,
16031
17000
  ambiguous: true
@@ -16033,8 +17002,8 @@ var StoreAccountRepository = class {
16033
17002
  }
16034
17003
  return {
16035
17004
  ref,
16036
- lastUsed: metadata.lastUsed,
16037
- dailyRequestCounts: metadata.dailyRequestCounts
17005
+ lastUsed: metadata2.lastUsed,
17006
+ dailyRequestCounts: metadata2.dailyRequestCounts
16038
17007
  };
16039
17008
  });
16040
17009
  }
@@ -16585,8 +17554,8 @@ function createAccountRepositoryFactory(modules, factoryOptions = {}) {
16585
17554
  }
16586
17555
 
16587
17556
  // ../core/dist/fingerprint.js
16588
- var AGY_CLI_VERSION = "1.3.3";
16589
- var AGY_CLI_CHANGE_LIST = "996823801";
17557
+ var AGY_CLI_VERSION = "1.3.5";
17558
+ var AGY_CLI_CHANGE_LIST = "998863838";
16590
17559
  function normalizeHarnessPlatform(platform = process.platform) {
16591
17560
  return platform === "win32" ? "windows" : platform || "unknown";
16592
17561
  }
@@ -16642,8 +17611,8 @@ function defineModel(id, model) {
16642
17611
  };
16643
17612
  }
16644
17613
  var ALL_MODEL_DEFINITIONS = {
16645
- "antigravity-gemini-3.5-flash": defineModel("antigravity-gemini-3.5-flash", {
16646
- name: "Gemini 3.5 Flash (Antigravity)",
17614
+ "antigravity-gemini-4-argon": defineModel("antigravity-gemini-4-argon", {
17615
+ name: "Gemini 4 Argon (Antigravity)",
16647
17616
  reasoning: true,
16648
17617
  limit: { context: 1048576, output: 65536 },
16649
17618
  modalities: DEFAULT_MODALITIES,
@@ -16653,24 +17622,8 @@ var ALL_MODEL_DEFINITIONS = {
16653
17622
  high: { thinkingLevel: "high" }
16654
17623
  }
16655
17624
  }),
16656
- "antigravity-gemini-3.1-flash-image": defineModel("antigravity-gemini-3.1-flash-image", {
16657
- name: "Gemini 3.1 Flash Image (Antigravity)",
16658
- reasoning: false,
16659
- limit: { context: 66e3, output: 33e3 },
16660
- modalities: { input: ["text", "image"], output: ["text", "image"] }
16661
- }),
16662
- "antigravity-gemini-3.1-pro": defineModel("antigravity-gemini-3.1-pro", {
16663
- name: "Gemini 3.1 Pro (Antigravity)",
16664
- reasoning: true,
16665
- limit: { context: 1048576, output: 65535 },
16666
- modalities: DEFAULT_MODALITIES,
16667
- variants: {
16668
- low: { thinkingLevel: "low" },
16669
- high: { thinkingLevel: "high" }
16670
- }
16671
- }),
16672
- "antigravity-gemini-3.8-flash": defineModel("antigravity-gemini-3.8-flash", {
16673
- name: "Gemini 3.8 Flash (Antigravity)",
17625
+ "antigravity-gemini-3.5-flash": defineModel("antigravity-gemini-3.5-flash", {
17626
+ name: "Gemini 3.5 Flash (Antigravity)",
16674
17627
  reasoning: true,
16675
17628
  limit: { context: 1048576, output: 65536 },
16676
17629
  modalities: DEFAULT_MODALITIES,
@@ -16680,19 +17633,14 @@ var ALL_MODEL_DEFINITIONS = {
16680
17633
  high: { thinkingLevel: "high" }
16681
17634
  }
16682
17635
  }),
16683
- "antigravity-gemini-3.7-flash": defineModel("antigravity-gemini-3.7-flash", {
16684
- name: "Gemini 3.7 Flash (Antigravity)",
16685
- reasoning: true,
16686
- limit: { context: 1048576, output: 65536 },
16687
- modalities: DEFAULT_MODALITIES,
16688
- variants: {
16689
- low: { thinkingLevel: "low" },
16690
- medium: { thinkingLevel: "medium" },
16691
- high: { thinkingLevel: "high" }
16692
- }
17636
+ "antigravity-gemini-3.1-flash-image": defineModel("antigravity-gemini-3.1-flash-image", {
17637
+ name: "Gemini 3.1 Flash Image (Antigravity)",
17638
+ reasoning: false,
17639
+ limit: { context: 66e3, output: 33e3 },
17640
+ modalities: { input: ["text", "image"], output: ["text", "image"] }
16693
17641
  }),
16694
- "antigravity-gemini-3.6-flash": defineModel("antigravity-gemini-3.6-flash", {
16695
- name: "Gemini 3.6 Flash (Antigravity)",
17642
+ "antigravity-gemini-3.8-flash": defineModel("antigravity-gemini-3.8-flash", {
17643
+ name: "Gemini 3.8 Flash (Antigravity)",
16696
17644
  reasoning: true,
16697
17645
  limit: { context: 1048576, output: 65536 },
16698
17646
  modalities: DEFAULT_MODALITIES,
@@ -16786,6 +17734,9 @@ var ALL_MODEL_DEFINITIONS = {
16786
17734
  })
16787
17735
  };
16788
17736
  var RESOLVER_ALIASES = {
17737
+ "gemini-4-argon-low": "gemini-4-argon",
17738
+ "gemini-4-argon-medium": "gemini-4-argon",
17739
+ "gemini-4-argon-high": "gemini-4-argon",
16789
17740
  "gemini-3.1-pro-low": "gemini-3.1-pro",
16790
17741
  "gemini-3.1-pro-high": "gemini-3.1-pro",
16791
17742
  "gemini-3-flash-low": "gemini-3-flash",
@@ -16847,12 +17798,10 @@ var QUOTA_GROUP_BY_MODEL_ID = {
16847
17798
  "gpt-oss-120b-medium": "non-gemini"
16848
17799
  };
16849
17800
  var ANTIGRAVITY_OPENCODE_MODEL_IDS = [
17801
+ "antigravity-gemini-4-argon",
16850
17802
  "antigravity-gemini-3.8-flash",
16851
- "antigravity-gemini-3.7-flash",
16852
- "antigravity-gemini-3.6-flash",
16853
17803
  "antigravity-gemini-3.5-flash",
16854
17804
  "antigravity-gemini-3.1-flash-image",
16855
- "antigravity-gemini-3.1-pro",
16856
17805
  "antigravity-claude-sonnet-5-5",
16857
17806
  "antigravity-claude-opus-5-5",
16858
17807
  "antigravity-gpt-oss-120b-medium"
@@ -16866,6 +17815,8 @@ function getResolverAliasMap() {
16866
17815
  }
16867
17816
  function getQuotaGroupForModel(modelId) {
16868
17817
  const normalized = modelId.toLowerCase();
17818
+ if (isGeminiArgonModel(normalized))
17819
+ return void 0;
16869
17820
  return QUOTA_GROUP_BY_MODEL_ID[normalized] ?? // Check Claude / GPT-OSS substrings BEFORE the `gemini` substring so
16870
17821
  // a `gemini-claude-*` alias (which is a Claude route exposed under
16871
17822
  // a `gemini-` namespace) attributes to the non-gemini pool rather
@@ -16873,6 +17824,9 @@ function getQuotaGroupForModel(modelId) {
16873
17824
  // alias IDs start with `gemini-` but contain `claude`.
16874
17825
  (normalized.includes("claude") || normalized.includes("gpt-oss") ? "non-gemini" : normalized.startsWith("gemini") || normalized.startsWith("tab_") ? "gemini" : void 0);
16875
17826
  }
17827
+ function isGeminiArgonModel(model) {
17828
+ return /^(?:antigravity-)?gemini-4-argon(?:-(?:low|medium|high))?$/.test(model.toLowerCase());
17829
+ }
16876
17830
 
16877
17831
  // ../core/dist/account-selector.js
16878
17832
  var ACCOUNT_SESSION_STATE_TTL_MS = 24 * 60 * 60 * 1e3;
@@ -16968,7 +17922,7 @@ async function rmEvictingDir(evictingPath) {
16968
17922
  });
16969
17923
  }
16970
17924
  async function sleep(ms) {
16971
- await new Promise((resolve7) => setTimeout(resolve7, ms));
17925
+ await new Promise((resolve13) => setTimeout(resolve13, ms));
16972
17926
  }
16973
17927
  async function acquireFencedFileLock(options) {
16974
17928
  const lockPath = `${options.path}.${options.name}.lock`;
@@ -17084,8 +18038,8 @@ function buildLock(lockPath, evictingPath, ownerId, options, now) {
17084
18038
  let released = false;
17085
18039
  let lost = false;
17086
18040
  let lostResolve = null;
17087
- let lostPromise = new Promise((resolve7) => {
17088
- lostResolve = resolve7;
18041
+ let lostPromise = new Promise((resolve13) => {
18042
+ lostResolve = resolve13;
17089
18043
  });
17090
18044
  const markLost = () => {
17091
18045
  if (lost)
@@ -17095,9 +18049,9 @@ function buildLock(lockPath, evictingPath, ownerId, options, now) {
17095
18049
  clearInterval(renewTimer);
17096
18050
  renewTimer = null;
17097
18051
  }
17098
- const resolve7 = lostResolve;
18052
+ const resolve13 = lostResolve;
17099
18053
  lostResolve = null;
17100
- resolve7?.();
18054
+ resolve13?.();
17101
18055
  };
17102
18056
  const setupRenew = () => {
17103
18057
  if (options.renew === false)
@@ -17321,7 +18275,7 @@ var AccountStorageUnreadableError = class extends Error {
17321
18275
  }
17322
18276
  };
17323
18277
  var RETRY_DELAYS_MS = [100, 200, 400, 800, 1e3];
17324
- var DEFAULT_SLEEP = (ms) => new Promise((resolve7) => setTimeout(resolve7, ms));
18278
+ var DEFAULT_SLEEP = (ms) => new Promise((resolve13) => setTimeout(resolve13, ms));
17325
18279
  var DEFAULT_BUILD_BACKUP_PATH = (path2, now) => `${path2}.corrupt-${now.toISOString().replace(/[:.]/g, "-")}`;
17326
18280
  async function ensureSecurePermissions(path2) {
17327
18281
  try {
@@ -17832,7 +18786,7 @@ function getHttpsProxy(url) {
17832
18786
  }
17833
18787
  }
17834
18788
  function waitForHead(socket, timeoutMs, onTimeout) {
17835
- return new Promise((resolve7, reject) => {
18789
+ return new Promise((resolve13, reject) => {
17836
18790
  let buffer = Buffer2.alloc(0);
17837
18791
  const timeout = setTimeout(() => {
17838
18792
  onTimeout();
@@ -17855,7 +18809,7 @@ function waitForHead(socket, timeoutMs, onTimeout) {
17855
18809
  return;
17856
18810
  const head = buffer.subarray(0, marker).toString("latin1");
17857
18811
  const leftover = buffer.subarray(marker + 4);
17858
- cleanup2(() => resolve7({ head, leftover }));
18812
+ cleanup2(() => resolve13({ head, leftover }));
17859
18813
  };
17860
18814
  socket.on("data", onData);
17861
18815
  socket.once("error", onError);
@@ -17869,7 +18823,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
17869
18823
  port: Number(proxyUrl.port || DEFAULT_PROXY_PORT),
17870
18824
  signal: signal ?? void 0
17871
18825
  });
17872
- await new Promise((resolve7, reject) => {
18826
+ await new Promise((resolve13, reject) => {
17873
18827
  const timeout = setTimeout(() => {
17874
18828
  onDebug?.(`agy transport proxy connect timeout after ${timeoutMs}ms`);
17875
18829
  proxySocket.destroy();
@@ -17878,7 +18832,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
17878
18832
  const cleanup2 = () => clearTimeout(timeout);
17879
18833
  proxySocket.once("connect", () => {
17880
18834
  cleanup2();
17881
- resolve7();
18835
+ resolve13();
17882
18836
  });
17883
18837
  proxySocket.once("error", (error) => {
17884
18838
  cleanup2();
@@ -17903,7 +18857,7 @@ Host: ${targetHost}:${targetPort}\r
17903
18857
  if (leftover.length > 0) {
17904
18858
  proxySocket.unshift(leftover);
17905
18859
  }
17906
- return await new Promise((resolve7, reject) => {
18860
+ return await new Promise((resolve13, reject) => {
17907
18861
  const tlsOptions = {
17908
18862
  socket: proxySocket,
17909
18863
  servername: targetHost,
@@ -17918,7 +18872,7 @@ Host: ${targetHost}:${targetPort}\r
17918
18872
  const cleanup2 = () => clearTimeout(timeout);
17919
18873
  tlsSocket.once("secureConnect", () => {
17920
18874
  cleanup2();
17921
- resolve7(tlsSocket);
18875
+ resolve13(tlsSocket);
17922
18876
  });
17923
18877
  tlsSocket.once("error", (error) => {
17924
18878
  cleanup2();
@@ -17927,7 +18881,7 @@ Host: ${targetHost}:${targetPort}\r
17927
18881
  });
17928
18882
  }
17929
18883
  async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
17930
- return await new Promise((resolve7, reject) => {
18884
+ return await new Promise((resolve13, reject) => {
17931
18885
  const tlsOptions = {
17932
18886
  host: targetUrl.hostname,
17933
18887
  port: Number(targetUrl.port || DEFAULT_HTTPS_PORT),
@@ -17943,7 +18897,7 @@ async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
17943
18897
  const cleanup2 = () => clearTimeout(timeout);
17944
18898
  socket.once("secureConnect", () => {
17945
18899
  cleanup2();
17946
- resolve7(socket);
18900
+ resolve13(socket);
17947
18901
  });
17948
18902
  socket.once("error", (error) => {
17949
18903
  cleanup2();
@@ -18577,8 +19531,8 @@ function getDefaultTierId(allowedTiers) {
18577
19531
  return allowedTiers[0]?.id;
18578
19532
  }
18579
19533
  function wait(ms) {
18580
- return new Promise((resolve7) => {
18581
- setTimeout(resolve7, ms);
19534
+ return new Promise((resolve13) => {
19535
+ setTimeout(resolve13, ms);
18582
19536
  });
18583
19537
  }
18584
19538
  function extractManagedProjectId(payload) {
@@ -19017,6 +19971,8 @@ function hashKey(key) {
19017
19971
  return createHash9("sha256").update(key).digest("hex").slice(0, 8);
19018
19972
  }
19019
19973
  function classifyQuotaGroup(modelName, displayName) {
19974
+ if (isGeminiArgonModel(modelName))
19975
+ return null;
19020
19976
  const registryGroup = getQuotaGroupForModel(modelName);
19021
19977
  if (registryGroup) {
19022
19978
  return registryGroup;
@@ -19432,10 +20388,183 @@ import {
19432
20388
  writeFileSync
19433
20389
  } from "node:fs";
19434
20390
  import { homedir as homedir2 } from "node:os";
19435
- import { dirname as dirname11, join as join9, resolve as resolve5 } from "node:path";
20391
+ import { dirname as dirname17, join as join9, resolve as resolve11 } from "node:path";
19436
20392
 
19437
20393
  // src/common-auth-embedded/logger/engine.js
19438
20394
  import { appendFileSync as appendFileSync2, chmodSync as chmodSync2, existsSync as existsSync3, renameSync as renameSync2, statSync as statSync4 } from "node:fs";
20395
+ import { open as open10 } from "node:fs/promises";
20396
+ import { dirname as dirname16, resolve as resolve10 } from "node:path";
20397
+
20398
+ // src/common-auth-embedded/fs/private-files.js
20399
+ import { lstat as lstat5, readFile as readFile8, rename as rename8, unlink as unlink9 } from "node:fs/promises";
20400
+ import { dirname as dirname15, resolve as resolve9 } from "node:path";
20401
+ var windowsPrivateFiles2 = process.platform === "win32";
20402
+ var migrationNotices2 = /* @__PURE__ */ new Set();
20403
+ function ioCode2(detail) {
20404
+ if (detail?.reason === "io-error") {
20405
+ if (detail.win32Code === 2 || detail.win32Code === 3)
20406
+ return "ENOENT";
20407
+ if (detail.win32Code === 80 || detail.win32Code === 183)
20408
+ return "EEXIST";
20409
+ }
20410
+ return detail?.code ?? "ERR_PRIVATE_FILE";
20411
+ }
20412
+ var backend2;
20413
+ function loadBackend2() {
20414
+ backend2 ??= import("@cortexkit/private-files");
20415
+ return backend2;
20416
+ }
20417
+ var PrivateFileError2 = class extends Error {
20418
+ path;
20419
+ stage;
20420
+ code;
20421
+ win32Code;
20422
+ reason;
20423
+ published = false;
20424
+ durabilityConfirmed = false;
20425
+ fileDurable = false;
20426
+ attempts = 0;
20427
+ elapsedMs = 0;
20428
+ orphanPath;
20429
+ constructor(path2, stage, cause) {
20430
+ const detail = cause;
20431
+ super(`Private file refused at ${stage}: ${path2} (${detail?.reason ?? detail?.code ?? "io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`, { cause });
20432
+ this.path = path2;
20433
+ this.stage = stage;
20434
+ this.name = "PrivateFileError";
20435
+ this.code = ioCode2(detail);
20436
+ this.win32Code = detail?.win32Code;
20437
+ this.reason = detail?.reason;
20438
+ }
20439
+ };
20440
+ async function privateOperation2(path2, stage, operation) {
20441
+ try {
20442
+ return await operation();
20443
+ } catch (cause) {
20444
+ if (cause instanceof PrivateFileError2)
20445
+ throw cause;
20446
+ throw new PrivateFileError2(path2, stage, cause);
20447
+ }
20448
+ }
20449
+ var safeParentOptionsForTest2;
20450
+ async function verifySafeDirectory2(path2, options) {
20451
+ path2 = resolve9(path2);
20452
+ options ??= safeParentOptionsForTest2;
20453
+ await privateOperation2(path2, "safe-parent", async () => {
20454
+ const result = await (await loadBackend2()).verifySafeParent(path2, options);
20455
+ if (result.ok === false) {
20456
+ if (result.reason === "io-error" || result.reason === "wrong-kind")
20457
+ await lstat5(path2);
20458
+ throw new PrivateFileError2(result.level ?? result.path, "safe-parent", {
20459
+ ...result,
20460
+ code: "ERR_PRIVATE_FILES_SECURITY"
20461
+ });
20462
+ }
20463
+ });
20464
+ }
20465
+ async function verifyPrivate2(path2, kind, migrate = false) {
20466
+ path2 = resolve9(path2);
20467
+ if (kind === "directory")
20468
+ return verifySafeDirectory2(path2);
20469
+ await privateOperation2(path2, "verify", async () => {
20470
+ const api = await loadBackend2();
20471
+ const result = await api.verifyOwnerOnly(path2);
20472
+ let repaired = false;
20473
+ if (!result.ok) {
20474
+ const { reason } = result.refusal;
20475
+ if (reason === "io-error")
20476
+ await api.verifyPrivatePath(path2, kind);
20477
+ if (migrate && [
20478
+ api.EXTRA_ACE,
20479
+ api.NOT_PROTECTED,
20480
+ api.NULL_DACL,
20481
+ api.EMPTY_DACL
20482
+ ].includes(reason)) {
20483
+ await verifySafeDirectory2(dirname15(path2));
20484
+ await api.securePrivatePath(path2, kind);
20485
+ repaired = true;
20486
+ } else {
20487
+ throw Object.assign(new Error("Owner-only verification refused"), {
20488
+ reason,
20489
+ code: "ERR_PRIVATE_FILES_SECURITY"
20490
+ });
20491
+ }
20492
+ }
20493
+ await api.verifyPrivatePath(path2, kind);
20494
+ if (repaired && !migrationNotices2.has(path2)) {
20495
+ migrationNotices2.add(path2);
20496
+ process.emitWarning(`Private permissions tightened: ${path2}. This object may have been readable before; rotate credentials if needed.`, "PrivateFileMigration");
20497
+ }
20498
+ });
20499
+ }
20500
+ async function ensurePrivateDirectory3(path2, _migrate = false, options) {
20501
+ path2 = resolve9(path2);
20502
+ await privateOperation2(path2, "directory", async () => {
20503
+ const api = await loadBackend2();
20504
+ try {
20505
+ await lstat5(path2);
20506
+ return await verifySafeDirectory2(path2, options);
20507
+ } catch (error) {
20508
+ if (ioCode2(error) !== "ENOENT")
20509
+ throw error;
20510
+ }
20511
+ const parent = dirname15(path2);
20512
+ if (parent === path2)
20513
+ throw Object.assign(new Error("Missing root"), { code: "ENOENT" });
20514
+ await ensurePrivateDirectory3(parent, false, options);
20515
+ try {
20516
+ await api.createOwnerOnly(path2, { kind: "dir" });
20517
+ } catch (error) {
20518
+ if (ioCode2(error) !== "EEXIST")
20519
+ throw error;
20520
+ }
20521
+ await verifySafeDirectory2(path2, options);
20522
+ });
20523
+ }
20524
+ async function createPrivateBytes2(path2, bytes) {
20525
+ await verifySafeDirectory2(dirname15(resolve9(path2)));
20526
+ await privateOperation2(path2, "create", async () => {
20527
+ await (await loadBackend2()).createPrivateFile(resolve9(path2), bytes);
20528
+ });
20529
+ }
20530
+ async function replaceWindowsFile2(from, to, options = {}) {
20531
+ from = resolve9(from);
20532
+ to = resolve9(to);
20533
+ const now = options.now ?? (() => performance.now());
20534
+ const start = now();
20535
+ const deadline = Math.min(start + 500, options.deadline ?? Infinity);
20536
+ const delays = [0, 10, 20, 40, 80, 100];
20537
+ let original;
20538
+ let attempts = 0;
20539
+ for (const delay of delays) {
20540
+ if (now() >= deadline)
20541
+ break;
20542
+ if (delay)
20543
+ await (options.sleep ?? ((ms) => new Promise((r) => setTimeout(r, ms))))(Math.min(delay, Math.max(0, deadline - now())));
20544
+ if (now() >= deadline)
20545
+ break;
20546
+ await options.beforeRename?.();
20547
+ if (now() >= deadline)
20548
+ break;
20549
+ attempts++;
20550
+ try {
20551
+ await (options.rename ?? rename8)(from, to);
20552
+ return { attempts, elapsedMs: now() - start };
20553
+ } catch (error2) {
20554
+ original ??= error2;
20555
+ const detail = error2;
20556
+ const candidate = detail.win32Code !== void 0 ? detail.win32Code === 32 || detail.win32Code === 33 : ["EBUSY", "EPERM", "EACCES"].includes(detail.code ?? "") && !detail.reason;
20557
+ if (!candidate)
20558
+ break;
20559
+ }
20560
+ }
20561
+ const error = new PrivateFileError2(to, "rename", original ?? Object.assign(new Error("Publication deadline expired"), {
20562
+ code: "ETIMEDOUT"
20563
+ }));
20564
+ error.attempts = attempts;
20565
+ error.elapsedMs = now() - start;
20566
+ throw error;
20567
+ }
19439
20568
 
19440
20569
  // src/common-auth-embedded/logger/redact.js
19441
20570
  var SECRET_KEY_EXACT2 = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
@@ -19534,6 +20663,69 @@ function rotateIfNeeded2(f) {
19534
20663
  } catch {
19535
20664
  }
19536
20665
  }
20666
+ async function closeWindowsFile2(sink) {
20667
+ const { file, handle } = sink;
20668
+ sink.file = void 0;
20669
+ sink.handle = void 0;
20670
+ if (file && handle)
20671
+ await privateOperation2(file, "log-close", () => handle.close());
20672
+ }
20673
+ async function openWindowsFile2(sink, file) {
20674
+ await ensurePrivateDirectory3(dirname16(file));
20675
+ try {
20676
+ await verifyPrivate2(file, "file", true);
20677
+ } catch (error) {
20678
+ if (error.code !== "ENOENT")
20679
+ throw error;
20680
+ try {
20681
+ await createPrivateBytes2(file, "");
20682
+ } catch (creationError) {
20683
+ if (creationError.code !== "EEXIST")
20684
+ throw creationError;
20685
+ await verifyPrivate2(file, "file", true);
20686
+ }
20687
+ }
20688
+ sink.handle = await privateOperation2(file, "log-open", () => open10(file, "a"));
20689
+ sink.file = file;
20690
+ return sink.handle;
20691
+ }
20692
+ async function flushWindowsFile2(sink, file, text2) {
20693
+ file = resolve10(file);
20694
+ try {
20695
+ if (sink.file !== file)
20696
+ await closeWindowsFile2(sink);
20697
+ let handle = sink.handle ?? await openWindowsFile2(sink, file);
20698
+ const info = await privateOperation2(file, "log-stat", () => handle.stat());
20699
+ if (info.size >= MAX_BYTES2) {
20700
+ await closeWindowsFile2(sink);
20701
+ for (let i = ROTATE_KEEP2 - 1; i >= 0; i--) {
20702
+ const source = i === 0 ? file : `${file}.${i}`;
20703
+ const target = `${file}.${i + 1}`;
20704
+ try {
20705
+ await verifyPrivate2(source, "file", true);
20706
+ } catch (error) {
20707
+ if (error.code === "ENOENT")
20708
+ continue;
20709
+ throw error;
20710
+ }
20711
+ try {
20712
+ await verifyPrivate2(target, "file", true);
20713
+ } catch (error) {
20714
+ if (error.code !== "ENOENT")
20715
+ throw error;
20716
+ }
20717
+ await replaceWindowsFile2(source, target);
20718
+ await verifyPrivate2(target, "file");
20719
+ }
20720
+ handle = await openWindowsFile2(sink, file);
20721
+ }
20722
+ await privateOperation2(file, "log-append", () => handle.appendFile(text2, "utf8"));
20723
+ } catch (error) {
20724
+ await closeWindowsFile2(sink).catch(() => {
20725
+ });
20726
+ throw error;
20727
+ }
20728
+ }
19537
20729
  function safeSerialize2(data) {
19538
20730
  try {
19539
20731
  return ` ${JSON.stringify(data)}`;
@@ -19549,7 +20741,20 @@ function createEngine2(options) {
19549
20741
  let captureSink;
19550
20742
  let buffer = [];
19551
20743
  let timer;
20744
+ let orderedSink = Promise.resolve();
20745
+ let sinkError;
20746
+ const windowsFile = {};
20747
+ function queueWindows(operation) {
20748
+ const next = orderedSink.then(operation);
20749
+ orderedSink = next.catch((error) => {
20750
+ sinkError = error;
20751
+ });
20752
+ return next;
20753
+ }
19552
20754
  function configure(next) {
20755
+ if (windowsPrivateFiles2 && next.file !== logFileSource)
20756
+ void queueWindows(() => closeWindowsFile2(windowsFile)).catch(() => {
20757
+ });
19553
20758
  logFileSource = next.file;
19554
20759
  initLevelSource = next.level;
19555
20760
  redactor = createRedactor2(next);
@@ -19573,24 +20778,47 @@ function createEngine2(options) {
19573
20778
  return floor;
19574
20779
  return "info";
19575
20780
  }
19576
- function flushLogs3() {
20781
+ function flushLogs3(close = true) {
19577
20782
  if (timer) {
19578
20783
  clearTimeout(timer);
19579
20784
  timer = void 0;
19580
20785
  }
19581
- if (!buffer.length)
20786
+ if (!buffer.length) {
20787
+ if (windowsPrivateFiles2)
20788
+ return queueWindows(async () => {
20789
+ if (close)
20790
+ await closeWindowsFile2(windowsFile);
20791
+ if (sinkError)
20792
+ throw sinkError;
20793
+ });
19582
20794
  return;
20795
+ }
19583
20796
  let file;
19584
20797
  try {
19585
20798
  file = logFilePath();
19586
20799
  } catch {
19587
20800
  buffer = [];
20801
+ if (windowsPrivateFiles2 && close)
20802
+ return queueWindows(() => closeWindowsFile2(windowsFile));
19588
20803
  return;
19589
20804
  }
19590
20805
  const text2 = buffer.join("");
19591
20806
  buffer = [];
19592
- if (!file)
20807
+ if (!file) {
20808
+ if (windowsPrivateFiles2 && close)
20809
+ return queueWindows(() => closeWindowsFile2(windowsFile));
19593
20810
  return;
20811
+ }
20812
+ if (windowsPrivateFiles2) {
20813
+ return queueWindows(async () => {
20814
+ try {
20815
+ await flushWindowsFile2(windowsFile, file, text2);
20816
+ } finally {
20817
+ if (close)
20818
+ await closeWindowsFile2(windowsFile);
20819
+ }
20820
+ });
20821
+ }
19594
20822
  try {
19595
20823
  rotateIfNeeded2(file);
19596
20824
  if (existsSync3(file))
@@ -19603,7 +20831,10 @@ function createEngine2(options) {
19603
20831
  if (!timer)
19604
20832
  timer = setTimeout(() => {
19605
20833
  timer = void 0;
19606
- flushLogs3();
20834
+ const flushed = flushLogs3(false);
20835
+ if (flushed instanceof Promise)
20836
+ void flushed.catch(() => {
20837
+ });
19607
20838
  }, 500);
19608
20839
  }
19609
20840
  function emit(channel, level, message, data) {
@@ -19632,9 +20863,12 @@ function createEngine2(options) {
19632
20863
  if (logFileSource === void 0)
19633
20864
  return;
19634
20865
  buffer.push(line);
19635
- if (buffer.length >= 50)
19636
- flushLogs3();
19637
- else
20866
+ if (buffer.length >= 50) {
20867
+ const flushed = flushLogs3(false);
20868
+ if (flushed instanceof Promise)
20869
+ void flushed.catch(() => {
20870
+ });
20871
+ } else
19638
20872
  schedule();
19639
20873
  } catch {
19640
20874
  }
@@ -19649,6 +20883,10 @@ function createEngine2(options) {
19649
20883
  };
19650
20884
  }
19651
20885
  function reset() {
20886
+ if (windowsPrivateFiles2)
20887
+ void queueWindows(() => closeWindowsFile2(windowsFile)).catch(() => {
20888
+ });
20889
+ sinkError = void 0;
19652
20890
  buffer = [];
19653
20891
  if (timer) {
19654
20892
  clearTimeout(timer);
@@ -20192,13 +21430,13 @@ function closeDebugLog() {
20192
21430
  if (!state || !current) return Promise.resolve();
20193
21431
  state.logStream = null;
20194
21432
  if (state.logFilePath) liveLogFilePaths.delete(state.logFilePath);
20195
- return new Promise((resolve7) => {
20196
- current.once("close", () => resolve7());
20197
- current.once("error", () => resolve7());
21433
+ return new Promise((resolve13) => {
21434
+ current.once("close", () => resolve13());
21435
+ current.once("error", () => resolve13());
20198
21436
  try {
20199
21437
  current.end();
20200
21438
  } catch {
20201
- resolve7();
21439
+ resolve13();
20202
21440
  }
20203
21441
  });
20204
21442
  }
@@ -20500,7 +21738,7 @@ var LegacyAccountPoolRetiredError = class extends Error {
20500
21738
  };
20501
21739
  async function assertLegacyPoolInUse(legacyPath) {
20502
21740
  try {
20503
- await assertLegacyAccountStorageWritable(resolve5(legacyPath));
21741
+ await assertLegacyAccountStorageWritable(resolve11(legacyPath));
20504
21742
  } catch (error) {
20505
21743
  throw new LegacyAccountPoolRetiredError(legacyPath, { cause: error });
20506
21744
  }
@@ -20508,7 +21746,7 @@ async function assertLegacyPoolInUse(legacyPath) {
20508
21746
  async function loadAccounts() {
20509
21747
  const path2 = getStoragePath();
20510
21748
  await assertLegacyPoolInUse(path2);
20511
- await ensureGitignore(dirname11(path2));
21749
+ await ensureGitignore(dirname17(path2));
20512
21750
  return loadAccountStorage(path2);
20513
21751
  }
20514
21752
 
@@ -21107,12 +22345,12 @@ async function startOAuthListener({
21107
22345
  let resolveCallback;
21108
22346
  let rejectCallback;
21109
22347
  let timeoutHandle;
21110
- const callbackPromise = new Promise((resolve7, reject) => {
22348
+ const callbackPromise = new Promise((resolve13, reject) => {
21111
22349
  resolveCallback = (url) => {
21112
22350
  if (settled) return;
21113
22351
  settled = true;
21114
22352
  if (timeoutHandle) clearTimeout(timeoutHandle);
21115
- resolve7(url);
22353
+ resolve13(url);
21116
22354
  };
21117
22355
  rejectCallback = (error) => {
21118
22356
  if (settled) return;
@@ -21270,7 +22508,7 @@ async function startOAuthListener({
21270
22508
  });
21271
22509
  });
21272
22510
  const bindAddress = getBindAddress();
21273
- await new Promise((resolve7, reject) => {
22511
+ await new Promise((resolve13, reject) => {
21274
22512
  const handleError = (error) => {
21275
22513
  server.off("error", handleError);
21276
22514
  if (error.code === "EADDRINUSE") {
@@ -21286,7 +22524,7 @@ async function startOAuthListener({
21286
22524
  server.once("error", handleError);
21287
22525
  server.listen(port, bindAddress, () => {
21288
22526
  server.off("error", handleError);
21289
- resolve7();
22527
+ resolve13();
21290
22528
  });
21291
22529
  });
21292
22530
  server.on("error", (error) => {
@@ -21294,7 +22532,7 @@ async function startOAuthListener({
21294
22532
  });
21295
22533
  return {
21296
22534
  waitForCallback: () => callbackPromise,
21297
- close: () => new Promise((resolve7, reject) => {
22535
+ close: () => new Promise((resolve13, reject) => {
21298
22536
  server.close((error) => {
21299
22537
  if (error && error.code !== "ERR_SERVER_NOT_RUNNING") {
21300
22538
  reject(error);
@@ -21303,7 +22541,7 @@ async function startOAuthListener({
21303
22541
  if (!settled) {
21304
22542
  rejectCallback(new Error("OAuth listener closed before callback"));
21305
22543
  }
21306
- resolve7();
22544
+ resolve13();
21307
22545
  });
21308
22546
  })
21309
22547
  };
@@ -21620,7 +22858,7 @@ function present(value) {
21620
22858
  return value === null ? void 0 : value;
21621
22859
  }
21622
22860
  function cliAccountOf(row) {
21623
- const metadata = row.metadata.status === "present" ? row.metadata.metadata : void 0;
22861
+ const metadata2 = row.metadata.status === "present" ? row.metadata.metadata : void 0;
21624
22862
  const groups = row.quota.status === "present" ? row.quota.quota.cachedQuota : void 0;
21625
22863
  const cachedQuota = {};
21626
22864
  for (const [name, group] of Object.entries(groups ?? {})) {
@@ -21630,19 +22868,19 @@ function cliAccountOf(row) {
21630
22868
  ...typeof group.resetTime === "string" ? { resetTime: group.resetTime } : {}
21631
22869
  };
21632
22870
  }
21633
- const email = present(metadata?.email);
21634
- const projectId = present(metadata?.projectId);
21635
- const managedProjectId = present(metadata?.managedProjectId);
22871
+ const email = present(metadata2?.email);
22872
+ const projectId = present(metadata2?.projectId);
22873
+ const managedProjectId = present(metadata2?.managedProjectId);
21636
22874
  return {
21637
22875
  refreshToken: row.credential?.refreshToken ?? "",
21638
- addedAt: metadata?.addedAt ?? row.storeAddedAt ?? 0,
21639
- lastUsed: metadata?.lastUsed ?? 0,
22876
+ addedAt: metadata2?.addedAt ?? row.storeAddedAt ?? 0,
22877
+ lastUsed: metadata2?.lastUsed ?? 0,
21640
22878
  enabled: row.enabled,
21641
22879
  ...email !== void 0 ? { email } : {},
21642
22880
  ...projectId !== void 0 ? { projectId } : {},
21643
22881
  ...managedProjectId !== void 0 ? { managedProjectId } : {},
21644
- ...metadata?.verificationRequired === true ? { verificationRequired: true } : {},
21645
- ...metadata?.accountIneligible === true ? { accountIneligible: true } : {},
22882
+ ...metadata2?.verificationRequired === true ? { verificationRequired: true } : {},
22883
+ ...metadata2?.accountIneligible === true ? { accountIneligible: true } : {},
21646
22884
  ...Object.keys(cachedQuota).length > 0 ? { cachedQuota } : {}
21647
22885
  };
21648
22886
  }
@@ -21692,7 +22930,7 @@ async function readAccountStore(legacyPath) {
21692
22930
  function createDefaultAccountStoreOperations() {
21693
22931
  const offline = { processesStopped: true };
21694
22932
  return {
21695
- legacyPath: () => resolve6(getStoragePath()),
22933
+ legacyPath: () => resolve12(getStoragePath()),
21696
22934
  migrate: async (legacyPath) => createAccountMigrationFactory(await loadCommonAuthStoreModules())({
21697
22935
  legacyPath,
21698
22936
  offline,