@cortexkit/opencode-antigravity-auth 3.0.38 → 3.0.40

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 (129) hide show
  1. package/README.md +1 -1
  2. package/dist/cli.js +865 -357
  3. package/dist/cli.js.map +4 -4
  4. package/dist/cli.meta.json +136 -39
  5. package/dist/index.js +1509 -657
  6. package/dist/index.js.map +4 -4
  7. package/dist/index.meta.json +188 -49
  8. package/dist/server.js +1662 -803
  9. package/dist/server.js.map +4 -4
  10. package/dist/server.meta.json +1 -1
  11. package/dist/src/common-auth-embedded/claustrum/availability.d.ts +7 -1
  12. package/dist/src/common-auth-embedded/claustrum/availability.js +9 -1
  13. package/dist/src/common-auth-embedded/claustrum/custody.d.ts +11 -2
  14. package/dist/src/common-auth-embedded/claustrum/custody.js +89 -31
  15. package/dist/src/common-auth-embedded/claustrum/enrollment.d.ts +29 -4
  16. package/dist/src/common-auth-embedded/claustrum/enrollment.js +110 -2
  17. package/dist/src/common-auth-embedded/claustrum/host.js +11 -7
  18. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  19. package/dist/src/common-auth-embedded/claustrum/index.js +1 -1
  20. package/dist/src/common-auth-embedded/fs/lock-record.js +55 -0
  21. package/dist/src/common-auth-embedded/fs/refresh-file-lock.js +148 -92
  22. package/dist/src/common-auth-embedded/fs/with-lock.js +19 -13
  23. package/dist/src/common-auth-embedded/quota-sidebar/index.d.ts +2 -36
  24. package/dist/src/common-auth-embedded/quota-sidebar/index.tsx +49 -607
  25. package/dist/src/common-auth-embedded/routing-accessor/cache-policy.d.ts +3 -0
  26. package/dist/src/common-auth-embedded/routing-accessor/cache-policy.js +11 -0
  27. package/dist/src/common-auth-embedded/routing-accessor/index.d.ts +48 -5
  28. package/dist/src/common-auth-embedded/routing-accessor/index.js +136 -5
  29. package/dist/src/common-auth-embedded/setup/command-error.d.ts +1 -1
  30. package/dist/src/common-auth-embedded/setup/command-error.js +3 -2
  31. package/dist/src/common-auth-embedded/setup/command.js +18 -5
  32. package/dist/src/common-auth-embedded/setup/enroll.d.ts +2 -2
  33. package/dist/src/common-auth-embedded/setup/enroll.js +14 -3
  34. package/dist/src/common-auth-embedded/setup/enrollment-access.js +77 -0
  35. package/dist/src/common-auth-embedded/setup/index.d.ts +1 -1
  36. package/dist/src/common-auth-embedded/setup/types.d.ts +13 -1
  37. package/dist/src/common-auth-embedded/source-output.json +95 -79
  38. package/dist/src/ga/tui/host-ga.d.ts +20 -3
  39. package/dist/src/ga/tui/host-ga.d.ts.map +1 -1
  40. package/dist/src/ga/tui/host-ga.js +102 -25
  41. package/dist/src/ga/tui/host-ga.js.map +1 -1
  42. package/dist/src/plugin/__fixtures__/release-model-ids.d.ts.map +1 -1
  43. package/dist/src/plugin/__fixtures__/release-model-ids.js +1 -0
  44. package/dist/src/plugin/__fixtures__/release-model-ids.js.map +1 -1
  45. package/dist/src/plugin/__fixtures__/verified-store.js +2 -2
  46. package/dist/src/plugin/ga-location-services.d.ts +1 -0
  47. package/dist/src/plugin/ga-location-services.d.ts.map +1 -1
  48. package/dist/src/plugin/ga-location-services.js +6 -0
  49. package/dist/src/plugin/ga-location-services.js.map +1 -1
  50. package/dist/src/plugin/logger.d.ts +3 -1
  51. package/dist/src/plugin/logger.d.ts.map +1 -1
  52. package/dist/src/plugin/logger.js +15 -7
  53. package/dist/src/plugin/logger.js.map +1 -1
  54. package/dist/src/plugin/request.d.ts.map +1 -1
  55. package/dist/src/plugin/request.js +3 -1
  56. package/dist/src/plugin/request.js.map +1 -1
  57. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  58. package/dist/src/plugin/shared/request-services.js +34 -9
  59. package/dist/src/plugin/shared/request-services.js.map +1 -1
  60. package/dist/src/plugin/shared/vault-billing.d.ts +30 -0
  61. package/dist/src/plugin/shared/vault-billing.d.ts.map +1 -0
  62. package/dist/src/plugin/shared/vault-billing.js +196 -0
  63. package/dist/src/plugin/shared/vault-billing.js.map +1 -0
  64. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  65. package/dist/src/plugin/vault-custody.js +3 -0
  66. package/dist/src/plugin/vault-custody.js.map +1 -1
  67. package/dist/src/setup.d.ts.map +1 -1
  68. package/dist/src/setup.js +14 -0
  69. package/dist/src/setup.js.map +1 -1
  70. package/dist/tui-build-map.json +19 -5
  71. package/dist/tui-ga-build-map.json +23 -9
  72. package/dist/types/src/common-auth-embedded/claustrum/availability.d.ts +7 -1
  73. package/dist/types/src/common-auth-embedded/claustrum/custody.d.ts +11 -2
  74. package/dist/types/src/common-auth-embedded/claustrum/enrollment.d.ts +29 -4
  75. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  76. package/dist/types/src/common-auth-embedded/routing-accessor/cache-policy.d.ts +3 -0
  77. package/dist/types/src/common-auth-embedded/routing-accessor/index.d.ts +48 -5
  78. package/dist/types/src/common-auth-embedded/setup/command-error.d.ts +1 -1
  79. package/dist/types/src/common-auth-embedded/setup/enroll.d.ts +2 -2
  80. package/dist/types/src/common-auth-embedded/setup/index.d.ts +1 -1
  81. package/dist/types/src/common-auth-embedded/setup/types.d.ts +13 -1
  82. package/dist/types/src/plugin/ga-location-services.d.ts +1 -0
  83. package/dist/types/src/plugin/ga-location-services.d.ts.map +1 -1
  84. package/dist/types/src/plugin/logger.d.ts +3 -1
  85. package/dist/types/src/plugin/logger.d.ts.map +1 -1
  86. package/dist/types/src/plugin/request.d.ts.map +1 -1
  87. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  88. package/dist/types/src/plugin/shared/vault-billing.d.ts +30 -0
  89. package/dist/types/src/plugin/shared/vault-billing.d.ts.map +1 -0
  90. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  91. package/dist/types/src/setup.d.ts.map +1 -1
  92. package/package.json +4 -3
  93. package/src/common-auth-embedded/claustrum/availability.d.ts +7 -1
  94. package/src/common-auth-embedded/claustrum/availability.js +9 -1
  95. package/src/common-auth-embedded/claustrum/custody.d.ts +11 -2
  96. package/src/common-auth-embedded/claustrum/custody.js +89 -31
  97. package/src/common-auth-embedded/claustrum/enrollment.d.ts +29 -4
  98. package/src/common-auth-embedded/claustrum/enrollment.js +110 -2
  99. package/src/common-auth-embedded/claustrum/host.js +11 -7
  100. package/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  101. package/src/common-auth-embedded/claustrum/index.js +1 -1
  102. package/src/common-auth-embedded/fs/lock-record.js +55 -0
  103. package/src/common-auth-embedded/fs/refresh-file-lock.js +148 -92
  104. package/src/common-auth-embedded/fs/with-lock.js +19 -13
  105. package/src/common-auth-embedded/quota-sidebar/index.d.ts +2 -36
  106. package/src/common-auth-embedded/quota-sidebar/index.tsx +49 -607
  107. package/src/common-auth-embedded/routing-accessor/cache-policy.d.ts +3 -0
  108. package/src/common-auth-embedded/routing-accessor/cache-policy.js +11 -0
  109. package/src/common-auth-embedded/routing-accessor/index.d.ts +48 -5
  110. package/src/common-auth-embedded/routing-accessor/index.js +136 -5
  111. package/src/common-auth-embedded/setup/command-error.d.ts +1 -1
  112. package/src/common-auth-embedded/setup/command-error.js +3 -2
  113. package/src/common-auth-embedded/setup/command.js +18 -5
  114. package/src/common-auth-embedded/setup/enroll.d.ts +2 -2
  115. package/src/common-auth-embedded/setup/enroll.js +14 -3
  116. package/src/common-auth-embedded/setup/enrollment-access.js +77 -0
  117. package/src/common-auth-embedded/setup/index.d.ts +1 -1
  118. package/src/common-auth-embedded/setup/types.d.ts +13 -1
  119. package/src/common-auth-embedded/source-output.json +95 -79
  120. package/src/tui-compiled/common-auth-embedded/quota-sidebar/index.js +36 -674
  121. package/src/tui-compiled/shared/a75d0d866c227b3f-index.js +678 -0
  122. package/src/tui-ga-compiled/host-ga.js +86 -26
  123. package/src/tui-ga-compiled/shared/a75d0d866c227b3f-index.js +678 -0
  124. package/src/tui-ga-compiled/shared/e4ec36f367492969-index.js +36 -674
  125. package/src/tui-ga-raw/host-ga.tsx +122 -25
  126. package/src/tui-ga-raw/shared/a75d0d866c227b3f-index.tsx +681 -0
  127. package/src/tui-ga-raw/shared/e4ec36f367492969-index.tsx +49 -607
  128. package/src/tui-raw/common-auth-embedded/quota-sidebar/index.tsx +49 -607
  129. package/src/tui-raw/shared/a75d0d866c227b3f-index.tsx +681 -0
package/dist/cli.js CHANGED
@@ -5851,6 +5851,8 @@ function getResolverAliasMap() {
5851
5851
  }
5852
5852
  function getQuotaGroupForModel(modelId, hasArgonPool = false) {
5853
5853
  const normalized = modelId.toLowerCase();
5854
+ if (isGeminiCarbonModel(normalized))
5855
+ return "gemini";
5854
5856
  if (isGeminiArgonModel(normalized))
5855
5857
  return hasArgonPool ? "gemini-argon" : void 0;
5856
5858
  return QUOTA_GROUP_BY_MODEL_ID[normalized] ?? // Check Claude / GPT-OSS substrings BEFORE the `gemini` substring so
@@ -5863,6 +5865,9 @@ function getQuotaGroupForModel(modelId, hasArgonPool = false) {
5863
5865
  function isGeminiArgonModel(model) {
5864
5866
  return /^(?:antigravity-)?gemini-4-argon(?:-(?:low|medium|high))?$/.test(model.toLowerCase());
5865
5867
  }
5868
+ function isGeminiCarbonModel(model) {
5869
+ return /^(?:antigravity-)?gemini-4-carbon(?:-(?:low|medium|high))?$/.test(model.toLowerCase());
5870
+ }
5866
5871
  var DEFAULT_MODALITIES, MODEL_RELEASE_DATE, DEFAULT_COST, DEFAULT_OPTIONS, ALL_MODEL_DEFINITIONS, RESOLVER_ALIASES, QUOTA_GROUP_BY_MODEL_ID, ANTIGRAVITY_OPENCODE_MODEL_IDS, OPENCODE_MODEL_DEFINITIONS;
5867
5872
  var init_model_registry = __esm({
5868
5873
  "../core/dist/model-registry.js"() {
@@ -5886,6 +5891,17 @@ var init_model_registry = __esm({
5886
5891
  high: { thinkingLevel: "high" }
5887
5892
  }
5888
5893
  }),
5894
+ "antigravity-gemini-4-carbon": defineModel("antigravity-gemini-4-carbon", {
5895
+ name: "Gemini 4 Carbon (Antigravity)",
5896
+ reasoning: true,
5897
+ limit: { context: 1048576, output: 262144 },
5898
+ modalities: DEFAULT_MODALITIES,
5899
+ variants: {
5900
+ low: { thinkingLevel: "low" },
5901
+ medium: { thinkingLevel: "medium" },
5902
+ high: { thinkingLevel: "high" }
5903
+ }
5904
+ }),
5889
5905
  "antigravity-gemini-3.1-flash-image": defineModel("antigravity-gemini-3.1-flash-image", {
5890
5906
  name: "Gemini 3.1 Flash Image (Antigravity)",
5891
5907
  reasoning: false,
@@ -5933,6 +5949,9 @@ var init_model_registry = __esm({
5933
5949
  })
5934
5950
  };
5935
5951
  RESOLVER_ALIASES = {
5952
+ "gemini-4-carbon-low": "gemini-4-carbon",
5953
+ "gemini-4-carbon-medium": "gemini-4-carbon",
5954
+ "gemini-4-carbon-high": "gemini-4-carbon",
5936
5955
  "gemini-4-argon-low": "gemini-4-argon",
5937
5956
  "gemini-4-argon-medium": "gemini-4-argon",
5938
5957
  "gemini-4-argon-high": "gemini-4-argon",
@@ -5994,6 +6013,7 @@ var init_model_registry = __esm({
5994
6013
  };
5995
6014
  ANTIGRAVITY_OPENCODE_MODEL_IDS = [
5996
6015
  "antigravity-gemini-4-argon",
6016
+ "antigravity-gemini-4-carbon",
5997
6017
  "antigravity-gemini-3.8-flash",
5998
6018
  "antigravity-gemini-3.1-flash-image",
5999
6019
  "antigravity-claude-sonnet-5-5",
@@ -6104,7 +6124,7 @@ async function rmEvictingDir(evictingPath) {
6104
6124
  });
6105
6125
  }
6106
6126
  async function sleep(ms) {
6107
- await new Promise((resolve22) => setTimeout(resolve22, ms));
6127
+ await new Promise((resolve24) => setTimeout(resolve24, ms));
6108
6128
  }
6109
6129
  async function acquireFencedFileLock(options) {
6110
6130
  const lockPath = `${options.path}.${options.name}.lock`;
@@ -6220,8 +6240,8 @@ function buildLock(lockPath, evictingPath, ownerId, options, now) {
6220
6240
  let released = false;
6221
6241
  let lost = false;
6222
6242
  let lostResolve = null;
6223
- let lostPromise = new Promise((resolve22) => {
6224
- lostResolve = resolve22;
6243
+ let lostPromise = new Promise((resolve24) => {
6244
+ lostResolve = resolve24;
6225
6245
  });
6226
6246
  const markLost = () => {
6227
6247
  if (lost)
@@ -6231,9 +6251,9 @@ function buildLock(lockPath, evictingPath, ownerId, options, now) {
6231
6251
  clearInterval(renewTimer);
6232
6252
  renewTimer = null;
6233
6253
  }
6234
- const resolve22 = lostResolve;
6254
+ const resolve24 = lostResolve;
6235
6255
  lostResolve = null;
6236
- resolve22?.();
6256
+ resolve24?.();
6237
6257
  };
6238
6258
  const setupRenew = () => {
6239
6259
  if (options.renew === false)
@@ -6875,7 +6895,7 @@ var init_account_storage = __esm({
6875
6895
  }
6876
6896
  };
6877
6897
  RETRY_DELAYS_MS = [100, 200, 400, 800, 1e3];
6878
- DEFAULT_SLEEP = (ms) => new Promise((resolve22) => setTimeout(resolve22, ms));
6898
+ DEFAULT_SLEEP = (ms) => new Promise((resolve24) => setTimeout(resolve24, ms));
6879
6899
  DEFAULT_BUILD_BACKUP_PATH = (path2, now) => `${path2}.corrupt-${now.toISOString().replace(/[:.]/g, "-")}`;
6880
6900
  }
6881
6901
  });
@@ -7043,7 +7063,7 @@ function getHttpsProxy(url) {
7043
7063
  }
7044
7064
  }
7045
7065
  function waitForHead(socket, timeoutMs, onTimeout) {
7046
- return new Promise((resolve22, reject) => {
7066
+ return new Promise((resolve24, reject) => {
7047
7067
  let buffer = Buffer2.alloc(0);
7048
7068
  const timeout = setTimeout(() => {
7049
7069
  onTimeout();
@@ -7066,7 +7086,7 @@ function waitForHead(socket, timeoutMs, onTimeout) {
7066
7086
  return;
7067
7087
  const head = buffer.subarray(0, marker).toString("latin1");
7068
7088
  const leftover = buffer.subarray(marker + 4);
7069
- cleanup2(() => resolve22({ head, leftover }));
7089
+ cleanup2(() => resolve24({ head, leftover }));
7070
7090
  };
7071
7091
  socket.on("data", onData);
7072
7092
  socket.once("error", onError);
@@ -7080,7 +7100,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
7080
7100
  port: Number(proxyUrl.port || DEFAULT_PROXY_PORT),
7081
7101
  signal: signal ?? void 0
7082
7102
  });
7083
- await new Promise((resolve22, reject) => {
7103
+ await new Promise((resolve24, reject) => {
7084
7104
  const timeout = setTimeout(() => {
7085
7105
  onDebug?.(`agy transport proxy connect timeout after ${timeoutMs}ms`);
7086
7106
  proxySocket.destroy();
@@ -7089,7 +7109,7 @@ async function connectViaProxy(proxyUrl, targetUrl, timeoutMs, signal, onDebug)
7089
7109
  const cleanup2 = () => clearTimeout(timeout);
7090
7110
  proxySocket.once("connect", () => {
7091
7111
  cleanup2();
7092
- resolve22();
7112
+ resolve24();
7093
7113
  });
7094
7114
  proxySocket.once("error", (error) => {
7095
7115
  cleanup2();
@@ -7114,7 +7134,7 @@ Host: ${targetHost}:${targetPort}\r
7114
7134
  if (leftover.length > 0) {
7115
7135
  proxySocket.unshift(leftover);
7116
7136
  }
7117
- return await new Promise((resolve22, reject) => {
7137
+ return await new Promise((resolve24, reject) => {
7118
7138
  const tlsOptions = {
7119
7139
  socket: proxySocket,
7120
7140
  servername: targetHost,
@@ -7129,7 +7149,7 @@ Host: ${targetHost}:${targetPort}\r
7129
7149
  const cleanup2 = () => clearTimeout(timeout);
7130
7150
  tlsSocket.once("secureConnect", () => {
7131
7151
  cleanup2();
7132
- resolve22(tlsSocket);
7152
+ resolve24(tlsSocket);
7133
7153
  });
7134
7154
  tlsSocket.once("error", (error) => {
7135
7155
  cleanup2();
@@ -7138,7 +7158,7 @@ Host: ${targetHost}:${targetPort}\r
7138
7158
  });
7139
7159
  }
7140
7160
  async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
7141
- return await new Promise((resolve22, reject) => {
7161
+ return await new Promise((resolve24, reject) => {
7142
7162
  const tlsOptions = {
7143
7163
  host: targetUrl.hostname,
7144
7164
  port: Number(targetUrl.port || DEFAULT_HTTPS_PORT),
@@ -7154,7 +7174,7 @@ async function connectDirect(targetUrl, timeoutMs, signal, onDebug) {
7154
7174
  const cleanup2 = () => clearTimeout(timeout);
7155
7175
  socket.once("secureConnect", () => {
7156
7176
  cleanup2();
7157
- resolve22(socket);
7177
+ resolve24(socket);
7158
7178
  });
7159
7179
  socket.once("error", (error) => {
7160
7180
  cleanup2();
@@ -8711,6 +8731,45 @@ var init_atomic_write2 = __esm({
8711
8731
  }
8712
8732
  });
8713
8733
 
8734
+ // ../core/dist/common-auth-embedded/fs/lock-record.js
8735
+ import { resolve as resolve3 } from "node:path";
8736
+ function isWindowsAccessDeniedRead(error, paths) {
8737
+ return error instanceof PrivateFileError && error.reason === "io-error" && error.win32Code === 5 && (error.stage === "read" || error.stage === "verify") && paths.some((path2) => resolve3(path2) === error.path);
8738
+ }
8739
+ function isWindowsAccessDeniedCreate(error, paths, stage) {
8740
+ return error instanceof PrivateFileError && error.reason === "io-error" && error.win32Code === 5 && error.stage === stage && paths.some((path2) => resolve3(path2) === error.path);
8741
+ }
8742
+ async function readLockRecord(path2, read) {
8743
+ try {
8744
+ return await read();
8745
+ } catch (error) {
8746
+ if (!isWindowsAccessDeniedRead(error, [path2]))
8747
+ throw error;
8748
+ try {
8749
+ return await read();
8750
+ } catch (recheckError) {
8751
+ if (recheckError.code === "ENOENT")
8752
+ throw new DisappearedLockRecordError(path2, error);
8753
+ throw error;
8754
+ }
8755
+ }
8756
+ }
8757
+ var DisappearedLockRecordError;
8758
+ var init_lock_record = __esm({
8759
+ "../core/dist/common-auth-embedded/fs/lock-record.js"() {
8760
+ "use strict";
8761
+ init_private_files();
8762
+ DisappearedLockRecordError = class extends Error {
8763
+ path;
8764
+ code = "ENOENT";
8765
+ constructor(path2, cause) {
8766
+ super(`Lock record disappeared: ${path2}`, { cause });
8767
+ this.path = path2;
8768
+ }
8769
+ };
8770
+ }
8771
+ });
8772
+
8714
8773
  // ../core/dist/common-auth-embedded/fs/refresh-file-lock.js
8715
8774
  import { randomUUID as randomUUID7 } from "node:crypto";
8716
8775
  import { link as link2, lstat as lstat3, mkdir as mkdir7, open as open4, readFile as readFile5, rename as rename6, rm as rm4, stat as stat3 } from "node:fs/promises";
@@ -8793,8 +8852,8 @@ async function acquireRefreshFileLockWithClock(options) {
8793
8852
  let releaseConfirmed = false;
8794
8853
  let loss;
8795
8854
  let resolveLoss;
8796
- const lostPromise = new Promise((resolve22) => {
8797
- resolveLoss = resolve22;
8855
+ const lostPromise = new Promise((resolve24) => {
8856
+ resolveLoss = resolve24;
8798
8857
  });
8799
8858
  function notifyTimerStep(event) {
8800
8859
  try {
@@ -8832,15 +8891,18 @@ async function acquireRefreshFileLockWithClock(options) {
8832
8891
  const evictOwnerId = randomUUID7();
8833
8892
  const EVICT_TTL = 5e3;
8834
8893
  const MAX_STEAL_ATTEMPTS = 8;
8894
+ function isChangingLockCreate(error) {
8895
+ return windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [lockPath], "create") || isWindowsAccessDeniedCreate(error, [evictPath], "directory-create"));
8896
+ }
8835
8897
  async function readOwner() {
8836
8898
  if (windowsPrivateFiles) {
8837
8899
  try {
8838
- return JSON.parse(await readPrivateText(lockPath, true));
8900
+ return JSON.parse(await readLockRecord(lockPath, () => readPrivateText(lockPath, true)));
8839
8901
  } catch (error) {
8840
8902
  if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
8841
8903
  throw error;
8842
- await verifyPrivate(lockPath, "directory", true);
8843
- return JSON.parse(await readPrivateText(legacyOwnerPath, true));
8904
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
8905
+ return JSON.parse(await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true)));
8844
8906
  }
8845
8907
  }
8846
8908
  try {
@@ -8916,8 +8978,8 @@ async function acquireRefreshFileLockWithClock(options) {
8916
8978
  await options.onStep("lease-contention-read-ready");
8917
8979
  try {
8918
8980
  if (code2 === "EISDIR") {
8919
- await verifyPrivate(lockPath, "directory", true);
8920
- await readPrivateText(legacyOwnerPath, true);
8981
+ await readLockRecord(lockPath, () => verifyPrivate(lockPath, "directory", true));
8982
+ await readLockRecord(legacyOwnerPath, () => readPrivateText(legacyOwnerPath, true));
8921
8983
  } else
8922
8984
  await readOwner();
8923
8985
  } catch (readError) {
@@ -8955,7 +9017,7 @@ async function acquireRefreshFileLockWithClock(options) {
8955
9017
  }
8956
9018
  }
8957
9019
  async function backoff() {
8958
- await new Promise((resolve22) => setTimeout(resolve22, Math.floor(Math.random() * 4)));
9020
+ await new Promise((resolve24) => setTimeout(resolve24, Math.floor(Math.random() * 4)));
8959
9021
  }
8960
9022
  async function readLockState(notifyReady = true) {
8961
9023
  if (notifyReady && options.onStep)
@@ -8964,6 +9026,8 @@ async function acquireRefreshFileLockWithClock(options) {
8964
9026
  try {
8965
9027
  owner = await readOwner();
8966
9028
  } catch (error) {
9029
+ if (error instanceof DisappearedLockRecordError)
9030
+ return { status: "missing" };
8967
9031
  if (windowsPrivateFiles && error.code !== "ENOENT")
8968
9032
  throw error;
8969
9033
  }
@@ -9011,7 +9075,7 @@ async function acquireRefreshFileLockWithClock(options) {
9011
9075
  }
9012
9076
  async function ownsEvictionMarker() {
9013
9077
  try {
9014
- const owner = JSON.parse(await readPrivateText(evictOwnerPath, windowsPrivateFiles));
9078
+ const owner = JSON.parse(await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, windowsPrivateFiles)));
9015
9079
  return owner?.ownerId === evictOwnerId;
9016
9080
  } catch (error) {
9017
9081
  if (windowsPrivateFiles && error.code !== "ENOENT")
@@ -9046,7 +9110,7 @@ async function acquireRefreshFileLockWithClock(options) {
9046
9110
  const remainingMs = deadline - performance.now();
9047
9111
  if (remainingMs <= 0)
9048
9112
  throw original;
9049
- await new Promise((resolve22) => setTimeout(resolve22, Math.min(delayMs, remainingMs)));
9113
+ await new Promise((resolve24) => setTimeout(resolve24, Math.min(delayMs, remainingMs)));
9050
9114
  if (performance.now() >= deadline)
9051
9115
  throw original;
9052
9116
  delayMs = Math.min(delayMs * 2, 50);
@@ -9150,7 +9214,7 @@ async function acquireRefreshFileLockWithClock(options) {
9150
9214
  }
9151
9215
  if (windowsPrivateFiles) {
9152
9216
  try {
9153
- await verifyPrivate(evictPath, "directory", true);
9217
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
9154
9218
  } catch (error) {
9155
9219
  if (error.code === "ENOENT")
9156
9220
  return "missing";
@@ -9205,8 +9269,8 @@ async function acquireRefreshFileLockWithClock(options) {
9205
9269
  if (error.code === "EEXIST") {
9206
9270
  if (windowsPrivateFiles) {
9207
9271
  try {
9208
- await verifyPrivate(evictPath, "directory", true);
9209
- await readPrivateText(evictOwnerPath, true);
9272
+ await readLockRecord(evictPath, () => verifyPrivate(evictPath, "directory", true));
9273
+ await readLockRecord(evictOwnerPath, () => readPrivateText(evictOwnerPath, true));
9210
9274
  } catch (ownerError) {
9211
9275
  if (ownerError.code !== "ENOENT")
9212
9276
  throw ownerError;
@@ -9227,7 +9291,11 @@ async function acquireRefreshFileLockWithClock(options) {
9227
9291
  try {
9228
9292
  await releaseEvictionMarker(deadline);
9229
9293
  } catch (error) {
9230
- if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
9294
+ if ((isRetryableRemoval(actionError, lockPath) || isWindowsAccessDeniedRead(actionError, [
9295
+ lockPath,
9296
+ legacyOwnerPath,
9297
+ evictOwnerPath
9298
+ ])) && (isRetryableRemoval(error, evictPath) || isWindowsAccessDeniedRead(error, [evictOwnerPath])))
9231
9299
  throw actionError;
9232
9300
  throw error;
9233
9301
  }
@@ -9243,7 +9311,7 @@ async function acquireRefreshFileLockWithClock(options) {
9243
9311
  try {
9244
9312
  owner = await readOwner();
9245
9313
  } catch (error) {
9246
- if (windowsPrivateFiles)
9314
+ if (windowsPrivateFiles && !(error instanceof DisappearedLockRecordError))
9247
9315
  throw error;
9248
9316
  return;
9249
9317
  }
@@ -9321,7 +9389,7 @@ async function acquireRefreshFileLockWithClock(options) {
9321
9389
  await options.onStep("renewal-marker-unavailable");
9322
9390
  }
9323
9391
  } catch (error) {
9324
- if (windowsPrivateFiles && error instanceof PrivateFileError) {
9392
+ if (windowsPrivateFiles && error instanceof PrivateFileError && !isChangingLockCreate(error)) {
9325
9393
  terminalIOError = error;
9326
9394
  recordLoss("renewal-failed");
9327
9395
  shouldReschedule = false;
@@ -9367,72 +9435,90 @@ async function acquireRefreshFileLockWithClock(options) {
9367
9435
  }
9368
9436
  return null;
9369
9437
  }
9370
- let acquired = await tryAcquire();
9438
+ let acquired = false;
9439
+ let changingCreateError;
9440
+ try {
9441
+ acquired = await tryAcquire();
9442
+ } catch (error) {
9443
+ if (!isChangingLockCreate(error))
9444
+ throw error;
9445
+ changingCreateError = error;
9446
+ }
9371
9447
  if (!acquired) {
9372
9448
  for (let attempt = 0; attempt < MAX_STEAL_ATTEMPTS; attempt++) {
9373
- acquired = await tryAcquire();
9374
- if (acquired)
9375
- break;
9376
- const observed = await readLockState();
9377
- if (observed.status === "live")
9378
- return contended();
9379
- if (observed.status === "missing")
9380
- continue;
9381
- if (options.onStep)
9382
- await options.onStep("stale-lock-observed");
9383
9449
  try {
9384
- if (!await tryAcquireEvictionMarker()) {
9385
- await backoff();
9386
- continue;
9387
- }
9388
- } catch (evictError) {
9389
- const code2 = evictError.code;
9390
- if (code2 !== "EEXIST")
9391
- throw evictError;
9392
- const recovered = await recoverStaleEvictionMarker();
9393
- if (recovered === "fresh")
9394
- return null;
9395
- await backoff();
9396
- continue;
9397
- }
9398
- try {
9399
- const confirmed = await readLockState();
9400
- if (confirmed.status === "live")
9450
+ acquired = await tryAcquire();
9451
+ if (acquired)
9452
+ break;
9453
+ const observed = await readLockState();
9454
+ if (observed.status === "live")
9401
9455
  return contended();
9402
- if (!sameStaleLock(observed.identity, confirmed))
9456
+ if (observed.status === "missing")
9403
9457
  continue;
9404
- if (!await ownsEvictionMarker())
9405
- return null;
9406
9458
  if (options.onStep)
9407
- await options.onStep("stale-lock-confirmed");
9408
- if (!await ownsEvictionMarker())
9409
- return null;
9410
- const current = await readLockState(false);
9411
- if (!sameStaleLock(observed.identity, current))
9459
+ await options.onStep("stale-lock-observed");
9460
+ try {
9461
+ if (!await tryAcquireEvictionMarker()) {
9462
+ await backoff();
9463
+ continue;
9464
+ }
9465
+ } catch (evictError) {
9466
+ const code2 = evictError.code;
9467
+ if (code2 !== "EEXIST")
9468
+ throw evictError;
9469
+ const recovered = await recoverStaleEvictionMarker();
9470
+ if (recovered === "fresh")
9471
+ return null;
9472
+ await backoff();
9412
9473
  continue;
9413
- await removeLeaseObject(lockPath);
9414
- if (!await ownsEvictionMarker())
9415
- return null;
9416
- if (options.onStep)
9417
- await options.onStep("stale-lock-removed");
9418
- acquired = await tryAcquire();
9419
- if (!acquired)
9420
- return null;
9421
- if (options.onStep)
9422
- await options.onStep("stale-lock-recreated");
9423
- if (!await ownsEvictionMarker()) {
9424
- await relinquishLockAfterMarkerLoss();
9425
- acquired = false;
9426
- return null;
9427
9474
  }
9428
- break;
9429
- } finally {
9430
- await releaseEvictionMarker();
9475
+ try {
9476
+ const confirmed = await readLockState();
9477
+ if (confirmed.status === "live")
9478
+ return contended();
9479
+ if (!sameStaleLock(observed.identity, confirmed))
9480
+ continue;
9481
+ if (!await ownsEvictionMarker())
9482
+ return null;
9483
+ if (options.onStep)
9484
+ await options.onStep("stale-lock-confirmed");
9485
+ if (!await ownsEvictionMarker())
9486
+ return null;
9487
+ const current = await readLockState(false);
9488
+ if (!sameStaleLock(observed.identity, current))
9489
+ continue;
9490
+ await removeLeaseObject(lockPath);
9491
+ if (!await ownsEvictionMarker())
9492
+ return null;
9493
+ if (options.onStep)
9494
+ await options.onStep("stale-lock-removed");
9495
+ acquired = await tryAcquire();
9496
+ if (!acquired)
9497
+ return null;
9498
+ if (options.onStep)
9499
+ await options.onStep("stale-lock-recreated");
9500
+ if (!await ownsEvictionMarker()) {
9501
+ await relinquishLockAfterMarkerLoss();
9502
+ acquired = false;
9503
+ return null;
9504
+ }
9505
+ break;
9506
+ } finally {
9507
+ await releaseEvictionMarker();
9508
+ }
9509
+ } catch (error) {
9510
+ if (!isChangingLockCreate(error))
9511
+ throw error;
9512
+ changingCreateError ??= error;
9513
+ await backoff();
9431
9514
  }
9432
9515
  }
9433
9516
  }
9434
- if (!acquired)
9517
+ if (!acquired) {
9518
+ if (changingCreateError)
9519
+ throw changingCreateError;
9435
9520
  return null;
9521
+ }
9436
9522
  scheduleRenewal();
9437
9523
  return {
9438
9524
  ownerId,
@@ -9470,6 +9556,7 @@ async function acquireRefreshFileLockWithClock(options) {
9470
9556
  const deadline = performance.now() + EVICT_TTL + 1e3;
9471
9557
  let delayMs = 5;
9472
9558
  let removalError;
9559
+ let changingRecordError;
9473
9560
  for (; ; ) {
9474
9561
  try {
9475
9562
  let removalConfirmed = false;
@@ -9495,6 +9582,7 @@ async function acquireRefreshFileLockWithClock(options) {
9495
9582
  await removeLeaseObject(lockPath);
9496
9583
  removalConfirmed = true;
9497
9584
  }, deadline);
9585
+ changingRecordError = void 0;
9498
9586
  if (markerAcquired) {
9499
9587
  if (windowsPrivateFiles && !removalConfirmed)
9500
9588
  throw new PrivateFileError(lockPath, "release-not-confirmed", {
@@ -9507,23 +9595,32 @@ async function acquireRefreshFileLockWithClock(options) {
9507
9595
  return;
9508
9596
  await recoverStaleEvictionMarker(deadline);
9509
9597
  } catch (error) {
9510
- if (!isRetryableRemoval(error, lockPath)) {
9598
+ const changingRecord = windowsPrivateFiles && (isChangingLockCreate(error) || isWindowsAccessDeniedRead(error, [
9599
+ lockPath,
9600
+ legacyOwnerPath,
9601
+ evictPath,
9602
+ evictOwnerPath
9603
+ ]));
9604
+ if (!isRetryableRemoval(error, lockPath) && !changingRecord) {
9511
9605
  if (windowsPrivateFiles)
9512
9606
  throw error;
9513
9607
  return;
9514
9608
  }
9515
- removalError ??= error;
9609
+ if (changingRecord)
9610
+ changingRecordError ??= error;
9611
+ else
9612
+ removalError ??= error;
9516
9613
  }
9517
9614
  const remainingMs = deadline - performance.now();
9518
9615
  if (remainingMs <= 0)
9519
9616
  break;
9520
- await new Promise((resolve22) => setTimeout(resolve22, Math.min(delayMs, remainingMs)));
9617
+ await new Promise((resolve24) => setTimeout(resolve24, Math.min(delayMs, remainingMs)));
9521
9618
  if (windowsPrivateFiles && performance.now() >= deadline)
9522
9619
  break;
9523
9620
  delayMs = Math.min(delayMs * 2, 50);
9524
9621
  }
9525
9622
  if (windowsPrivateFiles)
9526
- throw removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
9623
+ throw changingRecordError ?? removalError ?? new PrivateFileError(lockPath, "release-not-confirmed", {
9527
9624
  code: "ETIMEDOUT"
9528
9625
  });
9529
9626
  }
@@ -9533,6 +9630,7 @@ var leaseCreationTestHooks, setRefreshLockRenewalTimeout, clearRefreshLockRenewa
9533
9630
  var init_refresh_file_lock = __esm({
9534
9631
  "../core/dist/common-auth-embedded/fs/refresh-file-lock.js"() {
9535
9632
  "use strict";
9633
+ init_lock_record();
9536
9634
  init_private_files();
9537
9635
  init_with_lock();
9538
9636
  setRefreshLockRenewalTimeout = globalThis.setTimeout.bind(globalThis);
@@ -9542,22 +9640,21 @@ var init_refresh_file_lock = __esm({
9542
9640
  });
9543
9641
 
9544
9642
  // ../core/dist/common-auth-embedded/fs/with-lock.js
9545
- import { join as join6, resolve as resolve3 } from "node:path";
9643
+ import { join as join6, resolve as resolve4 } from "node:path";
9546
9644
  function lockPathFor(target, name) {
9547
9645
  return `${target}.${name}.lock`;
9548
9646
  }
9549
- function isChangingLockRead(error, target, name) {
9550
- if (!isWindowsSharingViolation(error) || error.stage !== "read" && error.stage !== "verify")
9551
- return false;
9552
- const path2 = resolve3(lockPathFor(target, name));
9553
- return error.path === path2 || error.path === join6(path2, "owner.json");
9647
+ function isChangingLockRecord(error, target, name) {
9648
+ const path2 = resolve4(lockPathFor(target, name));
9649
+ const paths = [path2, join6(path2, "owner.json")];
9650
+ return (isWindowsSharingViolation(error) || isWindowsAccessDeniedRead(error, paths)) && (error.stage === "read" || error.stage === "verify") && paths.includes(error.path) || windowsPrivateFiles && (isWindowsAccessDeniedCreate(error, [path2], "create") || isWindowsAccessDeniedCreate(error, [`${path2}.evicting`], "directory-create"));
9554
9651
  }
9555
9652
  async function withLock(target, options, fn) {
9556
9653
  const started = performance.now();
9654
+ let changingRecordError;
9557
9655
  for (; ; ) {
9558
9656
  options.signal?.throwIfAborted();
9559
9657
  let lock;
9560
- let changingReadError;
9561
9658
  try {
9562
9659
  lock = await acquireRefreshFileLock({
9563
9660
  path: target,
@@ -9567,11 +9664,12 @@ async function withLock(target, options, fn) {
9567
9664
  ...options.onStep ? { onStep: options.onStep } : {},
9568
9665
  ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
9569
9666
  });
9667
+ changingRecordError = void 0;
9570
9668
  } catch (error) {
9571
- if (!isChangingLockRead(error, target, options.name))
9669
+ if (!isChangingLockRecord(error, target, options.name))
9572
9670
  throw error;
9573
9671
  lock = null;
9574
- changingReadError = error;
9672
+ changingRecordError ??= error;
9575
9673
  }
9576
9674
  if (lock) {
9577
9675
  try {
@@ -9583,21 +9681,22 @@ async function withLock(target, options, fn) {
9583
9681
  }
9584
9682
  const remaining = options.timeoutMs - (performance.now() - started);
9585
9683
  if (remaining <= 0) {
9586
- if (changingReadError)
9587
- throw changingReadError;
9684
+ if (changingRecordError)
9685
+ throw changingRecordError;
9588
9686
  throw new LockContentionError({
9589
9687
  target,
9590
9688
  name: options.name,
9591
9689
  timeoutMs: options.timeoutMs
9592
9690
  });
9593
9691
  }
9594
- await new Promise((resolve22) => setTimeout(resolve22, Math.min(25, Math.ceil(remaining))));
9692
+ await new Promise((resolve24) => setTimeout(resolve24, Math.min(25, Math.ceil(remaining))));
9595
9693
  }
9596
9694
  }
9597
9695
  var LockContentionError, LockOwnershipError;
9598
9696
  var init_with_lock = __esm({
9599
9697
  "../core/dist/common-auth-embedded/fs/with-lock.js"() {
9600
9698
  "use strict";
9699
+ init_lock_record();
9601
9700
  init_private_files();
9602
9701
  init_refresh_file_lock();
9603
9702
  LockContentionError = class extends Error {
@@ -9680,7 +9779,7 @@ async function acquirePoolLock(spec, defaults, env3) {
9680
9779
  });
9681
9780
  }
9682
9781
  const jitter = Math.floor(Math.random() * (options.retryMs + 1));
9683
- await new Promise((resolve22) => setTimeout(resolve22, Math.min(options.retryMs + jitter, remaining)));
9782
+ await new Promise((resolve24) => setTimeout(resolve24, Math.min(options.retryMs + jitter, remaining)));
9684
9783
  }
9685
9784
  }
9686
9785
  function definedOnly(spec) {
@@ -12574,7 +12673,7 @@ var init_redact = __esm({
12574
12673
  // ../core/dist/common-auth-embedded/logger/engine.js
12575
12674
  import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
12576
12675
  import { open as open5 } from "node:fs/promises";
12577
- import { dirname as dirname8, resolve as resolve4 } from "node:path";
12676
+ import { dirname as dirname8, resolve as resolve5 } from "node:path";
12578
12677
  function chmodPrivate(path2) {
12579
12678
  try {
12580
12679
  chmodSync(path2, 384);
@@ -12625,7 +12724,7 @@ async function openWindowsFile(sink, file) {
12625
12724
  return sink.handle;
12626
12725
  }
12627
12726
  async function flushWindowsFile(sink, file, text2) {
12628
- file = resolve4(file);
12727
+ file = resolve5(file);
12629
12728
  try {
12630
12729
  if (sink.file !== file)
12631
12730
  await closeWindowsFile(sink);
@@ -13001,11 +13100,11 @@ var init_quota_writer = __esm({
13001
13100
  const left = deadline - performance.now();
13002
13101
  if (left <= 0)
13003
13102
  throw refusal2("pull", id, "lock-contention", `pool quota queue for ${id} is full (${POOL_QUOTA_QUEUE_LIMIT} readings) and the store locks stayed held`, true);
13004
- await new Promise((resolve22) => {
13103
+ await new Promise((resolve24) => {
13005
13104
  const done = () => {
13006
13105
  clearTimeout(timer);
13007
13106
  this.wake.delete(done);
13008
- resolve22();
13107
+ resolve24();
13009
13108
  };
13010
13109
  const timer = setTimeout(done, left);
13011
13110
  this.wake.add(done);
@@ -13398,7 +13497,7 @@ var init_refresh = __esm({
13398
13497
 
13399
13498
  // ../core/dist/common-auth-embedded/fs/file-read-cache.js
13400
13499
  import { lstat as lstat4, stat as stat4 } from "node:fs/promises";
13401
- import { resolve as resolve5 } from "node:path";
13500
+ import { resolve as resolve6 } from "node:path";
13402
13501
  async function identity(path2, followSymlinks) {
13403
13502
  try {
13404
13503
  const metadata = await (followSymlinks ? stat4(path2) : lstat4(path2));
@@ -13423,7 +13522,7 @@ var init_file_read_cache = __esm({
13423
13522
  this.#followSymlinks = options.followSymlinks ?? false;
13424
13523
  }
13425
13524
  async read(paths, read, validateHit) {
13426
- const resolvedPaths = paths.map((path2) => resolve5(path2));
13525
+ const resolvedPaths = paths.map((path2) => resolve6(path2));
13427
13526
  const key = JSON.stringify(resolvedPaths);
13428
13527
  const probed = await Promise.all(resolvedPaths.map((path2) => identity(path2, this.#followSymlinks)));
13429
13528
  const identities = probed.every((entry) => entry !== void 0) ? probed : void 0;
@@ -15612,9 +15711,17 @@ var init_availability = __esm({
15612
15711
  ERR_PRIVATE_FILES_SECURITY: "answered"
15613
15712
  });
15614
15713
  ClaustrumUnreachableError = class extends ClaustrumConsumerError {
15615
- constructor() {
15714
+ /**
15715
+ * Non-secret host connection diagnostic. A missing accessor can recover
15716
+ * once the host bridge installs; a failed accessor could not provide a client.
15717
+ * Other unreachable failures leave this unset. Never use adapter error text.
15718
+ */
15719
+ reason;
15720
+ constructor(reason) {
15616
15721
  super("unavailable", "Claustrum scoped operation unavailable");
15617
15722
  this.name = "ClaustrumUnreachableError";
15723
+ if (reason === "host-accessor-missing" || reason === "host-accessor-failed")
15724
+ this.reason = reason;
15618
15725
  }
15619
15726
  };
15620
15727
  }
@@ -15635,7 +15742,7 @@ function hostError(error) {
15635
15742
  if (typeof value.code === "string" && (value.class === "transient" || value.class === "permanent" || value.class === "auth_required" || value.class === "context_overflow") && (value.action === "gone" || value.action === "reauth" || value.action === "retry" || value.action === "reduce_and_retry"))
15636
15743
  return new ClaustrumCredentialError2(value.code, value.class, value.action);
15637
15744
  if (value.name === "ClaustrumUnreachableError" || typeof value.code === "string" && classifyVaultFailure(Object.assign(new Error(), { code: value.code })) === "unreachable")
15638
- return new ClaustrumUnreachableError();
15745
+ return new ClaustrumUnreachableError(value.reason === "host-accessor-missing" || value.reason === "host-accessor-failed" ? value.reason : void 0);
15639
15746
  return error;
15640
15747
  }
15641
15748
  function call(operation) {
@@ -15701,14 +15808,15 @@ function connectVaultHost(pluginId) {
15701
15808
  throw new ClaustrumUnreachableError();
15702
15809
  try {
15703
15810
  const accessor = globalThis[/* @__PURE__ */ Symbol.for("cortexkit.vault")];
15704
- if (typeof accessor !== "function")
15705
- throw new ClaustrumUnreachableError();
15706
- const client = wrapHostClient(accessor(pluginId));
15707
- hostClients.add(client);
15708
- return client;
15811
+ if (typeof accessor === "function") {
15812
+ const client = wrapHostClient(accessor(pluginId));
15813
+ hostClients.add(client);
15814
+ return client;
15815
+ }
15709
15816
  } catch {
15710
- throw new ClaustrumUnreachableError();
15817
+ throw new ClaustrumUnreachableError("host-accessor-failed");
15711
15818
  }
15819
+ throw new ClaustrumUnreachableError("host-accessor-missing");
15712
15820
  }
15713
15821
  var VAULT_HOST_STATUS, VAULT_HOST_CONNECT_REFUSAL, hostClients;
15714
15822
  var init_host = __esm({
@@ -16044,7 +16152,7 @@ async function select(terminal, items, options) {
16044
16152
  writeLine("");
16045
16153
  renderedLines = lines;
16046
16154
  };
16047
- return new Promise((resolve22) => {
16155
+ return new Promise((resolve24) => {
16048
16156
  const wasRaw = stdin.isRaw ?? false;
16049
16157
  const cleanup2 = () => {
16050
16158
  if (cleaned)
@@ -16064,7 +16172,7 @@ async function select(terminal, items, options) {
16064
16172
  };
16065
16173
  const finish = (value) => {
16066
16174
  cleanup2();
16067
- resolve22(value);
16175
+ resolve24(value);
16068
16176
  };
16069
16177
  const onSignal = () => finish(null);
16070
16178
  const onKey = (data) => {
@@ -16104,7 +16212,7 @@ async function select(terminal, items, options) {
16104
16212
  stdin.setRawMode(true);
16105
16213
  } catch {
16106
16214
  cleanup2();
16107
- resolve22(null);
16215
+ resolve24(null);
16108
16216
  return;
16109
16217
  }
16110
16218
  stdin.resume();
@@ -16840,7 +16948,7 @@ var init_watch = __esm({
16840
16948
  });
16841
16949
 
16842
16950
  // ../core/dist/common-auth-embedded/claustrum/insula.js
16843
- import { resolve as resolve6 } from "node:path";
16951
+ import { resolve as resolve7 } from "node:path";
16844
16952
  import { storeIdentity } from "@cortexkit/claustrum-client";
16845
16953
  import { SubcClient } from "@cortexkit/subc-client";
16846
16954
  function insulaUsageTransport(options) {
@@ -16968,8 +17076,8 @@ function refusalCode(error) {
16968
17076
  }
16969
17077
  function acquireInsulaQuotaSource(transport, tokenPath) {
16970
17078
  const key = JSON.stringify([
16971
- resolve6(transport.connectionFile),
16972
- resolve6(tokenPath)
17079
+ resolve7(transport.connectionFile),
17080
+ resolve7(tokenPath)
16973
17081
  ]);
16974
17082
  let shared3 = sources.get(key);
16975
17083
  if (!shared3) {
@@ -17283,7 +17391,7 @@ var init_any_signal = __esm({
17283
17391
  import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID10 } from "node:crypto";
17284
17392
  import { constants as fsConstants } from "node:fs";
17285
17393
  import { chmod as chmod2, mkdir as mkdir8, open as open6, readFile as readFile6, realpath as realpath3, rename as rename7, stat as stat5, unlink as unlink6 } from "node:fs/promises";
17286
- import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join7, resolve as resolve7 } from "node:path";
17394
+ import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join7, resolve as resolve8 } from "node:path";
17287
17395
  import { ClaustrumCredentialError as ClaustrumCredentialError3, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
17288
17396
  function classifyEnrollmentError(error) {
17289
17397
  if (!(error instanceof ClaustrumCredentialError3))
@@ -17302,6 +17410,29 @@ function enrollmentName(plugin, host) {
17302
17410
  throw new ClaustrumConsumerError("invalid-state", "Claustrum enrollment names use lowercase letters, digits and dashes");
17303
17411
  return `${plugin}-${host}`;
17304
17412
  }
17413
+ function validEnrollmentDisplayName(displayName) {
17414
+ const length = Array.from(displayName).length;
17415
+ return length >= 1 && length <= 40 && !/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\u200b-\u200d\u2060\ufeff]/u.test(displayName);
17416
+ }
17417
+ function validEnrollmentRequestedGrants(grants) {
17418
+ return Array.isArray(grants) && grants.length >= 1 && grants.length <= 4 && Array.from(grants).every((grant) => {
17419
+ if (!isRecord6(grant) || Object.keys(grant).length !== 2 || grant.operation !== "read" && grant.operation !== "list" || !isRecord6(grant.selector))
17420
+ return false;
17421
+ const keys = Object.keys(grant.selector);
17422
+ const key = keys[0];
17423
+ return keys.length === 1 && (key === "category" || key === "exact") && typeof grant.selector[key] === "string" && grant.selector[key].trim().length > 0;
17424
+ });
17425
+ }
17426
+ function grantProposal(state) {
17427
+ return {
17428
+ ...state.requestedGrants !== void 0 && {
17429
+ requestedGrants: state.requestedGrants
17430
+ },
17431
+ ...state.requestedGrantsStatus !== void 0 && {
17432
+ requestedGrantsStatus: state.requestedGrantsStatus
17433
+ }
17434
+ };
17435
+ }
17305
17436
  function connectClaustrumEnrollmentClient(options) {
17306
17437
  return ClaustrumWireClient.connect(options);
17307
17438
  }
@@ -17317,7 +17448,7 @@ function hostEnrollmentPaths(input) {
17317
17448
  const override = input.override?.trim();
17318
17449
  if (override && !isAbsolute2(override) && !input.cwd)
17319
17450
  throw new ClaustrumConsumerError("invalid-state", "A relative Claustrum enrollment override needs a base directory");
17320
- const tokenPath = override ? isAbsolute2(override) ? override : resolve7(input.cwd, override) : join7(input.stateDir, `${input.host}-enrollment.json`);
17451
+ const tokenPath = override ? isAbsolute2(override) ? override : resolve8(input.cwd, override) : join7(input.stateDir, `${input.host}-enrollment.json`);
17321
17452
  return getClaustrumEnrollmentPaths(tokenPath);
17322
17453
  }
17323
17454
  function isRecord6(value) {
@@ -17337,6 +17468,7 @@ function decodeEnrollmentState(value) {
17337
17468
  throw invalidState();
17338
17469
  }
17339
17470
  if (value.phase === "pending") {
17471
+ const grants = decodeGrantProposal(value);
17340
17472
  if (!TOKEN_RE.test(String(value.requestSecret ?? "")) || value.requestId !== void 0 && (typeof value.requestId !== "string" || value.requestId.length === 0) || !validTimestamp(value.createdAt) || !validTimestamp(value.updatedAt)) {
17341
17473
  throw invalidState();
17342
17474
  }
@@ -17349,10 +17481,12 @@ function decodeEnrollmentState(value) {
17349
17481
  requestId: value.requestId
17350
17482
  },
17351
17483
  createdAt: value.createdAt,
17352
- updatedAt: value.updatedAt
17484
+ updatedAt: value.updatedAt,
17485
+ ...grants
17353
17486
  };
17354
17487
  }
17355
17488
  if (value.phase === "approved") {
17489
+ const grants = decodeGrantProposal(value);
17356
17490
  if (value.approvedName !== void 0 && (typeof value.approvedName !== "string" || value.approvedName.length === 0) || !validGeneration(value.tokenGeneration) || !validTimestamp(value.updatedAt)) {
17357
17491
  throw invalidState();
17358
17492
  }
@@ -17364,7 +17498,8 @@ function decodeEnrollmentState(value) {
17364
17498
  approvedName: value.approvedName
17365
17499
  },
17366
17500
  tokenGeneration: value.tokenGeneration,
17367
- updatedAt: value.updatedAt
17501
+ updatedAt: value.updatedAt,
17502
+ ...grants
17368
17503
  };
17369
17504
  }
17370
17505
  if (value.phase === "denied" || value.phase === "blocked") {
@@ -17383,6 +17518,11 @@ function decodeEnrollmentState(value) {
17383
17518
  }
17384
17519
  throw invalidState();
17385
17520
  }
17521
+ function decodeGrantProposal(value) {
17522
+ if (value.requestedGrants !== void 0 && !validEnrollmentRequestedGrants(value.requestedGrants) || value.requestedGrantsStatus !== void 0 && (value.requestedGrants === void 0 || value.requestedGrantsStatus !== "sent" && value.requestedGrantsStatus !== "dropped"))
17523
+ return {};
17524
+ return grantProposal(value);
17525
+ }
17386
17526
  function decodeTokenFile(value) {
17387
17527
  if (!isRecord6(value) || !TOKEN_RE.test(String(value.token ?? "")) || !validGeneration(value.token_generation)) {
17388
17528
  throw new ClaustrumConsumerError("invalid-token", "invalid Claustrum enrollment token file");
@@ -17596,7 +17736,8 @@ async function readEnrollmentStatus(paths, proposedName) {
17596
17736
  ...state?.phase === "approved" && state.approvedName !== void 0 && {
17597
17737
  approvedName: state.approvedName
17598
17738
  },
17599
- tokenGeneration: token.token_generation
17739
+ tokenGeneration: token.token_generation,
17740
+ ...state && (state.phase === "approved" || state.phase === "pending") && grantProposal(state)
17600
17741
  }
17601
17742
  };
17602
17743
  }
@@ -17655,7 +17796,8 @@ function statusFromState(state) {
17655
17796
  return {
17656
17797
  state: "pending",
17657
17798
  proposedName: state.proposedName,
17658
- ...state.requestId !== void 0 && { requestId: state.requestId }
17799
+ ...state.requestId !== void 0 && { requestId: state.requestId },
17800
+ ...grantProposal(state)
17659
17801
  };
17660
17802
  }
17661
17803
  if (state.phase === "approved") {
@@ -17665,7 +17807,8 @@ function statusFromState(state) {
17665
17807
  ...state.approvedName !== void 0 && {
17666
17808
  approvedName: state.approvedName
17667
17809
  },
17668
- tokenGeneration: state.tokenGeneration
17810
+ tokenGeneration: state.tokenGeneration,
17811
+ ...grantProposal(state)
17669
17812
  };
17670
17813
  }
17671
17814
  if (state.phase === "denied")
@@ -17784,15 +17927,26 @@ var init_enrollment = __esm({
17784
17927
  #client;
17785
17928
  #paths;
17786
17929
  #proposedName;
17930
+ #displayName;
17931
+ #requestedGrants;
17787
17932
  #now;
17788
17933
  #mintSecret;
17789
17934
  #writeTokenFile;
17790
17935
  #ancestorOptions;
17791
17936
  constructor(options) {
17937
+ if (options.displayName !== void 0 && !validEnrollmentDisplayName(options.displayName))
17938
+ throw new ClaustrumConsumerError("invalid-state", "invalid Claustrum enrollment display name");
17939
+ if (options.requestedGrants !== void 0 && !validEnrollmentRequestedGrants(options.requestedGrants))
17940
+ throw new ClaustrumConsumerError("invalid-state", "invalid Claustrum enrollment requested grants");
17941
+ this.#requestedGrants = options.requestedGrants?.map((grant) => ({
17942
+ selector: { ...grant.selector },
17943
+ operation: grant.operation
17944
+ }));
17792
17945
  this.#ancestorOptions = options.ancestorOptions ?? {};
17793
17946
  this.#client = options.client;
17794
17947
  this.#paths = options.paths;
17795
17948
  this.#proposedName = options.proposedName;
17949
+ this.#displayName = options.displayName;
17796
17950
  this.#now = options.now ?? Date.now;
17797
17951
  this.#mintSecret = options.mintSecret ?? (() => randomBytes2(32).toString("hex"));
17798
17952
  this.#writeTokenFile = options.writeTokenFile ?? writeEnrollmentTokenFile;
@@ -17838,6 +17992,7 @@ var init_enrollment = __esm({
17838
17992
  phase: "approved",
17839
17993
  proposedName: state?.proposedName ?? this.#proposedName,
17840
17994
  tokenGeneration: token.token_generation,
17995
+ ...state && grantProposal(state),
17841
17996
  updatedAt: this.#now()
17842
17997
  };
17843
17998
  await writeStateAtomic(this.#paths.statePath, approved, this.#ancestorOptions);
@@ -17849,7 +18004,8 @@ var init_enrollment = __esm({
17849
18004
  ...state.phase === "approved" && state.approvedName !== void 0 && {
17850
18005
  approvedName: state.approvedName
17851
18006
  },
17852
- tokenGeneration: token.token_generation
18007
+ tokenGeneration: token.token_generation,
18008
+ ...state.phase === "approved" && grantProposal(state)
17853
18009
  };
17854
18010
  }
17855
18011
  if (state?.phase === "approved") {
@@ -17873,7 +18029,10 @@ var init_enrollment = __esm({
17873
18029
  proposedName: this.#proposedName,
17874
18030
  requestSecret: this.#mintSecret(),
17875
18031
  createdAt: now,
17876
- updatedAt: now
18032
+ updatedAt: now,
18033
+ ...this.#requestedGrants !== void 0 && {
18034
+ requestedGrants: this.#requestedGrants
18035
+ }
17877
18036
  };
17878
18037
  if (!TOKEN_RE.test(state.requestSecret))
17879
18038
  throw new ClaustrumConsumerError("invalid-state", "invalid minted Claustrum enrollment secret");
@@ -17882,14 +18041,38 @@ var init_enrollment = __esm({
17882
18041
  if (!state.requestId) {
17883
18042
  try {
17884
18043
  const requestSecretHash = createHash5("sha256").update(Buffer.from(state.requestSecret, "hex")).digest("hex");
17885
- const proposed = await this.#client.enrollPropose({
18044
+ const proposal = {
17886
18045
  name: state.proposedName,
17887
18046
  requestSecretHash
17888
- });
18047
+ };
18048
+ let proposed;
18049
+ let requestedGrantsStatus = state.requestedGrantsStatus;
18050
+ try {
18051
+ proposed = await this.#client.enrollPropose({
18052
+ ...proposal,
18053
+ ...this.#displayName !== void 0 && {
18054
+ displayName: this.#displayName
18055
+ },
18056
+ ...state.requestedGrants !== void 0 && {
18057
+ requestedGrants: state.requestedGrants
18058
+ }
18059
+ });
18060
+ if (state.requestedGrants !== void 0)
18061
+ requestedGrantsStatus = "sent";
18062
+ } catch (error) {
18063
+ if (this.#displayName === void 0 && state.requestedGrants === void 0 || !(error instanceof ClaustrumCredentialError3) || error.code !== "invalid_params")
18064
+ throw error;
18065
+ proposed = await this.#client.enrollPropose(proposal);
18066
+ if (state.requestedGrants !== void 0)
18067
+ requestedGrantsStatus = "dropped";
18068
+ }
17889
18069
  state = {
17890
18070
  ...state,
17891
18071
  requestId: proposed.requestId,
17892
- updatedAt: this.#now()
18072
+ updatedAt: this.#now(),
18073
+ ...requestedGrantsStatus !== void 0 && {
18074
+ requestedGrantsStatus
18075
+ }
17893
18076
  };
17894
18077
  await writeStateAtomic(this.#paths.statePath, state, this.#ancestorOptions);
17895
18078
  } catch (error) {
@@ -17900,7 +18083,8 @@ var init_enrollment = __esm({
17900
18083
  return {
17901
18084
  state: "pending",
17902
18085
  proposedName: state.proposedName,
17903
- retryCode: refusal3.code
18086
+ retryCode: refusal3.code,
18087
+ ...grantProposal(state)
17904
18088
  };
17905
18089
  }
17906
18090
  if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE) {
@@ -17950,6 +18134,7 @@ var init_enrollment = __esm({
17950
18134
  proposedName: state.proposedName,
17951
18135
  approvedName: outcome.name,
17952
18136
  tokenGeneration: outcome.tokenGeneration,
18137
+ ...grantProposal(state),
17953
18138
  updatedAt: this.#now()
17954
18139
  };
17955
18140
  await writeStateAtomic(this.#paths.statePath, approved, this.#ancestorOptions);
@@ -17963,7 +18148,8 @@ var init_enrollment = __esm({
17963
18148
  state: "pending",
17964
18149
  proposedName: state.proposedName,
17965
18150
  requestId,
17966
- retryCode: refusal3.code
18151
+ retryCode: refusal3.code,
18152
+ ...grantProposal(state)
17967
18153
  };
17968
18154
  }
17969
18155
  return this.#block(state, refusal3.code);
@@ -18052,10 +18238,10 @@ async function drainShutdown(pending, onTimeout) {
18052
18238
  try {
18053
18239
  await Promise.race([
18054
18240
  drained,
18055
- new Promise((resolve22) => {
18241
+ new Promise((resolve24) => {
18056
18242
  timer = setTimeout(() => {
18057
18243
  expired = true;
18058
- resolve22();
18244
+ resolve24();
18059
18245
  }, 2e3);
18060
18246
  })
18061
18247
  ]);
@@ -18399,8 +18585,15 @@ var init_custody = __esm({
18399
18585
  this.#warnShutdown = shutdownWarning(this.#logger);
18400
18586
  this.#setTimeout = options.setTimeoutImpl ?? setTimeout;
18401
18587
  this.#clearTimeout = options.clearTimeoutImpl ?? clearTimeout;
18588
+ const currentClient = () => this.#client;
18402
18589
  this.#usage = new ScopedUsageReporter({
18403
- client: this.#client,
18590
+ client: {
18591
+ // Queued readings follow a replacement without losing client capability checks.
18592
+ get reportUsageScoped() {
18593
+ const client = currentClient();
18594
+ return client.reportUsageScoped?.bind(client);
18595
+ }
18596
+ },
18404
18597
  owns: (id) => this.#usageServed.has(id),
18405
18598
  token: async () => hasVaultHost() ? "" : checkedEnrollmentToken(await this.#readToken()),
18406
18599
  logger: this.#logger,
@@ -18408,12 +18601,30 @@ var init_custody = __esm({
18408
18601
  clearTimeout: this.#clearTimeout
18409
18602
  });
18410
18603
  }
18604
+ /**
18605
+ * Replace the connection to the same vault without discarding receipts or
18606
+ * their enrollment tokens. Open roster watches restart on the new client;
18607
+ * their existing handles remain usable. Passing the current client does nothing.
18608
+ * Neither client is closed here: the caller closes the old one, and custody's
18609
+ * close()/dispose() still closes the client it holds at shutdown.
18610
+ * While hosted, next must come from connectVaultHost, as in the constructor.
18611
+ */
18612
+ replaceClient(next) {
18613
+ this.#check();
18614
+ if (next === this.#client)
18615
+ return;
18616
+ if (hasVaultHost() && !isVaultHostClient(next))
18617
+ throw new ClaustrumUnreachableError();
18618
+ this.#client = next;
18619
+ for (const watch of this.#watches)
18620
+ watch.restart();
18621
+ }
18411
18622
  /** A watch losing its transport is the same outage as an unreachable read. */
18412
18623
  transportLost(error) {
18413
18624
  if (this.#closed || this.#outage)
18414
18625
  return;
18415
18626
  this.#outage = true;
18416
- this.#outageError = error instanceof ClaustrumCredentialError5 ? error : new ClaustrumUnreachableError();
18627
+ this.#outageError = error instanceof ClaustrumCredentialError5 ? error : new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError ? error.reason : void 0);
18417
18628
  this.#logger.warn("serving kept vault receipt", { reason: "unreachable" });
18418
18629
  this.#scheduleProbe();
18419
18630
  }
@@ -18511,7 +18722,7 @@ var init_custody = __esm({
18511
18722
  if (error instanceof ClaustrumCredentialError5)
18512
18723
  throw error;
18513
18724
  if (classifyVaultFailure(error) === "unreachable")
18514
- throw new ClaustrumUnreachableError();
18725
+ throw new ClaustrumUnreachableError(error instanceof ClaustrumUnreachableError ? error.reason : void 0);
18515
18726
  throw new ClaustrumConsumerError("unavailable", "Claustrum scoped operation unavailable");
18516
18727
  } finally {
18517
18728
  removeAbortListener?.();
@@ -18727,7 +18938,7 @@ var init_custody = __esm({
18727
18938
  if (kept.since === null)
18728
18939
  kept.since = this.#now();
18729
18940
  const attempt = Object.freeze(Object.defineProperty({ ...kept.attempt, fromKeptReceipt: true }, "accessToken", { value: kept.attempt.accessToken, enumerable: false }));
18730
- this.#provenance.set(attempt, this.#provenance.get(kept.attempt) ?? { token, client: this.#client });
18941
+ this.#provenance.set(attempt, this.#provenance.get(kept.attempt) ?? { token });
18731
18942
  this.#keptAttempts.set(attempt, routeId);
18732
18943
  return attempt;
18733
18944
  }
@@ -18788,15 +18999,15 @@ var init_custody = __esm({
18788
18999
  recordVersion: served.recordVersion,
18789
19000
  expiresAtMs
18790
19001
  }, "accessToken", { value: accessToken, enumerable: false }));
18791
- this.#provenance.set(attempt, { token, client: this.#client });
19002
+ this.#provenance.set(attempt, { token });
18792
19003
  return attempt;
18793
19004
  }
18794
19005
  /**
18795
19006
  * Report that a send this consumer actually made was rejected. Only a 401
18796
19007
  * is reported (the vault refuses 429, 402 and 5xx reports), addressed by
18797
19008
  * credential id with the exact record version that send was served, and
18798
- * sent through the client and enrollment token that authorized it. A receipt
18799
- * this custody did not issue is refused rather than reported.
19009
+ * sent through the current client with the enrollment token that authorized
19010
+ * it. A receipt this custody did not issue is refused rather than reported.
18800
19011
  */
18801
19012
  async reportFailure(attempt, status, reporterSource) {
18802
19013
  if (status !== 401)
@@ -18820,7 +19031,7 @@ var init_custody = __esm({
18820
19031
  const pending = this.#reports.get(attempt);
18821
19032
  if (pending)
18822
19033
  return pending;
18823
- const report = this.#call(() => provenance.client.reportAuthFailureScoped({
19034
+ const report = this.#call(() => this.#client.reportAuthFailureScoped({
18824
19035
  credentialId: attempt.credentialId,
18825
19036
  enrollmentToken: provenance.token,
18826
19037
  providerStatus: 401,
@@ -18861,34 +19072,64 @@ var init_custody = __esm({
18861
19072
  */
18862
19073
  watchRoster(options) {
18863
19074
  this.#check();
18864
- const watch = new ScopedRosterWatch({
18865
- client: this.#client,
18866
- enrollmentToken: () => this.#token(),
18867
- view: options.view ?? (() => this.#discoveredView),
18868
- discover: async (view) => {
18869
- await options.onView(view);
18870
- },
18871
- onRefused: (error) => {
18872
- this.listFailed(error);
18873
- options.onRefused?.(error);
19075
+ const currentView = options.view ?? (() => this.#discoveredView);
19076
+ let discovering;
19077
+ let watch;
19078
+ const create = (resubscribed = false) => {
19079
+ const opened = new ScopedRosterWatch({
19080
+ client: this.#client,
19081
+ enrollmentToken: () => this.#token(),
19082
+ // Nothing observed the gap between clients, even if the view is unchanged.
19083
+ view: () => resubscribed ? void 0 : currentView(),
19084
+ discover: async (view) => {
19085
+ while (discovering)
19086
+ await discovering.catch(() => {
19087
+ });
19088
+ if (watch !== opened)
19089
+ return;
19090
+ resubscribed = false;
19091
+ discovering = Promise.resolve().then(() => options.onView(view));
19092
+ try {
19093
+ await discovering;
19094
+ } finally {
19095
+ discovering = void 0;
19096
+ }
19097
+ },
19098
+ onRefused: (error) => {
19099
+ this.listFailed(error);
19100
+ options.onRefused?.(error);
19101
+ },
19102
+ onTransportLost: () => this.transportLost(),
19103
+ onReachable: () => this.reachable(),
19104
+ onError: options.onError,
19105
+ onMode: options.onMode,
19106
+ logger: this.#logger,
19107
+ now: this.#now,
19108
+ setTimeoutImpl: this.#setTimeout,
19109
+ clearTimeoutImpl: this.#clearTimeout
19110
+ });
19111
+ return opened;
19112
+ };
19113
+ watch = create();
19114
+ const tracked = {
19115
+ restart: () => {
19116
+ const previousMode = watch.mode;
19117
+ watch.stop();
19118
+ watch = create(true);
19119
+ if (previousMode !== watch.mode)
19120
+ options.onMode?.(watch.mode);
19121
+ watch.start();
18874
19122
  },
18875
- onTransportLost: () => this.transportLost(),
18876
- onReachable: () => this.reachable(),
18877
- onError: options.onError,
18878
- onMode: options.onMode,
18879
- logger: this.#logger,
18880
- now: this.#now,
18881
- setTimeoutImpl: this.#setTimeout,
18882
- clearTimeoutImpl: this.#clearTimeout
18883
- });
18884
- this.#watches.add(watch);
19123
+ stop: () => watch.stop()
19124
+ };
19125
+ this.#watches.add(tracked);
18885
19126
  watch.start();
18886
19127
  return {
18887
19128
  get mode() {
18888
19129
  return watch.mode;
18889
19130
  },
18890
19131
  close: () => {
18891
- this.#watches.delete(watch);
19132
+ this.#watches.delete(tracked);
18892
19133
  watch.stop();
18893
19134
  }
18894
19135
  };
@@ -19028,7 +19269,7 @@ var init_interlock = __esm({
19028
19269
  // ../core/dist/common-auth-embedded/claustrum/roster.js
19029
19270
  import { createHash as createHash6 } from "node:crypto";
19030
19271
  import { stat as stat6 } from "node:fs/promises";
19031
- import { resolve as resolve8 } from "node:path";
19272
+ import { resolve as resolve9 } from "node:path";
19032
19273
  function vaultRosterSeed(roster) {
19033
19274
  return {
19034
19275
  declined: roster.declined.map((entry) => ({ ...entry })),
@@ -19430,16 +19671,16 @@ function applyVaultQuota(current, input) {
19430
19671
  };
19431
19672
  }
19432
19673
  function forgetPendingVaultDiscovery(path2) {
19433
- pendingDiscoveries.delete(resolve8(path2));
19674
+ pendingDiscoveries.delete(resolve9(path2));
19434
19675
  }
19435
19676
  function isVaultRosterLockRefusal(path2, error) {
19436
- const target = resolve8(path2);
19677
+ const target = resolve9(path2);
19437
19678
  if (error instanceof ClaustrumConsumerError)
19438
19679
  return error.kind === "roster-busy";
19439
19680
  if (error instanceof LockContentionError || error instanceof LockOwnershipError)
19440
- return resolve8(error.details.target) === target;
19681
+ return resolve9(error.details.target) === target;
19441
19682
  if (error instanceof PrivateFileError) {
19442
- const failed = resolve8(error.path);
19683
+ const failed = resolve9(error.path);
19443
19684
  return [WRITE_LOCK.name, DISCOVERY_LEASE.name].some((name) => {
19444
19685
  const lock = lockPathFor(target, name);
19445
19686
  return failed === lock || failed.startsWith(`${lock}.`);
@@ -19500,7 +19741,7 @@ async function refreshVaultRoster(options) {
19500
19741
  throw new ClaustrumConsumerError("roster-busy", "Claustrum account discovery is already in progress");
19501
19742
  return persisted;
19502
19743
  }
19503
- const key = resolve8(options.path);
19744
+ const key = resolve9(options.path);
19504
19745
  const listedOver = options.listedOver;
19505
19746
  let discovered;
19506
19747
  try {
@@ -19624,9 +19865,9 @@ var init_roster = __esm({
19624
19865
  });
19625
19866
 
19626
19867
  // ../core/dist/common-auth-embedded/claustrum/quota-writer.js
19627
- import { resolve as resolve9 } from "node:path";
19868
+ import { resolve as resolve10 } from "node:path";
19628
19869
  function writerFor(path2, clock = quotaCommitTimer) {
19629
- const key = resolve9(path2);
19870
+ const key = resolve10(path2);
19630
19871
  let writer = writers.get(key);
19631
19872
  if (!writer) {
19632
19873
  writer = {
@@ -19690,7 +19931,7 @@ function orderedFields(pending) {
19690
19931
  return [...pending.values()].flatMap((account) => [...account.values()]).sort((a, b) => a.order - b.order);
19691
19932
  }
19692
19933
  function pendingVaultQuota(path2, roster) {
19693
- const writer = writers.get(resolve9(path2));
19934
+ const writer = writers.get(resolve10(path2));
19694
19935
  if (writer) {
19695
19936
  for (const field of orderedFields(writer.pending)) {
19696
19937
  if (field.priorReading)
@@ -19701,7 +19942,7 @@ function pendingVaultQuota(path2, roster) {
19701
19942
  return roster;
19702
19943
  }
19703
19944
  function hasPendingVaultQuota(path2) {
19704
- return !!writers.get(resolve9(path2))?.pending.size;
19945
+ return !!writers.get(resolve10(path2))?.pending.size;
19705
19946
  }
19706
19947
  function schedule(writer, delay3) {
19707
19948
  if (writer.running || writer.timer || !writer.pending.size || writer.abort.signal.aborted)
@@ -19766,7 +20007,7 @@ function flush(writer) {
19766
20007
  return writer.running;
19767
20008
  }
19768
20009
  async function drainVaultQuota(path2, timeoutMs = 1e3) {
19769
- const key = resolve9(path2);
20010
+ const key = resolve10(path2);
19770
20011
  const writer = writers.get(key);
19771
20012
  if (!writer)
19772
20013
  return;
@@ -19914,7 +20155,7 @@ var init_consumer = __esm({
19914
20155
  this.#shutdown.signal,
19915
20156
  ...signal ? [signal] : []
19916
20157
  ]);
19917
- return new Promise((resolve22, reject) => {
20158
+ return new Promise((resolve24, reject) => {
19918
20159
  const cleanup2 = () => {
19919
20160
  combined.signal.removeEventListener("abort", abort);
19920
20161
  combined.dispose();
@@ -19929,7 +20170,7 @@ var init_consumer = __esm({
19929
20170
  if (combined.signal.aborted)
19930
20171
  reject(combined.signal.reason);
19931
20172
  else
19932
- resolve22(value);
20173
+ resolve24(value);
19933
20174
  }, (error) => {
19934
20175
  cleanup2();
19935
20176
  reject(error);
@@ -20674,7 +20915,7 @@ var init_consumer = __esm({
20674
20915
  import { createHash as createHash7 } from "node:crypto";
20675
20916
  import { channel as channel2 } from "node:diagnostics_channel";
20676
20917
  import { readdir, stat as stat7 } from "node:fs/promises";
20677
- import { dirname as dirname10, join as join8, resolve as resolve10 } from "node:path";
20918
+ import { dirname as dirname10, join as join8, resolve as resolve11 } from "node:path";
20678
20919
  function canonicalJson3(value, path2 = /* @__PURE__ */ new Set()) {
20679
20920
  if (value === null)
20680
20921
  return "null";
@@ -20735,12 +20976,12 @@ function unreachableConnect2() {
20735
20976
  return new ClaustrumUnreachableError();
20736
20977
  }
20737
20978
  function untilAborted(pending, signal) {
20738
- return new Promise((resolve22, reject) => {
20979
+ return new Promise((resolve24, reject) => {
20739
20980
  const abort = () => reject(signal.reason);
20740
20981
  signal.addEventListener("abort", abort, { once: true });
20741
20982
  pending.then((value) => {
20742
20983
  signal.removeEventListener("abort", abort);
20743
- resolve22(value);
20984
+ resolve24(value);
20744
20985
  }, (error) => {
20745
20986
  signal.removeEventListener("abort", abort);
20746
20987
  reject(error);
@@ -20898,7 +21139,7 @@ var init_hub = __esm({
20898
21139
  };
20899
21140
  const { consumer, hooks } = createHubMember(port, consumerOptions);
20900
21141
  entry.hooks = hooks;
20901
- const path2 = resolve10(entry.path);
21142
+ const path2 = resolve11(entry.path);
20902
21143
  const subscribers = sharedRosters.get(path2) ?? /* @__PURE__ */ new Set();
20903
21144
  const install = (roster) => {
20904
21145
  if (entry.closed || this.#active !== true || !this.#current || !this.#live(this.#current) || !hooks.roster() || this.#collides(hooks, roster))
@@ -20929,7 +21170,7 @@ var init_hub = __esm({
20929
21170
  return;
20930
21171
  entry.seen = JSON.stringify(decodedVaultRoster(roster));
20931
21172
  entry.hooks?.install(roster);
20932
- for (const install of sharedRosters.get(resolve10(entry.path)) ?? []) {
21173
+ for (const install of sharedRosters.get(resolve11(entry.path)) ?? []) {
20933
21174
  if (!this.#live(generation))
20934
21175
  return;
20935
21176
  if (install !== entry.receiveRoster)
@@ -21732,6 +21973,8 @@ __export(claustrum_exports, {
21732
21973
  reorderVaultRoster: () => reorderVaultRoster,
21733
21974
  resetClaustrumEnrollmentState: () => resetClaustrumEnrollmentState,
21734
21975
  resolveVaultPrimary: () => resolveVaultPrimary,
21976
+ validEnrollmentDisplayName: () => validEnrollmentDisplayName,
21977
+ validEnrollmentRequestedGrants: () => validEnrollmentRequestedGrants,
21735
21978
  vaultAuthority: () => vaultAuthority,
21736
21979
  vaultRosterSeed: () => vaultRosterSeed,
21737
21980
  vaultRoutingRows: () => vaultRoutingRows
@@ -21988,7 +22231,7 @@ var init_lock = __esm({
21988
22231
  import { createHash as createHash8 } from "node:crypto";
21989
22232
  import { constants as constants2 } from "node:fs";
21990
22233
  import { lstat as lstat5, mkdir as mkdir10, open as open7, unlink as unlink7 } from "node:fs/promises";
21991
- import { dirname as dirname11, resolve as resolve11 } from "node:path";
22234
+ import { dirname as dirname11, resolve as resolve12 } from "node:path";
21992
22235
  import { setTimeout as sleep2 } from "node:timers/promises";
21993
22236
  function rootSpans(text2) {
21994
22237
  let i = text2.indexOf("{") + 1;
@@ -22189,8 +22432,8 @@ function createPiSlot(options, onStep, hooks) {
22189
22432
  if (!provider2 || !options.authPath || !options.stashPath || !placeholderKey || placeholderKey.startsWith("!") || placeholderKey.includes("$") || !Number.isFinite(timeout) || timeout < 0) {
22190
22433
  throw new PiSlotError("invalid-options");
22191
22434
  }
22192
- const authPath = resolve11(options.authPath);
22193
- const stashPath = resolve11(options.stashPath);
22435
+ const authPath = resolve12(options.authPath);
22436
+ const stashPath = resolve12(options.stashPath);
22194
22437
  if (authPath === stashPath || stashPath === `${authPath}.lock`) {
22195
22438
  throw new PiSlotError("invalid-options");
22196
22439
  }
@@ -22458,8 +22701,8 @@ function getDefaultTierId(allowedTiers) {
22458
22701
  return allowedTiers[0]?.id;
22459
22702
  }
22460
22703
  function wait(ms) {
22461
- return new Promise((resolve22) => {
22462
- setTimeout(resolve22, ms);
22704
+ return new Promise((resolve24) => {
22705
+ setTimeout(resolve24, ms);
22463
22706
  });
22464
22707
  }
22465
22708
  function extractManagedProjectId(payload) {
@@ -23481,7 +23724,7 @@ var init_capture_sink2 = __esm({
23481
23724
  import { randomUUID as randomUUID11 } from "node:crypto";
23482
23725
  import { lstat as lstat6, readFile as readFile7, rename as rename8, unlink as unlink8 } from "node:fs/promises";
23483
23726
  import { tmpdir as tmpdir2 } from "node:os";
23484
- import { dirname as dirname13, join as join10, resolve as resolve12 } from "node:path";
23727
+ import { dirname as dirname13, join as join10, resolve as resolve13 } from "node:path";
23485
23728
  function ioCode2(detail) {
23486
23729
  if (detail?.reason === "io-error") {
23487
23730
  if (detail.win32Code === 2 || detail.win32Code === 3)
@@ -23531,7 +23774,7 @@ async function privateOperation2(path2, stage, operation) {
23531
23774
  }
23532
23775
  }
23533
23776
  async function verifySafeDirectory2(path2, options) {
23534
- path2 = resolve12(path2);
23777
+ path2 = resolve13(path2);
23535
23778
  options ??= safeParentOptionsForTest2;
23536
23779
  await privateOperation2(path2, "safe-parent", async () => {
23537
23780
  const result = await (await loadBackend2()).verifySafeParent(path2, options);
@@ -23546,7 +23789,7 @@ async function verifySafeDirectory2(path2, options) {
23546
23789
  });
23547
23790
  }
23548
23791
  async function verifyPrivate2(path2, kind, migrate = false) {
23549
- path2 = resolve12(path2);
23792
+ path2 = resolve13(path2);
23550
23793
  if (kind === "directory")
23551
23794
  return verifySafeDirectory2(path2);
23552
23795
  await privateOperation2(path2, "verify", async () => {
@@ -23581,7 +23824,7 @@ async function verifyPrivate2(path2, kind, migrate = false) {
23581
23824
  });
23582
23825
  }
23583
23826
  async function ensurePrivateDirectory2(path2, _migrate = false, options) {
23584
- path2 = resolve12(path2);
23827
+ path2 = resolve13(path2);
23585
23828
  await privateOperation2(path2, "directory", async () => {
23586
23829
  const api = await loadBackend2();
23587
23830
  try {
@@ -23612,7 +23855,7 @@ async function readPrivateText2(path2, migrate = false) {
23612
23855
  async function readPrivateBuffer2(path2, migrate = false) {
23613
23856
  if (!windowsPrivateFiles2)
23614
23857
  return readFile7(path2);
23615
- path2 = resolve12(path2);
23858
+ path2 = resolve13(path2);
23616
23859
  if (migrate) {
23617
23860
  await verifySafeDirectory2(dirname13(path2));
23618
23861
  await verifyPrivate2(path2, "file", true);
@@ -23620,20 +23863,20 @@ async function readPrivateBuffer2(path2, migrate = false) {
23620
23863
  return privateOperation2(path2, "read", async () => (await loadBackend2()).readOwnerOnly(path2));
23621
23864
  }
23622
23865
  async function createPrivateBytes2(path2, bytes) {
23623
- await verifySafeDirectory2(dirname13(resolve12(path2)));
23866
+ await verifySafeDirectory2(dirname13(resolve13(path2)));
23624
23867
  await privateOperation2(path2, "create", async () => {
23625
- await (await loadBackend2()).createPrivateFile(resolve12(path2), bytes);
23868
+ await (await loadBackend2()).createPrivateFile(resolve13(path2), bytes);
23626
23869
  });
23627
23870
  }
23628
23871
  async function createPrivateDirectoryExclusive2(path2) {
23629
- await verifySafeDirectory2(dirname13(resolve12(path2)));
23872
+ await verifySafeDirectory2(dirname13(resolve13(path2)));
23630
23873
  await privateOperation2(path2, "directory-create", async () => {
23631
- await (await loadBackend2()).createOwnerOnly(resolve12(path2), { kind: "dir" });
23874
+ await (await loadBackend2()).createOwnerOnly(resolve13(path2), { kind: "dir" });
23632
23875
  });
23633
23876
  }
23634
23877
  async function replaceWindowsFile2(from, to, options = {}) {
23635
- from = resolve12(from);
23636
- to = resolve12(to);
23878
+ from = resolve13(from);
23879
+ to = resolve13(to);
23637
23880
  const now = options.now ?? (() => performance.now());
23638
23881
  const start = now();
23639
23882
  const leaseDeadline = options.deadline ?? Infinity;
@@ -23676,7 +23919,7 @@ async function replaceWindowsFile2(from, to, options = {}) {
23676
23919
  throw error;
23677
23920
  }
23678
23921
  async function writePrivateAtomic2(path2, bytes, options = {}) {
23679
- path2 = resolve12(path2);
23922
+ path2 = resolve13(path2);
23680
23923
  await ensurePrivateDirectory2(dirname13(path2));
23681
23924
  try {
23682
23925
  await verifyPrivate2(path2, "file", true);
@@ -23684,7 +23927,7 @@ async function writePrivateAtomic2(path2, bytes, options = {}) {
23684
23927
  if (error.code !== "ENOENT")
23685
23928
  throw error;
23686
23929
  }
23687
- const stage = resolve12(options.stagePath ?? `${path2}.${randomUUID11()}.tmp`);
23930
+ const stage = resolve13(options.stagePath ?? `${path2}.${randomUUID11()}.tmp`);
23688
23931
  if (dirname13(stage) !== dirname13(path2))
23689
23932
  throw new PrivateFileError2(path2, "stage-directory", { code: "EXDEV" });
23690
23933
  let created = false;
@@ -23850,7 +24093,7 @@ var init_redact2 = __esm({
23850
24093
  // src/common-auth-embedded/logger/engine.js
23851
24094
  import { appendFileSync as appendFileSync2, chmodSync as chmodSync2, existsSync as existsSync2, renameSync as renameSync2, statSync as statSync3 } from "node:fs";
23852
24095
  import { open as open8 } from "node:fs/promises";
23853
- import { dirname as dirname14, resolve as resolve13 } from "node:path";
24096
+ import { dirname as dirname14, resolve as resolve14 } from "node:path";
23854
24097
  function chmodPrivate2(path2) {
23855
24098
  try {
23856
24099
  chmodSync2(path2, 384);
@@ -23901,7 +24144,7 @@ async function openWindowsFile2(sink, file) {
23901
24144
  return sink.handle;
23902
24145
  }
23903
24146
  async function flushWindowsFile2(sink, file, text2) {
23904
- file = resolve13(file);
24147
+ file = resolve14(file);
23905
24148
  try {
23906
24149
  if (sink.file !== file)
23907
24150
  await closeWindowsFile2(sink);
@@ -24222,7 +24465,7 @@ import { randomUUID as randomUUID12 } from "node:crypto";
24222
24465
  import { realpathSync, rmSync } from "node:fs";
24223
24466
  import { chmod as chmod3, mkdir as mkdir11, readFile as readFile8, rename as rename9, rm as rm5, writeFile as writeFile3 } from "node:fs/promises";
24224
24467
  import { homedir as homedir2 } from "node:os";
24225
- import { join as join11, resolve as resolve14 } from "node:path";
24468
+ import { join as join11, resolve as resolve15 } from "node:path";
24226
24469
  function processHeartbeatDir() {
24227
24470
  const base = process.env.XDG_STATE_HOME || join11(homedir2(), ".local", "state");
24228
24471
  return join11(base, "cortexkit", "antigravity-auth", "processes");
@@ -24235,7 +24478,7 @@ function processConfigFolderKey() {
24235
24478
  try {
24236
24479
  return realpathSync.native(folder);
24237
24480
  } catch {
24238
- return resolve14(folder);
24481
+ return resolve15(folder);
24239
24482
  }
24240
24483
  }
24241
24484
  function processHasOlderGeneration() {
@@ -24819,7 +25062,7 @@ import {
24819
25062
  stat as stat10,
24820
25063
  unlink as unlink10
24821
25064
  } from "node:fs/promises";
24822
- import { basename as basename4, dirname as dirname15, join as join13, resolve as resolve15 } from "node:path";
25065
+ import { basename as basename4, dirname as dirname15, join as join13, resolve as resolve16 } from "node:path";
24823
25066
  function refusalMessage(stateDir, errorClass2) {
24824
25067
  if (errorClass2 === "ERR_PRIVATE_FILES_SECURITY")
24825
25068
  return `antigravity-auth cannot start: ${stateDir} is not a folder only your user can access, or it is a link, so the plugin will not use it (${errorClass2}). Replace it with a plain folder of your own, then restart OpenCode.`;
@@ -25679,7 +25922,7 @@ async function removeMovedVaultStateLeftover(vaultDir, accountFile) {
25679
25922
  if (process.env.OPENCODE_ANTIGRAVITY_AUTH_VAULT_DIR) return;
25680
25923
  const location = runtimeLayoutLocation();
25681
25924
  const files = layoutFiles(location, accountFile);
25682
- if (resolve15(vaultDir) !== resolve15(files.vault.next)) return;
25925
+ if (resolve16(vaultDir) !== resolve16(files.vault.next)) return;
25683
25926
  const stateDir = location.stateHomeDir;
25684
25927
  const marker = await readMarker(
25685
25928
  join13(stateDir, RUNTIME_LAYOUT_MARKER_FILE),
@@ -26108,7 +26351,7 @@ import {
26108
26351
  writeFileSync
26109
26352
  } from "node:fs";
26110
26353
  import { homedir as homedir4 } from "node:os";
26111
- import { dirname as dirname16, join as join14, resolve as resolve16 } from "node:path";
26354
+ import { dirname as dirname16, join as join14, resolve as resolve17 } from "node:path";
26112
26355
  async function ensureGitignore(configDir) {
26113
26356
  const gitignorePath = join14(configDir, ".gitignore");
26114
26357
  try {
@@ -26208,8 +26451,8 @@ function migrateLegacyWindowsConfig() {
26208
26451
  }
26209
26452
  }
26210
26453
  function resolveWindowsAccountAnchor(newPath, legacyPath) {
26211
- const standard = resolve16(newPath);
26212
- const legacy = resolve16(legacyPath);
26454
+ const standard = resolve17(newPath);
26455
+ const legacy = resolve17(legacyPath);
26213
26456
  if (standard.toLowerCase() === legacy.toLowerCase()) return newPath;
26214
26457
  const standardPointer = existsSync3(accountStorePointerPath(standard));
26215
26458
  const legacyPointer = existsSync3(accountStorePointerPath(legacy));
@@ -26231,7 +26474,7 @@ function getStoragePathWithMigration() {
26231
26474
  "antigravity-accounts.json"
26232
26475
  );
26233
26476
  const anchored = resolveWindowsAccountAnchor(newPath, legacyPath);
26234
- if (resolve16(anchored).toLowerCase() !== resolve16(newPath).toLowerCase() && !existsSync3(accountStorePointerPath(resolve16(anchored)))) {
26477
+ if (resolve17(anchored).toLowerCase() !== resolve17(newPath).toLowerCase() && !existsSync3(accountStorePointerPath(resolve17(anchored)))) {
26235
26478
  log6.info("Using legacy Windows config path (migration failed)", {
26236
26479
  legacyPath,
26237
26480
  newPath
@@ -26248,7 +26491,7 @@ function accountFileForVault(configDir = getConfigDir()) {
26248
26491
  const configured = join14(configDir, "antigravity-accounts.json");
26249
26492
  if (process.platform !== "win32") return configured;
26250
26493
  const legacyDir = getLegacyWindowsConfigDir();
26251
- if (resolve16(configDir).toLowerCase() === resolve16(legacyDir).toLowerCase())
26494
+ if (resolve17(configDir).toLowerCase() === resolve17(legacyDir).toLowerCase())
26252
26495
  return configured;
26253
26496
  const configuredVault = join14(configDir, "antigravity-auth-vault");
26254
26497
  const legacyVault = join14(legacyDir, "antigravity-auth-vault");
@@ -26279,7 +26522,7 @@ function getStoragePath() {
26279
26522
  }
26280
26523
  async function assertLegacyPoolInUse(legacyPath) {
26281
26524
  try {
26282
- await assertLegacyAccountStorageWritable(resolve16(legacyPath));
26525
+ await assertLegacyAccountStorageWritable(resolve17(legacyPath));
26283
26526
  } catch (error) {
26284
26527
  throw new LegacyAccountPoolRetiredError(legacyPath, { cause: error });
26285
26528
  }
@@ -26299,7 +26542,7 @@ function refusalMessage2(admission) {
26299
26542
  async function bindingOf(options) {
26300
26543
  if (options.legacyPath === void 0) await prepareLocalAccountStore();
26301
26544
  const now = options.now ?? (() => Date.now());
26302
- const legacyPath = resolve16(options.legacyPath ?? getStoragePath());
26545
+ const legacyPath = resolve17(options.legacyPath ?? getStoragePath());
26303
26546
  return {
26304
26547
  legacyPath,
26305
26548
  now,
@@ -26368,7 +26611,7 @@ async function openAccountStore(options) {
26368
26611
  async function initializeFreshAccountStoreFor(modules, options = {}) {
26369
26612
  if (options.legacyPath === void 0) await prepareLocalAccountStore();
26370
26613
  return initializeFreshAccountStore(modules, {
26371
- legacyPath: resolve16(options.legacyPath ?? getStoragePath()),
26614
+ legacyPath: resolve17(options.legacyPath ?? getStoragePath()),
26372
26615
  now: options.now ?? (() => Date.now())
26373
26616
  });
26374
26617
  }
@@ -26414,12 +26657,12 @@ var init_storage = __esm({
26414
26657
  import { createHash as createHash11 } from "node:crypto";
26415
26658
  import { existsSync as existsSync4, promises as fs2, readFileSync as readFileSync2, realpathSync as realpathSync2 } from "node:fs";
26416
26659
  import { homedir as homedir5 } from "node:os";
26417
- import { dirname as dirname17, join as join15, resolve as resolve17 } from "node:path";
26660
+ import { dirname as dirname17, join as join15, resolve as resolve18 } from "node:path";
26418
26661
  function configDirIdentity(path2) {
26419
26662
  try {
26420
26663
  return realpathSync2.native(path2);
26421
26664
  } catch {
26422
- return resolve17(path2);
26665
+ return resolve18(path2);
26423
26666
  }
26424
26667
  }
26425
26668
  function decisionKey(location) {
@@ -27081,13 +27324,13 @@ function closeDebugLog() {
27081
27324
  if (!state || !current) return Promise.resolve();
27082
27325
  state.logStream = null;
27083
27326
  if (state.logFilePath) liveLogFilePaths.delete(state.logFilePath);
27084
- return new Promise((resolve22) => {
27085
- current.once("close", () => resolve22());
27086
- current.once("error", () => resolve22());
27327
+ return new Promise((resolve24) => {
27328
+ current.once("close", () => resolve24());
27329
+ current.once("error", () => resolve24());
27087
27330
  try {
27088
27331
  current.end();
27089
27332
  } catch {
27090
- resolve22();
27333
+ resolve24();
27091
27334
  }
27092
27335
  });
27093
27336
  }
@@ -27122,8 +27365,8 @@ var init_debug = __esm({
27122
27365
  // src/plugin/logger.ts
27123
27366
  function createLocationLogger(options) {
27124
27367
  let configuredLevel = options.level ? LOG_LEVEL_FROM_OPERATOR[options.level] ?? "debug" : "debug";
27125
- const emit = (record3) => {
27126
- if (options.sink && options.sinkEnabled()) {
27368
+ const emit = (record3, alwaysHost = false) => {
27369
+ if (options.sink && (alwaysHost || options.sinkEnabled())) {
27127
27370
  try {
27128
27371
  const pending = options.sink(record3);
27129
27372
  if (isThenable(pending)) {
@@ -27142,26 +27385,33 @@ function createLocationLogger(options) {
27142
27385
  }
27143
27386
  }
27144
27387
  };
27145
- const engine = createLoggerInstance2({
27388
+ const createEngine3 = (alwaysHost) => createLoggerInstance2({
27146
27389
  level: () => configuredLevel,
27147
27390
  extraSecretKeys: isProviderSecretKey,
27148
27391
  extraValuePatterns: OAUTH_REDIRECT_VALUE_PATTERNS,
27149
27392
  captureSink: ({ channel: channel3, level, message, data }) => {
27150
27393
  const extra = data !== null && typeof data === "object" && !Array.isArray(data) ? Object.fromEntries(Object.entries(data)) : void 0;
27151
- emit({
27152
- service: channel3,
27153
- level: level === "trace" ? "debug" : level,
27154
- message,
27155
- extra
27156
- });
27394
+ emit(
27395
+ {
27396
+ service: channel3,
27397
+ level: level === "trace" ? "debug" : level,
27398
+ message,
27399
+ extra
27400
+ },
27401
+ alwaysHost
27402
+ );
27157
27403
  }
27158
27404
  });
27405
+ const engine = createEngine3(false);
27406
+ const hostEngine = createEngine3(true);
27159
27407
  return {
27160
27408
  createLogger(module) {
27161
27409
  const channel3 = engine.createLogger(`antigravity.${module}`);
27410
+ const hostChannel = hostEngine.createLogger(`antigravity.${module}`);
27162
27411
  return {
27163
27412
  debug: (message, extra) => channel3.debug(message, extra),
27164
27413
  info: (message, extra) => channel3.info(message, extra),
27414
+ hostInfo: (message, extra) => hostChannel.info(message, extra),
27165
27415
  warn: (message, extra) => channel3.warn(message, extra),
27166
27416
  error: (message, extra) => channel3.error(message, extra)
27167
27417
  };
@@ -27205,6 +27455,10 @@ function createLogger4(module) {
27205
27455
  return {
27206
27456
  debug: (message, extra) => log9("debug", message, extra),
27207
27457
  info: (message, extra) => log9("info", message, extra),
27458
+ hostInfo: (message, extra) => {
27459
+ channel3 ??= getLegacyLogger().createLogger(module);
27460
+ channel3.hostInfo?.(message, extra);
27461
+ },
27208
27462
  warn: (message, extra) => log9("warn", message, extra),
27209
27463
  error: (message, extra) => log9("error", message, extra)
27210
27464
  };
@@ -27234,7 +27488,7 @@ var init_logger4 = __esm({
27234
27488
  init_dist();
27235
27489
  import { execFile } from "node:child_process";
27236
27490
  import { realpathSync as realpathSync4 } from "node:fs";
27237
- import { resolve as resolve21 } from "node:path";
27491
+ import { resolve as resolve23 } from "node:path";
27238
27492
  import { createInterface } from "node:readline/promises";
27239
27493
  import { fileURLToPath as fileURLToPath2 } from "node:url";
27240
27494
  import { promisify } from "node:util";
@@ -27642,14 +27896,14 @@ async function fetchQuotaPayloads(options) {
27642
27896
  };
27643
27897
  }
27644
27898
  function untilQuotaAborted(pending, signal) {
27645
- return new Promise((resolve22, reject) => {
27899
+ return new Promise((resolve24, reject) => {
27646
27900
  const abort = () => reject(signal.reason);
27647
27901
  if (signal.aborted) abort();
27648
27902
  else signal.addEventListener("abort", abort, { once: true });
27649
27903
  void pending.then(
27650
27904
  (value) => {
27651
27905
  signal.removeEventListener("abort", abort);
27652
- resolve22(value);
27906
+ resolve24(value);
27653
27907
  },
27654
27908
  (error) => {
27655
27909
  signal.removeEventListener("abort", abort);
@@ -27931,12 +28185,12 @@ async function startOAuthListener({
27931
28185
  let resolveCallback;
27932
28186
  let rejectCallback;
27933
28187
  let timeoutHandle;
27934
- const callbackPromise = new Promise((resolve22, reject) => {
28188
+ const callbackPromise = new Promise((resolve24, reject) => {
27935
28189
  resolveCallback = (url) => {
27936
28190
  if (settled) return;
27937
28191
  settled = true;
27938
28192
  if (timeoutHandle) clearTimeout(timeoutHandle);
27939
- resolve22(url);
28193
+ resolve24(url);
27940
28194
  };
27941
28195
  rejectCallback = (error) => {
27942
28196
  if (settled) return;
@@ -28095,7 +28349,7 @@ async function startOAuthListener({
28095
28349
  });
28096
28350
  });
28097
28351
  const bindAddress = getBindAddress();
28098
- await new Promise((resolve22, reject) => {
28352
+ await new Promise((resolve24, reject) => {
28099
28353
  const handleError = (error) => {
28100
28354
  server.off("error", handleError);
28101
28355
  if (error.code === "EADDRINUSE") {
@@ -28111,7 +28365,7 @@ async function startOAuthListener({
28111
28365
  server.once("error", handleError);
28112
28366
  server.listen(port, bindAddress, () => {
28113
28367
  server.off("error", handleError);
28114
- resolve22();
28368
+ resolve24();
28115
28369
  });
28116
28370
  });
28117
28371
  server.on("error", (error) => {
@@ -28119,7 +28373,7 @@ async function startOAuthListener({
28119
28373
  });
28120
28374
  return {
28121
28375
  waitForCallback: () => callbackPromise,
28122
- close: () => new Promise((resolve22, reject) => {
28376
+ close: () => new Promise((resolve24, reject) => {
28123
28377
  server.close((error) => {
28124
28378
  if (error && error.code !== "ERR_SERVER_NOT_RUNNING") {
28125
28379
  reject(error);
@@ -28128,7 +28382,7 @@ async function startOAuthListener({
28128
28382
  if (!settled) {
28129
28383
  rejectCallback(new Error("OAuth listener closed before callback"));
28130
28384
  }
28131
- resolve22();
28385
+ resolve24();
28132
28386
  });
28133
28387
  })
28134
28388
  };
@@ -28147,7 +28401,7 @@ init_runtime_paths();
28147
28401
  // src/setup.ts
28148
28402
  init_dist();
28149
28403
  import { lstat as lstat9, readFile as readFile13 } from "node:fs/promises";
28150
- import { join as join22, resolve as resolve20 } from "node:path";
28404
+ import { join as join22, resolve as resolve22 } from "node:path";
28151
28405
 
28152
28406
  // src/auth-method-labels.ts
28153
28407
  var OPENCODE2_POOL_AUTH_LABEL = "Google (antigravity-auth pool, browser)";
@@ -28320,7 +28574,7 @@ async function select2(terminal, items, options) {
28320
28574
  writeLine("");
28321
28575
  renderedLines = lines;
28322
28576
  };
28323
- return new Promise((resolve22) => {
28577
+ return new Promise((resolve24) => {
28324
28578
  const wasRaw = stdin.isRaw ?? false;
28325
28579
  const cleanup2 = () => {
28326
28580
  if (cleaned)
@@ -28340,7 +28594,7 @@ async function select2(terminal, items, options) {
28340
28594
  };
28341
28595
  const finish = (value) => {
28342
28596
  cleanup2();
28343
- resolve22(value);
28597
+ resolve24(value);
28344
28598
  };
28345
28599
  const onSignal = () => finish(null);
28346
28600
  const onKey = (data) => {
@@ -28380,7 +28634,7 @@ async function select2(terminal, items, options) {
28380
28634
  stdin.setRawMode(true);
28381
28635
  } catch {
28382
28636
  cleanup2();
28383
- resolve22(null);
28637
+ resolve24(null);
28384
28638
  return;
28385
28639
  }
28386
28640
  stdin.resume();
@@ -28394,12 +28648,12 @@ async function select2(terminal, items, options) {
28394
28648
  import { createHash as createHash12, randomBytes as randomBytes3, randomUUID as randomUUID15 } from "node:crypto";
28395
28649
  import { constants as fsConstants2 } from "node:fs";
28396
28650
  import { chmod as chmod5, mkdir as mkdir14, open as open10, readFile as readFile12, realpath as realpath4, rename as rename12, stat as stat13, unlink as unlink11 } from "node:fs/promises";
28397
- import { basename as basename5, dirname as dirname19, extname as extname2, isAbsolute as isAbsolute4, join as join18, resolve as resolve19 } from "node:path";
28651
+ import { basename as basename5, dirname as dirname19, extname as extname2, isAbsolute as isAbsolute4, join as join18, resolve as resolve21 } from "node:path";
28398
28652
  import { ClaustrumCredentialError as ClaustrumCredentialError9, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
28399
28653
 
28400
28654
  // src/common-auth-embedded/fs/file-read-cache.js
28401
28655
  import { lstat as lstat7, stat as stat11 } from "node:fs/promises";
28402
- import { resolve as resolve18 } from "node:path";
28656
+ import { resolve as resolve19 } from "node:path";
28403
28657
  async function identity2(path2, followSymlinks) {
28404
28658
  try {
28405
28659
  const metadata = await (followSymlinks ? stat11(path2) : lstat7(path2));
@@ -28420,7 +28674,7 @@ var FileReadCache2 = class {
28420
28674
  this.#followSymlinks = options.followSymlinks ?? false;
28421
28675
  }
28422
28676
  async read(paths, read, validateHit) {
28423
- const resolvedPaths = paths.map((path2) => resolve18(path2));
28677
+ const resolvedPaths = paths.map((path2) => resolve19(path2));
28424
28678
  const key = JSON.stringify(resolvedPaths);
28425
28679
  const probed = await Promise.all(resolvedPaths.map((path2) => identity2(path2, this.#followSymlinks)));
28426
28680
  const identities = probed.every((entry) => entry !== void 0) ? probed : void 0;
@@ -28469,11 +28723,46 @@ var WRITER_LOCK_CONSTANTS2 = Object.freeze({
28469
28723
  init_private_files2();
28470
28724
 
28471
28725
  // src/common-auth-embedded/fs/refresh-file-lock.js
28472
- init_private_files2();
28473
28726
  import { randomUUID as randomUUID14 } from "node:crypto";
28474
28727
  import { link as link3, lstat as lstat8, mkdir as mkdir13, open as open9, readFile as readFile11, rename as rename11, rm as rm6, stat as stat12 } from "node:fs/promises";
28475
28728
  import { dirname as dirname18, join as join17 } from "node:path";
28476
28729
 
28730
+ // src/common-auth-embedded/fs/lock-record.js
28731
+ init_private_files2();
28732
+ import { resolve as resolve20 } from "node:path";
28733
+ var DisappearedLockRecordError2 = class extends Error {
28734
+ path;
28735
+ code = "ENOENT";
28736
+ constructor(path2, cause) {
28737
+ super(`Lock record disappeared: ${path2}`, { cause });
28738
+ this.path = path2;
28739
+ }
28740
+ };
28741
+ function isWindowsAccessDeniedRead2(error, paths) {
28742
+ return error instanceof PrivateFileError2 && error.reason === "io-error" && error.win32Code === 5 && (error.stage === "read" || error.stage === "verify") && paths.some((path2) => resolve20(path2) === error.path);
28743
+ }
28744
+ function isWindowsAccessDeniedCreate2(error, paths, stage) {
28745
+ return error instanceof PrivateFileError2 && error.reason === "io-error" && error.win32Code === 5 && error.stage === stage && paths.some((path2) => resolve20(path2) === error.path);
28746
+ }
28747
+ async function readLockRecord2(path2, read) {
28748
+ try {
28749
+ return await read();
28750
+ } catch (error) {
28751
+ if (!isWindowsAccessDeniedRead2(error, [path2]))
28752
+ throw error;
28753
+ try {
28754
+ return await read();
28755
+ } catch (recheckError) {
28756
+ if (recheckError.code === "ENOENT")
28757
+ throw new DisappearedLockRecordError2(path2, error);
28758
+ throw error;
28759
+ }
28760
+ }
28761
+ }
28762
+
28763
+ // src/common-auth-embedded/fs/refresh-file-lock.js
28764
+ init_private_files2();
28765
+
28477
28766
  // src/common-auth-embedded/fs/with-lock.js
28478
28767
  init_private_files2();
28479
28768
  function lockPathFor2(target, name) {
@@ -28572,8 +28861,8 @@ async function acquireRefreshFileLockWithClock2(options) {
28572
28861
  let releaseConfirmed = false;
28573
28862
  let loss;
28574
28863
  let resolveLoss;
28575
- const lostPromise = new Promise((resolve22) => {
28576
- resolveLoss = resolve22;
28864
+ const lostPromise = new Promise((resolve24) => {
28865
+ resolveLoss = resolve24;
28577
28866
  });
28578
28867
  function notifyTimerStep(event) {
28579
28868
  try {
@@ -28611,15 +28900,18 @@ async function acquireRefreshFileLockWithClock2(options) {
28611
28900
  const evictOwnerId = randomUUID14();
28612
28901
  const EVICT_TTL = 5e3;
28613
28902
  const MAX_STEAL_ATTEMPTS = 8;
28903
+ function isChangingLockCreate(error) {
28904
+ return windowsPrivateFiles2 && (isWindowsAccessDeniedCreate2(error, [lockPath], "create") || isWindowsAccessDeniedCreate2(error, [evictPath], "directory-create"));
28905
+ }
28614
28906
  async function readOwner() {
28615
28907
  if (windowsPrivateFiles2) {
28616
28908
  try {
28617
- return JSON.parse(await readPrivateText2(lockPath, true));
28909
+ return JSON.parse(await readLockRecord2(lockPath, () => readPrivateText2(lockPath, true)));
28618
28910
  } catch (error) {
28619
28911
  if (error.code !== "EISDIR" && error.reason !== "wrong-kind")
28620
28912
  throw error;
28621
- await verifyPrivate2(lockPath, "directory", true);
28622
- return JSON.parse(await readPrivateText2(legacyOwnerPath, true));
28913
+ await readLockRecord2(lockPath, () => verifyPrivate2(lockPath, "directory", true));
28914
+ return JSON.parse(await readLockRecord2(legacyOwnerPath, () => readPrivateText2(legacyOwnerPath, true)));
28623
28915
  }
28624
28916
  }
28625
28917
  try {
@@ -28695,8 +28987,8 @@ async function acquireRefreshFileLockWithClock2(options) {
28695
28987
  await options.onStep("lease-contention-read-ready");
28696
28988
  try {
28697
28989
  if (code2 === "EISDIR") {
28698
- await verifyPrivate2(lockPath, "directory", true);
28699
- await readPrivateText2(legacyOwnerPath, true);
28990
+ await readLockRecord2(lockPath, () => verifyPrivate2(lockPath, "directory", true));
28991
+ await readLockRecord2(legacyOwnerPath, () => readPrivateText2(legacyOwnerPath, true));
28700
28992
  } else
28701
28993
  await readOwner();
28702
28994
  } catch (readError) {
@@ -28734,7 +29026,7 @@ async function acquireRefreshFileLockWithClock2(options) {
28734
29026
  }
28735
29027
  }
28736
29028
  async function backoff() {
28737
- await new Promise((resolve22) => setTimeout(resolve22, Math.floor(Math.random() * 4)));
29029
+ await new Promise((resolve24) => setTimeout(resolve24, Math.floor(Math.random() * 4)));
28738
29030
  }
28739
29031
  async function readLockState(notifyReady = true) {
28740
29032
  if (notifyReady && options.onStep)
@@ -28743,6 +29035,8 @@ async function acquireRefreshFileLockWithClock2(options) {
28743
29035
  try {
28744
29036
  owner = await readOwner();
28745
29037
  } catch (error) {
29038
+ if (error instanceof DisappearedLockRecordError2)
29039
+ return { status: "missing" };
28746
29040
  if (windowsPrivateFiles2 && error.code !== "ENOENT")
28747
29041
  throw error;
28748
29042
  }
@@ -28790,7 +29084,7 @@ async function acquireRefreshFileLockWithClock2(options) {
28790
29084
  }
28791
29085
  async function ownsEvictionMarker() {
28792
29086
  try {
28793
- const owner = JSON.parse(await readPrivateText2(evictOwnerPath, windowsPrivateFiles2));
29087
+ const owner = JSON.parse(await readLockRecord2(evictOwnerPath, () => readPrivateText2(evictOwnerPath, windowsPrivateFiles2)));
28794
29088
  return owner?.ownerId === evictOwnerId;
28795
29089
  } catch (error) {
28796
29090
  if (windowsPrivateFiles2 && error.code !== "ENOENT")
@@ -28825,7 +29119,7 @@ async function acquireRefreshFileLockWithClock2(options) {
28825
29119
  const remainingMs = deadline - performance.now();
28826
29120
  if (remainingMs <= 0)
28827
29121
  throw original;
28828
- await new Promise((resolve22) => setTimeout(resolve22, Math.min(delayMs, remainingMs)));
29122
+ await new Promise((resolve24) => setTimeout(resolve24, Math.min(delayMs, remainingMs)));
28829
29123
  if (performance.now() >= deadline)
28830
29124
  throw original;
28831
29125
  delayMs = Math.min(delayMs * 2, 50);
@@ -28929,7 +29223,7 @@ async function acquireRefreshFileLockWithClock2(options) {
28929
29223
  }
28930
29224
  if (windowsPrivateFiles2) {
28931
29225
  try {
28932
- await verifyPrivate2(evictPath, "directory", true);
29226
+ await readLockRecord2(evictPath, () => verifyPrivate2(evictPath, "directory", true));
28933
29227
  } catch (error) {
28934
29228
  if (error.code === "ENOENT")
28935
29229
  return "missing";
@@ -28984,8 +29278,8 @@ async function acquireRefreshFileLockWithClock2(options) {
28984
29278
  if (error.code === "EEXIST") {
28985
29279
  if (windowsPrivateFiles2) {
28986
29280
  try {
28987
- await verifyPrivate2(evictPath, "directory", true);
28988
- await readPrivateText2(evictOwnerPath, true);
29281
+ await readLockRecord2(evictPath, () => verifyPrivate2(evictPath, "directory", true));
29282
+ await readLockRecord2(evictOwnerPath, () => readPrivateText2(evictOwnerPath, true));
28989
29283
  } catch (ownerError) {
28990
29284
  if (ownerError.code !== "ENOENT")
28991
29285
  throw ownerError;
@@ -29006,7 +29300,11 @@ async function acquireRefreshFileLockWithClock2(options) {
29006
29300
  try {
29007
29301
  await releaseEvictionMarker(deadline);
29008
29302
  } catch (error) {
29009
- if (isRetryableRemoval(actionError, lockPath) && isRetryableRemoval(error, evictPath))
29303
+ if ((isRetryableRemoval(actionError, lockPath) || isWindowsAccessDeniedRead2(actionError, [
29304
+ lockPath,
29305
+ legacyOwnerPath,
29306
+ evictOwnerPath
29307
+ ])) && (isRetryableRemoval(error, evictPath) || isWindowsAccessDeniedRead2(error, [evictOwnerPath])))
29010
29308
  throw actionError;
29011
29309
  throw error;
29012
29310
  }
@@ -29022,7 +29320,7 @@ async function acquireRefreshFileLockWithClock2(options) {
29022
29320
  try {
29023
29321
  owner = await readOwner();
29024
29322
  } catch (error) {
29025
- if (windowsPrivateFiles2)
29323
+ if (windowsPrivateFiles2 && !(error instanceof DisappearedLockRecordError2))
29026
29324
  throw error;
29027
29325
  return;
29028
29326
  }
@@ -29100,7 +29398,7 @@ async function acquireRefreshFileLockWithClock2(options) {
29100
29398
  await options.onStep("renewal-marker-unavailable");
29101
29399
  }
29102
29400
  } catch (error) {
29103
- if (windowsPrivateFiles2 && error instanceof PrivateFileError2) {
29401
+ if (windowsPrivateFiles2 && error instanceof PrivateFileError2 && !isChangingLockCreate(error)) {
29104
29402
  terminalIOError = error;
29105
29403
  recordLoss("renewal-failed");
29106
29404
  shouldReschedule = false;
@@ -29146,72 +29444,90 @@ async function acquireRefreshFileLockWithClock2(options) {
29146
29444
  }
29147
29445
  return null;
29148
29446
  }
29149
- let acquired = await tryAcquire();
29447
+ let acquired = false;
29448
+ let changingCreateError;
29449
+ try {
29450
+ acquired = await tryAcquire();
29451
+ } catch (error) {
29452
+ if (!isChangingLockCreate(error))
29453
+ throw error;
29454
+ changingCreateError = error;
29455
+ }
29150
29456
  if (!acquired) {
29151
29457
  for (let attempt = 0; attempt < MAX_STEAL_ATTEMPTS; attempt++) {
29152
- acquired = await tryAcquire();
29153
- if (acquired)
29154
- break;
29155
- const observed = await readLockState();
29156
- if (observed.status === "live")
29157
- return contended();
29158
- if (observed.status === "missing")
29159
- continue;
29160
- if (options.onStep)
29161
- await options.onStep("stale-lock-observed");
29162
- try {
29163
- if (!await tryAcquireEvictionMarker()) {
29164
- await backoff();
29165
- continue;
29166
- }
29167
- } catch (evictError) {
29168
- const code2 = evictError.code;
29169
- if (code2 !== "EEXIST")
29170
- throw evictError;
29171
- const recovered = await recoverStaleEvictionMarker();
29172
- if (recovered === "fresh")
29173
- return null;
29174
- await backoff();
29175
- continue;
29176
- }
29177
29458
  try {
29178
- const confirmed = await readLockState();
29179
- if (confirmed.status === "live")
29459
+ acquired = await tryAcquire();
29460
+ if (acquired)
29461
+ break;
29462
+ const observed = await readLockState();
29463
+ if (observed.status === "live")
29180
29464
  return contended();
29181
- if (!sameStaleLock(observed.identity, confirmed))
29465
+ if (observed.status === "missing")
29182
29466
  continue;
29183
- if (!await ownsEvictionMarker())
29184
- return null;
29185
29467
  if (options.onStep)
29186
- await options.onStep("stale-lock-confirmed");
29187
- if (!await ownsEvictionMarker())
29188
- return null;
29189
- const current = await readLockState(false);
29190
- if (!sameStaleLock(observed.identity, current))
29468
+ await options.onStep("stale-lock-observed");
29469
+ try {
29470
+ if (!await tryAcquireEvictionMarker()) {
29471
+ await backoff();
29472
+ continue;
29473
+ }
29474
+ } catch (evictError) {
29475
+ const code2 = evictError.code;
29476
+ if (code2 !== "EEXIST")
29477
+ throw evictError;
29478
+ const recovered = await recoverStaleEvictionMarker();
29479
+ if (recovered === "fresh")
29480
+ return null;
29481
+ await backoff();
29191
29482
  continue;
29192
- await removeLeaseObject(lockPath);
29193
- if (!await ownsEvictionMarker())
29194
- return null;
29195
- if (options.onStep)
29196
- await options.onStep("stale-lock-removed");
29197
- acquired = await tryAcquire();
29198
- if (!acquired)
29199
- return null;
29200
- if (options.onStep)
29201
- await options.onStep("stale-lock-recreated");
29202
- if (!await ownsEvictionMarker()) {
29203
- await relinquishLockAfterMarkerLoss();
29204
- acquired = false;
29205
- return null;
29206
29483
  }
29207
- break;
29208
- } finally {
29209
- await releaseEvictionMarker();
29484
+ try {
29485
+ const confirmed = await readLockState();
29486
+ if (confirmed.status === "live")
29487
+ return contended();
29488
+ if (!sameStaleLock(observed.identity, confirmed))
29489
+ continue;
29490
+ if (!await ownsEvictionMarker())
29491
+ return null;
29492
+ if (options.onStep)
29493
+ await options.onStep("stale-lock-confirmed");
29494
+ if (!await ownsEvictionMarker())
29495
+ return null;
29496
+ const current = await readLockState(false);
29497
+ if (!sameStaleLock(observed.identity, current))
29498
+ continue;
29499
+ await removeLeaseObject(lockPath);
29500
+ if (!await ownsEvictionMarker())
29501
+ return null;
29502
+ if (options.onStep)
29503
+ await options.onStep("stale-lock-removed");
29504
+ acquired = await tryAcquire();
29505
+ if (!acquired)
29506
+ return null;
29507
+ if (options.onStep)
29508
+ await options.onStep("stale-lock-recreated");
29509
+ if (!await ownsEvictionMarker()) {
29510
+ await relinquishLockAfterMarkerLoss();
29511
+ acquired = false;
29512
+ return null;
29513
+ }
29514
+ break;
29515
+ } finally {
29516
+ await releaseEvictionMarker();
29517
+ }
29518
+ } catch (error) {
29519
+ if (!isChangingLockCreate(error))
29520
+ throw error;
29521
+ changingCreateError ??= error;
29522
+ await backoff();
29210
29523
  }
29211
29524
  }
29212
29525
  }
29213
- if (!acquired)
29526
+ if (!acquired) {
29527
+ if (changingCreateError)
29528
+ throw changingCreateError;
29214
29529
  return null;
29530
+ }
29215
29531
  scheduleRenewal();
29216
29532
  return {
29217
29533
  ownerId,
@@ -29249,6 +29565,7 @@ async function acquireRefreshFileLockWithClock2(options) {
29249
29565
  const deadline = performance.now() + EVICT_TTL + 1e3;
29250
29566
  let delayMs = 5;
29251
29567
  let removalError;
29568
+ let changingRecordError;
29252
29569
  for (; ; ) {
29253
29570
  try {
29254
29571
  let removalConfirmed = false;
@@ -29274,6 +29591,7 @@ async function acquireRefreshFileLockWithClock2(options) {
29274
29591
  await removeLeaseObject(lockPath);
29275
29592
  removalConfirmed = true;
29276
29593
  }, deadline);
29594
+ changingRecordError = void 0;
29277
29595
  if (markerAcquired) {
29278
29596
  if (windowsPrivateFiles2 && !removalConfirmed)
29279
29597
  throw new PrivateFileError2(lockPath, "release-not-confirmed", {
@@ -29286,23 +29604,32 @@ async function acquireRefreshFileLockWithClock2(options) {
29286
29604
  return;
29287
29605
  await recoverStaleEvictionMarker(deadline);
29288
29606
  } catch (error) {
29289
- if (!isRetryableRemoval(error, lockPath)) {
29607
+ const changingRecord = windowsPrivateFiles2 && (isChangingLockCreate(error) || isWindowsAccessDeniedRead2(error, [
29608
+ lockPath,
29609
+ legacyOwnerPath,
29610
+ evictPath,
29611
+ evictOwnerPath
29612
+ ]));
29613
+ if (!isRetryableRemoval(error, lockPath) && !changingRecord) {
29290
29614
  if (windowsPrivateFiles2)
29291
29615
  throw error;
29292
29616
  return;
29293
29617
  }
29294
- removalError ??= error;
29618
+ if (changingRecord)
29619
+ changingRecordError ??= error;
29620
+ else
29621
+ removalError ??= error;
29295
29622
  }
29296
29623
  const remainingMs = deadline - performance.now();
29297
29624
  if (remainingMs <= 0)
29298
29625
  break;
29299
- await new Promise((resolve22) => setTimeout(resolve22, Math.min(delayMs, remainingMs)));
29626
+ await new Promise((resolve24) => setTimeout(resolve24, Math.min(delayMs, remainingMs)));
29300
29627
  if (windowsPrivateFiles2 && performance.now() >= deadline)
29301
29628
  break;
29302
29629
  delayMs = Math.min(delayMs * 2, 50);
29303
29630
  }
29304
29631
  if (windowsPrivateFiles2)
29305
- throw removalError ?? new PrivateFileError2(lockPath, "release-not-confirmed", {
29632
+ throw changingRecordError ?? removalError ?? new PrivateFileError2(lockPath, "release-not-confirmed", {
29306
29633
  code: "ETIMEDOUT"
29307
29634
  });
29308
29635
  }
@@ -29442,6 +29769,29 @@ function classifyEnrollmentError2(error) {
29442
29769
  disposition: error.action === "retry" ? "retry" : "terminal"
29443
29770
  };
29444
29771
  }
29772
+ function validEnrollmentDisplayName2(displayName) {
29773
+ const length = Array.from(displayName).length;
29774
+ return length >= 1 && length <= 40 && !/[\p{Cc}\u061c\u200e\u200f\u202a-\u202e\u2066-\u2069\u200b-\u200d\u2060\ufeff]/u.test(displayName);
29775
+ }
29776
+ function validEnrollmentRequestedGrants2(grants) {
29777
+ return Array.isArray(grants) && grants.length >= 1 && grants.length <= 4 && Array.from(grants).every((grant) => {
29778
+ if (!isRecord10(grant) || Object.keys(grant).length !== 2 || grant.operation !== "read" && grant.operation !== "list" || !isRecord10(grant.selector))
29779
+ return false;
29780
+ const keys = Object.keys(grant.selector);
29781
+ const key = keys[0];
29782
+ return keys.length === 1 && (key === "category" || key === "exact") && typeof grant.selector[key] === "string" && grant.selector[key].trim().length > 0;
29783
+ });
29784
+ }
29785
+ function grantProposal2(state) {
29786
+ return {
29787
+ ...state.requestedGrants !== void 0 && {
29788
+ requestedGrants: state.requestedGrants
29789
+ },
29790
+ ...state.requestedGrantsStatus !== void 0 && {
29791
+ requestedGrantsStatus: state.requestedGrantsStatus
29792
+ }
29793
+ };
29794
+ }
29445
29795
  function connectClaustrumEnrollmentClient2(options) {
29446
29796
  return ClaustrumWireClient2.connect(options);
29447
29797
  }
@@ -29457,7 +29807,7 @@ function hostEnrollmentPaths2(input) {
29457
29807
  const override = input.override?.trim();
29458
29808
  if (override && !isAbsolute4(override) && !input.cwd)
29459
29809
  throw new ClaustrumConsumerError2("invalid-state", "A relative Claustrum enrollment override needs a base directory");
29460
- const tokenPath = override ? isAbsolute4(override) ? override : resolve19(input.cwd, override) : join18(input.stateDir, `${input.host}-enrollment.json`);
29810
+ const tokenPath = override ? isAbsolute4(override) ? override : resolve21(input.cwd, override) : join18(input.stateDir, `${input.host}-enrollment.json`);
29461
29811
  return getClaustrumEnrollmentPaths2(tokenPath);
29462
29812
  }
29463
29813
  function isRecord10(value) {
@@ -29477,6 +29827,7 @@ function decodeEnrollmentState2(value) {
29477
29827
  throw invalidState2();
29478
29828
  }
29479
29829
  if (value.phase === "pending") {
29830
+ const grants = decodeGrantProposal2(value);
29480
29831
  if (!TOKEN_RE2.test(String(value.requestSecret ?? "")) || value.requestId !== void 0 && (typeof value.requestId !== "string" || value.requestId.length === 0) || !validTimestamp2(value.createdAt) || !validTimestamp2(value.updatedAt)) {
29481
29832
  throw invalidState2();
29482
29833
  }
@@ -29489,10 +29840,12 @@ function decodeEnrollmentState2(value) {
29489
29840
  requestId: value.requestId
29490
29841
  },
29491
29842
  createdAt: value.createdAt,
29492
- updatedAt: value.updatedAt
29843
+ updatedAt: value.updatedAt,
29844
+ ...grants
29493
29845
  };
29494
29846
  }
29495
29847
  if (value.phase === "approved") {
29848
+ const grants = decodeGrantProposal2(value);
29496
29849
  if (value.approvedName !== void 0 && (typeof value.approvedName !== "string" || value.approvedName.length === 0) || !validGeneration2(value.tokenGeneration) || !validTimestamp2(value.updatedAt)) {
29497
29850
  throw invalidState2();
29498
29851
  }
@@ -29504,7 +29857,8 @@ function decodeEnrollmentState2(value) {
29504
29857
  approvedName: value.approvedName
29505
29858
  },
29506
29859
  tokenGeneration: value.tokenGeneration,
29507
- updatedAt: value.updatedAt
29860
+ updatedAt: value.updatedAt,
29861
+ ...grants
29508
29862
  };
29509
29863
  }
29510
29864
  if (value.phase === "denied" || value.phase === "blocked") {
@@ -29523,6 +29877,11 @@ function decodeEnrollmentState2(value) {
29523
29877
  }
29524
29878
  throw invalidState2();
29525
29879
  }
29880
+ function decodeGrantProposal2(value) {
29881
+ if (value.requestedGrants !== void 0 && !validEnrollmentRequestedGrants2(value.requestedGrants) || value.requestedGrantsStatus !== void 0 && (value.requestedGrants === void 0 || value.requestedGrantsStatus !== "sent" && value.requestedGrantsStatus !== "dropped"))
29882
+ return {};
29883
+ return grantProposal2(value);
29884
+ }
29526
29885
  function decodeTokenFile2(value) {
29527
29886
  if (!isRecord10(value) || !TOKEN_RE2.test(String(value.token ?? "")) || !validGeneration2(value.token_generation)) {
29528
29887
  throw new ClaustrumConsumerError2("invalid-token", "invalid Claustrum enrollment token file");
@@ -29737,7 +30096,8 @@ async function readEnrollmentStatus2(paths, proposedName) {
29737
30096
  ...state?.phase === "approved" && state.approvedName !== void 0 && {
29738
30097
  approvedName: state.approvedName
29739
30098
  },
29740
- tokenGeneration: token.token_generation
30099
+ tokenGeneration: token.token_generation,
30100
+ ...state && (state.phase === "approved" || state.phase === "pending") && grantProposal2(state)
29741
30101
  }
29742
30102
  };
29743
30103
  }
@@ -29785,12 +30145,19 @@ async function vaultAuthority3(paths, proposedName) {
29785
30145
  return "host";
29786
30146
  return enrollmentAuthority2(paths, proposedName);
29787
30147
  }
30148
+ async function readClaustrumEnrollmentToken2(tokenPath) {
30149
+ const value = await readBoundedJson2(tokenPath);
30150
+ if (value === void 0)
30151
+ throw new ClaustrumConsumerError2("not-enrolled", "Claustrum enrollment is not configured");
30152
+ return decodeTokenFile2(value);
30153
+ }
29788
30154
  function statusFromState2(state) {
29789
30155
  if (state.phase === "pending") {
29790
30156
  return {
29791
30157
  state: "pending",
29792
30158
  proposedName: state.proposedName,
29793
- ...state.requestId !== void 0 && { requestId: state.requestId }
30159
+ ...state.requestId !== void 0 && { requestId: state.requestId },
30160
+ ...grantProposal2(state)
29794
30161
  };
29795
30162
  }
29796
30163
  if (state.phase === "approved") {
@@ -29800,7 +30167,8 @@ function statusFromState2(state) {
29800
30167
  ...state.approvedName !== void 0 && {
29801
30168
  approvedName: state.approvedName
29802
30169
  },
29803
- tokenGeneration: state.tokenGeneration
30170
+ tokenGeneration: state.tokenGeneration,
30171
+ ...grantProposal2(state)
29804
30172
  };
29805
30173
  }
29806
30174
  if (state.phase === "denied")
@@ -29818,15 +30186,26 @@ var ClaustrumEnrollmentManager2 = class {
29818
30186
  #client;
29819
30187
  #paths;
29820
30188
  #proposedName;
30189
+ #displayName;
30190
+ #requestedGrants;
29821
30191
  #now;
29822
30192
  #mintSecret;
29823
30193
  #writeTokenFile;
29824
30194
  #ancestorOptions;
29825
30195
  constructor(options) {
30196
+ if (options.displayName !== void 0 && !validEnrollmentDisplayName2(options.displayName))
30197
+ throw new ClaustrumConsumerError2("invalid-state", "invalid Claustrum enrollment display name");
30198
+ if (options.requestedGrants !== void 0 && !validEnrollmentRequestedGrants2(options.requestedGrants))
30199
+ throw new ClaustrumConsumerError2("invalid-state", "invalid Claustrum enrollment requested grants");
30200
+ this.#requestedGrants = options.requestedGrants?.map((grant) => ({
30201
+ selector: { ...grant.selector },
30202
+ operation: grant.operation
30203
+ }));
29826
30204
  this.#ancestorOptions = options.ancestorOptions ?? {};
29827
30205
  this.#client = options.client;
29828
30206
  this.#paths = options.paths;
29829
30207
  this.#proposedName = options.proposedName;
30208
+ this.#displayName = options.displayName;
29830
30209
  this.#now = options.now ?? Date.now;
29831
30210
  this.#mintSecret = options.mintSecret ?? (() => randomBytes3(32).toString("hex"));
29832
30211
  this.#writeTokenFile = options.writeTokenFile ?? writeEnrollmentTokenFile2;
@@ -29872,6 +30251,7 @@ var ClaustrumEnrollmentManager2 = class {
29872
30251
  phase: "approved",
29873
30252
  proposedName: state?.proposedName ?? this.#proposedName,
29874
30253
  tokenGeneration: token.token_generation,
30254
+ ...state && grantProposal2(state),
29875
30255
  updatedAt: this.#now()
29876
30256
  };
29877
30257
  await writeStateAtomic2(this.#paths.statePath, approved, this.#ancestorOptions);
@@ -29883,7 +30263,8 @@ var ClaustrumEnrollmentManager2 = class {
29883
30263
  ...state.phase === "approved" && state.approvedName !== void 0 && {
29884
30264
  approvedName: state.approvedName
29885
30265
  },
29886
- tokenGeneration: token.token_generation
30266
+ tokenGeneration: token.token_generation,
30267
+ ...state.phase === "approved" && grantProposal2(state)
29887
30268
  };
29888
30269
  }
29889
30270
  if (state?.phase === "approved") {
@@ -29907,7 +30288,10 @@ var ClaustrumEnrollmentManager2 = class {
29907
30288
  proposedName: this.#proposedName,
29908
30289
  requestSecret: this.#mintSecret(),
29909
30290
  createdAt: now,
29910
- updatedAt: now
30291
+ updatedAt: now,
30292
+ ...this.#requestedGrants !== void 0 && {
30293
+ requestedGrants: this.#requestedGrants
30294
+ }
29911
30295
  };
29912
30296
  if (!TOKEN_RE2.test(state.requestSecret))
29913
30297
  throw new ClaustrumConsumerError2("invalid-state", "invalid minted Claustrum enrollment secret");
@@ -29916,14 +30300,38 @@ var ClaustrumEnrollmentManager2 = class {
29916
30300
  if (!state.requestId) {
29917
30301
  try {
29918
30302
  const requestSecretHash = createHash12("sha256").update(Buffer.from(state.requestSecret, "hex")).digest("hex");
29919
- const proposed = await this.#client.enrollPropose({
30303
+ const proposal = {
29920
30304
  name: state.proposedName,
29921
30305
  requestSecretHash
29922
- });
30306
+ };
30307
+ let proposed;
30308
+ let requestedGrantsStatus = state.requestedGrantsStatus;
30309
+ try {
30310
+ proposed = await this.#client.enrollPropose({
30311
+ ...proposal,
30312
+ ...this.#displayName !== void 0 && {
30313
+ displayName: this.#displayName
30314
+ },
30315
+ ...state.requestedGrants !== void 0 && {
30316
+ requestedGrants: state.requestedGrants
30317
+ }
30318
+ });
30319
+ if (state.requestedGrants !== void 0)
30320
+ requestedGrantsStatus = "sent";
30321
+ } catch (error) {
30322
+ if (this.#displayName === void 0 && state.requestedGrants === void 0 || !(error instanceof ClaustrumCredentialError9) || error.code !== "invalid_params")
30323
+ throw error;
30324
+ proposed = await this.#client.enrollPropose(proposal);
30325
+ if (state.requestedGrants !== void 0)
30326
+ requestedGrantsStatus = "dropped";
30327
+ }
29923
30328
  state = {
29924
30329
  ...state,
29925
30330
  requestId: proposed.requestId,
29926
- updatedAt: this.#now()
30331
+ updatedAt: this.#now(),
30332
+ ...requestedGrantsStatus !== void 0 && {
30333
+ requestedGrantsStatus
30334
+ }
29927
30335
  };
29928
30336
  await writeStateAtomic2(this.#paths.statePath, state, this.#ancestorOptions);
29929
30337
  } catch (error) {
@@ -29934,7 +30342,8 @@ var ClaustrumEnrollmentManager2 = class {
29934
30342
  return {
29935
30343
  state: "pending",
29936
30344
  proposedName: state.proposedName,
29937
- retryCode: refusal3.code
30345
+ retryCode: refusal3.code,
30346
+ ...grantProposal2(state)
29938
30347
  };
29939
30348
  }
29940
30349
  if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE2) {
@@ -29984,6 +30393,7 @@ var ClaustrumEnrollmentManager2 = class {
29984
30393
  proposedName: state.proposedName,
29985
30394
  approvedName: outcome.name,
29986
30395
  tokenGeneration: outcome.tokenGeneration,
30396
+ ...grantProposal2(state),
29987
30397
  updatedAt: this.#now()
29988
30398
  };
29989
30399
  await writeStateAtomic2(this.#paths.statePath, approved, this.#ancestorOptions);
@@ -29997,7 +30407,8 @@ var ClaustrumEnrollmentManager2 = class {
29997
30407
  state: "pending",
29998
30408
  proposedName: state.proposedName,
29999
30409
  requestId,
30000
- retryCode: refusal3.code
30410
+ retryCode: refusal3.code,
30411
+ ...grantProposal2(state)
30001
30412
  };
30002
30413
  }
30003
30414
  return this.#block(state, refusal3.code);
@@ -30090,7 +30501,7 @@ var ByteTail = class {
30090
30501
  };
30091
30502
  var defaultCommandRunner = {
30092
30503
  run(file, args, options = {}) {
30093
- return new Promise((resolve22) => {
30504
+ return new Promise((resolve24) => {
30094
30505
  const started = performance.now();
30095
30506
  const timeoutMs = options.timeoutMs ?? 15e3;
30096
30507
  const stderr = new ByteTail();
@@ -30108,7 +30519,7 @@ var defaultCommandRunner = {
30108
30519
  stdio: ["ignore", "pipe", "pipe"]
30109
30520
  });
30110
30521
  } catch {
30111
- resolve22({
30522
+ resolve24({
30112
30523
  exitCode: 1,
30113
30524
  stdout: "",
30114
30525
  stderr: "",
@@ -30143,7 +30554,7 @@ var defaultCommandRunner = {
30143
30554
  settled = true;
30144
30555
  if (timer)
30145
30556
  clearTimeout(timer);
30146
- resolve22({
30557
+ resolve24({
30147
30558
  exitCode: spawnError ? 1 : outputExceeded ? 1 : code2 ?? 1,
30148
30559
  stdout: Buffer.concat(stdout, stdoutLength).toString("utf8"),
30149
30560
  stderr: stderr.toString(),
@@ -30176,6 +30587,68 @@ function runResolvedCommand(runner, platform, file, args, env3, timeoutMs = 15e3
30176
30587
  return runner.run(file, args, { env: env3, timeoutMs });
30177
30588
  }
30178
30589
 
30590
+ // src/common-auth-embedded/setup/enrollment-access.js
30591
+ function shellArgument(value) {
30592
+ if (/^[a-zA-Z0-9_:@./-]+$/.test(value))
30593
+ return value;
30594
+ return process.platform === "win32" ? `'${value.replaceAll("'", "''")}'` : `'${value.replaceAll("'", "'\\''")}'`;
30595
+ }
30596
+ async function confirmEnrollmentAccess(client, status, tokenPath, configuredGrants) {
30597
+ const requestedGrants = status.requestedGrants ?? configuredGrants;
30598
+ if (!requestedGrants)
30599
+ return void 0;
30600
+ const grants = requestedGrants.map((grant) => ({
30601
+ grant,
30602
+ ...status.approvedName !== void 0 && {
30603
+ grantCommand: `ck auth grant --principal ${shellArgument(`enrolled:${status.approvedName}`)} --selector-kind ${grant.selector.exact === void 0 ? "category" : "exact"} --selector ${shellArgument(grant.selector.exact ?? grant.selector.category)} --operation ${grant.operation}`
30604
+ }
30605
+ }));
30606
+ if (status.requestedGrantsStatus === "dropped")
30607
+ return { state: "older-vault", grants };
30608
+ try {
30609
+ if (!client.listScoped)
30610
+ return { state: "unconfirmed", grants };
30611
+ const { token } = await readClaustrumEnrollmentToken2(tokenPath);
30612
+ const inventory = await client.listScoped(token);
30613
+ const confirmed = grants.map((entry) => ({
30614
+ ...entry,
30615
+ reachableLogins: inventory.rows.filter((row) => row.operations.includes(entry.grant.operation) && (entry.grant.selector.exact !== void 0 ? row.id === entry.grant.selector.exact : row.categories.includes(entry.grant.selector.category))).length
30616
+ }));
30617
+ return {
30618
+ state: confirmed.every((entry) => entry.reachableLogins > 0) ? "reachable" : confirmed.some((entry) => entry.reachableLogins > 0) ? "partial" : "no-logins",
30619
+ grants: confirmed.map((entry) => {
30620
+ if (entry.reachableLogins === 0)
30621
+ return entry;
30622
+ const { grantCommand: _, ...reachable } = entry;
30623
+ return reachable;
30624
+ })
30625
+ };
30626
+ } catch {
30627
+ return { state: "unconfirmed", grants };
30628
+ }
30629
+ }
30630
+ function enrollmentAccessLines(access) {
30631
+ const lines = [];
30632
+ const remedy = access.grants.some((entry) => entry.grantCommand) ? "run:" : "check ck auth status for the approved name before granting access.";
30633
+ if (access.state === "older-vault")
30634
+ lines.push(`Approved. This vault is too old to grant access with the approval; ${remedy}`);
30635
+ else if (access.state === "no-logins")
30636
+ lines.push(`Approved, but no logins are reachable yet; ${remedy}`);
30637
+ else if (access.state === "partial")
30638
+ lines.push(`Approved, but some requested access has no reachable logins yet; ${remedy}`);
30639
+ else if (access.state === "unconfirmed")
30640
+ lines.push(`Approved, but access could not be confirmed; ${access.grants.some((entry) => entry.grantCommand) ? "check ck auth status or run:" : remedy}`);
30641
+ for (const { grant, reachableLogins, grantCommand } of access.grants) {
30642
+ if (reachableLogins !== void 0 && reachableLogins > 0) {
30643
+ const target = grant.selector.exact === void 0 ? `the vault's ${JSON.stringify(grant.selector.category)} accounts` : `credential ${JSON.stringify(grant.selector.exact)}`;
30644
+ lines.push(`Confirmed ${grant.operation} access to ${target} (${reachableLogins} reachable ${reachableLogins === 1 ? "login" : "logins"}).`);
30645
+ }
30646
+ if (grantCommand)
30647
+ lines.push(` ${grantCommand}`);
30648
+ }
30649
+ return lines;
30650
+ }
30651
+
30179
30652
  // src/common-auth-embedded/setup/command-error.js
30180
30653
  var PI_INSTALL_ERROR_MESSAGE = "Pi install failed; run pi install after checking your npm connection.";
30181
30654
  function utf8Tail(value) {
@@ -30216,8 +30689,8 @@ var OUTCOME_TEXT = {
30216
30689
  "not-enrolled": "not connected",
30217
30690
  unknown: "unknown, check with ck auth status"
30218
30691
  };
30219
- function setupEnrollmentLine({ host, outcome }) {
30220
- return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}`;
30692
+ function setupEnrollmentLine({ host, outcome, access }) {
30693
+ return `${HOST_LABELS[host]}: ${OUTCOME_TEXT[outcome]}${access ? ` \u2014 ${enrollmentAccessLines(access).join("\n")}` : ""}`;
30221
30694
  }
30222
30695
  var recordedEnrollment = /* @__PURE__ */ new WeakMap();
30223
30696
  function recordSetupEnrollment(failure, enrollment) {
@@ -30755,7 +31228,7 @@ function approveCommand(requestId, name) {
30755
31228
  async function connectSetupHost(plugin, host, io, terminal, fence) {
30756
31229
  if (hasVaultHost2())
30757
31230
  throw new Error(VAULT_HOST_CONNECT_REFUSAL2);
30758
- const { name, paths: input } = plugin.vault.hosts[host];
31231
+ const { name, displayName, requestedGrants, paths: input } = plugin.vault.hosts[host];
30759
31232
  const paths = hostEnrollmentPaths2(input);
30760
31233
  await fence();
30761
31234
  const client = await (io.connect ?? connectClaustrumEnrollmentClient2)({
@@ -30769,6 +31242,8 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
30769
31242
  try {
30770
31243
  const manager = new ClaustrumEnrollmentManager2({
30771
31244
  proposedName: name,
31245
+ displayName,
31246
+ requestedGrants,
30772
31247
  paths,
30773
31248
  // Each tick of the wait below checks the fence once, just before
30774
31249
  // reconcile proposes or polls. Checking again inside every vault call
@@ -30784,7 +31259,11 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
30784
31259
  const initial = await manager.status();
30785
31260
  if (initial.state === "approved") {
30786
31261
  printLine2(terminal, `Already connected as ${initial.approvedName ?? initial.proposedName}.`);
30787
- return;
31262
+ const access = await confirmEnrollmentAccess(client, initial, paths.tokenPath, requestedGrants);
31263
+ if (access)
31264
+ for (const line of enrollmentAccessLines(access))
31265
+ printLine2(terminal, line);
31266
+ return access;
30788
31267
  }
30789
31268
  printLine2(terminal, `Asking the vault to connect ${name}\u2026`);
30790
31269
  const deadline = now() + ENROLLMENT_WAIT_MS;
@@ -30796,7 +31275,11 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
30796
31275
  const status = await manager.reconcile();
30797
31276
  if (status.state === "approved") {
30798
31277
  printLine2(terminal, `Connected ${host} to Claustrum.`);
30799
- return;
31278
+ const access = await confirmEnrollmentAccess(client, status, paths.tokenPath, requestedGrants);
31279
+ if (access)
31280
+ for (const line of enrollmentAccessLines(access))
31281
+ printLine2(terminal, line);
31282
+ return access;
30800
31283
  }
30801
31284
  if (status.state === "unavailable" && status.code === UNSUPPORTED_ENROLLMENT_CODE2)
30802
31285
  throw new HostNotEnrolledError(UNSUPPORTED_VAULT_MESSAGE, {
@@ -31230,12 +31713,15 @@ function validatePlugin(plugin) {
31230
31713
  for (const host of Object.values(plugin.vault.hosts)) {
31231
31714
  if (!/^[a-z0-9][a-z0-9-]*$/.test(host.name))
31232
31715
  throw new Error("Setup requires lowercase vault names containing only letters, digits and dashes.");
31716
+ if (host.requestedGrants !== void 0 && !validEnrollmentRequestedGrants2(host.requestedGrants))
31717
+ throw new Error("invalid Claustrum enrollment requested grants");
31233
31718
  }
31234
31719
  }
31235
- async function enrollmentReport(plugin, hosts, recorded) {
31720
+ async function enrollmentReport(plugin, hosts, recorded, recordedAccess) {
31236
31721
  const report = [];
31237
31722
  for (const host of hosts) {
31238
31723
  let outcome = recorded.get(host) ?? "not-enrolled";
31724
+ let access = recordedAccess.get(host);
31239
31725
  if (outcome === "unknown") {
31240
31726
  const { name, paths } = plugin.vault.hosts[host];
31241
31727
  const authority = await vaultAuthority3(hostEnrollmentPaths2(paths), name).catch(() => "unreadable");
@@ -31243,8 +31729,13 @@ async function enrollmentReport(plugin, hosts, recorded) {
31243
31729
  outcome = "enrolled";
31244
31730
  else if (authority === "local")
31245
31731
  outcome = "not-enrolled";
31732
+ if (outcome === "enrolled") {
31733
+ const status = await readClaustrumEnrollmentStatus2(hostEnrollmentPaths2(paths), name).catch(() => void 0);
31734
+ if (status?.state === "approved")
31735
+ access = await confirmEnrollmentAccess({}, status, hostEnrollmentPaths2(paths).tokenPath, plugin.vault.hosts[host].requestedGrants);
31736
+ }
31246
31737
  }
31247
- report.push({ host, outcome });
31738
+ report.push({ host, outcome, ...access && { access } });
31248
31739
  }
31249
31740
  return report;
31250
31741
  }
@@ -31373,6 +31864,7 @@ ${write.content}`);
31373
31864
  piAgentDir: detection.pi.directory
31374
31865
  };
31375
31866
  const enrollment = /* @__PURE__ */ new Map();
31867
+ const enrollmentAccess = /* @__PURE__ */ new Map();
31376
31868
  try {
31377
31869
  for (const host of hosts) {
31378
31870
  await stopped();
@@ -31381,7 +31873,9 @@ ${write.content}`);
31381
31873
  if (useVault) {
31382
31874
  enrollment.set(host, "unknown");
31383
31875
  try {
31384
- await connectSetupHost(plugin, host, io, terminal, stopped);
31876
+ const access = await connectSetupHost(plugin, host, io, terminal, stopped);
31877
+ if (access)
31878
+ enrollmentAccess.set(host, access);
31385
31879
  } catch (error) {
31386
31880
  if (error instanceof HostNotEnrolledError)
31387
31881
  enrollment.set(host, "not-enrolled");
@@ -31406,7 +31900,7 @@ ${write.content}`);
31406
31900
  if (enrollment.size === 0)
31407
31901
  throw error;
31408
31902
  try {
31409
- const report = await enrollmentReport(plugin, hosts, enrollment);
31903
+ const report = await enrollmentReport(plugin, hosts, enrollment, enrollmentAccess);
31410
31904
  recordSetupEnrollment(error, report);
31411
31905
  for (const entry of report)
31412
31906
  printLine2(terminal, setupEnrollmentLine(entry));
@@ -31515,7 +32009,7 @@ async function writeNativeSlot(host, slot, context, expectedAuthority = "local")
31515
32009
  beforeRename: async () => {
31516
32010
  await assertSetupHostsStopped();
31517
32011
  const claustrum = await loadCommonAuthClaustrum();
31518
- const stateDir = host === "opencode" ? openCodeVaultDir(resolve20(accountFileForVault())) : getPiAntigravityVaultDir();
32012
+ const stateDir = host === "opencode" ? openCodeVaultDir(resolve22(accountFileForVault())) : getPiAntigravityVaultDir();
31519
32013
  if (await claustrum.vaultAuthority(
31520
32014
  claustrum.hostEnrollmentPaths({ stateDir, host }),
31521
32015
  `antigravity-auth-${host}`
@@ -31549,17 +32043,31 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
31549
32043
  const hosts = {
31550
32044
  opencode: {
31551
32045
  name: OPENCODE_VAULT_ENROLLMENT_NAME,
32046
+ displayName: "Antigravity sign-in for OpenCode",
32047
+ requestedGrants: [
32048
+ {
32049
+ selector: { category: "antigravity-native" },
32050
+ operation: "read"
32051
+ }
32052
+ ],
31552
32053
  // Read at each use: a real run settles the vault folder in
31553
32054
  // `beforeSignIn`, which may move it after this plugin is built.
31554
32055
  paths: {
31555
32056
  get stateDir() {
31556
- return openCodeVaultDir(resolve20(accountFileForVault()));
32057
+ return openCodeVaultDir(resolve22(accountFileForVault()));
31557
32058
  },
31558
32059
  host: "opencode"
31559
32060
  }
31560
32061
  },
31561
32062
  pi: {
31562
32063
  name: "antigravity-auth-pi",
32064
+ displayName: "Antigravity sign-in for Pi",
32065
+ requestedGrants: [
32066
+ {
32067
+ selector: { category: "antigravity-native" },
32068
+ operation: "read"
32069
+ }
32070
+ ],
31563
32071
  paths: { stateDir: piDir, host: "pi" }
31564
32072
  }
31565
32073
  };
@@ -31570,7 +32078,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
31570
32078
  const assertLocal = async (host, context) => {
31571
32079
  if (host === "opencode")
31572
32080
  return assertLocalOpenCodeLogin(
31573
- resolve20(accountFileForVault()),
32081
+ resolve22(accountFileForVault()),
31574
32082
  context.opencodeGeneration
31575
32083
  );
31576
32084
  if (await authority(host) !== "local")
@@ -32230,7 +32738,7 @@ async function runCliProcess(argv, deps) {
32230
32738
  ...deps,
32231
32739
  prepareVaultFolder: deps.prepareVaultFolder ?? (async (options) => {
32232
32740
  const folder = await prepareVaultFolder({
32233
- accountFile: resolve21(accountFileForVault()),
32741
+ accountFile: resolve23(accountFileForVault()),
32234
32742
  ...options
32235
32743
  });
32236
32744
  if (folder.refusal) throw folder.refusal;
@@ -32276,11 +32784,11 @@ function createDefaultCliDependencies() {
32276
32784
  );
32277
32785
  if (host !== "pi")
32278
32786
  await assertLocalOpenCodeLogin(
32279
- resolve21(accountFileForVault()),
32787
+ resolve23(accountFileForVault()),
32280
32788
  context?.opencodeGeneration
32281
32789
  );
32282
32790
  const repository = host === "pi" ? void 0 : await prepareCliLoginStore(
32283
- resolve21(getStoragePath()),
32791
+ resolve23(getStoragePath()),
32284
32792
  context?.opencodeGeneration
32285
32793
  );
32286
32794
  try {
@@ -32296,7 +32804,7 @@ function createDefaultCliDependencies() {
32296
32804
  }
32297
32805
  if (host === "opencode") await assertSetupHostsStopped();
32298
32806
  await assertLocalOpenCodeLogin(
32299
- resolve21(accountFileForVault()),
32807
+ resolve23(accountFileForVault()),
32300
32808
  context?.opencodeGeneration
32301
32809
  );
32302
32810
  await persistCliStoreLogin(
@@ -32316,7 +32824,7 @@ function createDefaultCliDependencies() {
32316
32824
  };
32317
32825
  }
32318
32826
  async function prepareCliLoginStore(legacyPath, generation) {
32319
- await assertLocalOpenCodeLogin(resolve21(accountFileForVault()), generation);
32827
+ await assertLocalOpenCodeLogin(resolve23(accountFileForVault()), generation);
32320
32828
  const modules = await loadCommonAuthStoreModules();
32321
32829
  const options = {
32322
32830
  legacyPath,
@@ -32461,7 +32969,7 @@ async function readAccountStore(legacyPath) {
32461
32969
  function createDefaultAccountStoreOperations() {
32462
32970
  const offline = { processesStopped: true };
32463
32971
  return {
32464
- legacyPath: () => resolve21(
32972
+ legacyPath: () => resolve23(
32465
32973
  decidedAccountStoreAnchor(runtimeLayoutLocation()) ? getStoragePath() : discoveredAccountFile()
32466
32974
  ),
32467
32975
  migrate: async (legacyPath) => createAccountMigrationFactory(await loadCommonAuthStoreModules())({
@@ -32492,7 +33000,7 @@ function createDefaultAccountStoreOperations() {
32492
33000
  };
32493
33001
  }
32494
33002
  function samePath(left, right) {
32495
- return process.platform === "win32" ? resolve21(left).toLowerCase() === resolve21(right).toLowerCase() : resolve21(left) === resolve21(right);
33003
+ return process.platform === "win32" ? resolve23(left).toLowerCase() === resolve23(right).toLowerCase() : resolve23(left) === resolve23(right);
32496
33004
  }
32497
33005
  function isCliEntry() {
32498
33006
  if (import.meta.main !== void 0) return import.meta.main;