@cortexkit/opencode-antigravity-auth 3.0.10 → 3.0.11

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 (53) hide show
  1. package/dist/cli.js +319 -111
  2. package/dist/cli.js.map +3 -3
  3. package/dist/cli.meta.json +48 -23
  4. package/dist/index.js +457 -211
  5. package/dist/index.js.map +3 -3
  6. package/dist/index.meta.json +55 -30
  7. package/dist/server.js +457 -211
  8. package/dist/server.js.map +3 -3
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/claustrum/enrollment.d.ts +5 -0
  11. package/dist/src/common-auth-embedded/claustrum/enrollment.js +27 -0
  12. package/dist/src/common-auth-embedded/fs/private-files.d.ts +2 -0
  13. package/dist/src/common-auth-embedded/fs/private-files.js +49 -3
  14. package/dist/src/common-auth-embedded/setup/enroll.d.ts +34 -0
  15. package/dist/src/common-auth-embedded/setup/enroll.js +116 -34
  16. package/dist/src/common-auth-embedded/setup/index.d.ts +1 -0
  17. package/dist/src/common-auth-embedded/setup/index.js +1 -0
  18. package/dist/src/common-auth-embedded/setup/process-fence.d.ts +7 -0
  19. package/dist/src/common-auth-embedded/setup/process-fence.js +56 -1
  20. package/dist/src/common-auth-embedded/setup/types.d.ts +5 -0
  21. package/dist/src/common-auth-embedded/source-output.json +45 -37
  22. package/dist/src/plugin/lifecycle.d.ts.map +1 -1
  23. package/dist/src/plugin/lifecycle.js +48 -27
  24. package/dist/src/plugin/lifecycle.js.map +1 -1
  25. package/dist/src/plugin/shared/request-services.js +2 -2
  26. package/dist/src/plugin/shared/request-services.js.map +1 -1
  27. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  28. package/dist/src/plugin/vault-custody.js +13 -3
  29. package/dist/src/plugin/vault-custody.js.map +1 -1
  30. package/dist/tui-build-map.json +5 -5
  31. package/dist/tui-ga-build-map.json +1 -1
  32. package/dist/types/src/common-auth-embedded/claustrum/enrollment.d.ts +5 -0
  33. package/dist/types/src/common-auth-embedded/setup/enroll.d.ts +34 -0
  34. package/dist/types/src/common-auth-embedded/setup/index.d.ts +1 -0
  35. package/dist/types/src/common-auth-embedded/setup/process-fence.d.ts +7 -0
  36. package/dist/types/src/common-auth-embedded/setup/types.d.ts +5 -0
  37. package/dist/types/src/plugin/lifecycle.d.ts.map +1 -1
  38. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  39. package/package.json +2 -2
  40. package/src/common-auth-embedded/claustrum/enrollment.d.ts +5 -0
  41. package/src/common-auth-embedded/claustrum/enrollment.js +27 -0
  42. package/src/common-auth-embedded/fs/private-files.d.ts +2 -0
  43. package/src/common-auth-embedded/fs/private-files.js +49 -3
  44. package/src/common-auth-embedded/setup/enroll.d.ts +34 -0
  45. package/src/common-auth-embedded/setup/enroll.js +116 -34
  46. package/src/common-auth-embedded/setup/index.d.ts +1 -0
  47. package/src/common-auth-embedded/setup/index.js +1 -0
  48. package/src/common-auth-embedded/setup/process-fence.d.ts +7 -0
  49. package/src/common-auth-embedded/setup/process-fence.js +56 -1
  50. package/src/common-auth-embedded/setup/types.d.ts +5 -0
  51. package/src/common-auth-embedded/source-output.json +45 -37
  52. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +49 -3
  53. package/src/tui-raw/common-auth-embedded/fs/private-files.js +49 -3
package/dist/index.js CHANGED
@@ -764,7 +764,8 @@ var init_identity = __esm({
764
764
  // ../core/dist/common-auth-embedded/fs/private-files.js
765
765
  import { randomUUID as randomUUID7 } from "node:crypto";
766
766
  import { lstat as lstat2, readFile as readFile4, rename as rename3, unlink as unlink5 } from "node:fs/promises";
767
- import { dirname as dirname5, resolve as resolve2 } from "node:path";
767
+ import { tmpdir } from "node:os";
768
+ import { dirname as dirname5, join as join4, resolve as resolve2 } from "node:path";
768
769
  function ioCode(detail) {
769
770
  if (detail?.reason === "io-error") {
770
771
  if (detail.win32Code === 2 || detail.win32Code === 3)
@@ -774,8 +775,31 @@ function ioCode(detail) {
774
775
  }
775
776
  return detail?.code ?? "ERR_PRIVATE_FILE";
776
777
  }
778
+ function privateFilesUnavailable(cause) {
779
+ return Object.assign(new Error("Windows private-files native addon is unavailable", { cause }), {
780
+ code: "ERR_PRIVATE_FILES_UNAVAILABLE",
781
+ reason: PRIVATE_FILES_UNAVAILABLE_REASON
782
+ });
783
+ }
784
+ function isUnavailable(api, error) {
785
+ return error instanceof api.PrivateFilesUnavailableError || error?.code === "ERR_PRIVATE_FILES_UNAVAILABLE";
786
+ }
787
+ async function assertNativeAddonLoads(api) {
788
+ try {
789
+ await api.verifyPrivatePath(join4(tmpdir(), `.common-auth-private-files-probe-${randomUUID7()}`), "file");
790
+ } catch (error) {
791
+ if (isUnavailable(api, error))
792
+ throw privateFilesUnavailable(error);
793
+ }
794
+ }
777
795
  function loadBackend() {
778
- backend ??= import("@cortexkit/private-files");
796
+ backend ??= import("@cortexkit/private-files").then(async (api) => {
797
+ if (windowsPrivateFiles)
798
+ await assertNativeAddonLoads(api);
799
+ return api;
800
+ }, (cause) => {
801
+ throw windowsPrivateFiles ? privateFilesUnavailable(cause) : cause;
802
+ });
779
803
  return backend;
780
804
  }
781
805
  async function privateOperation(path5, stage, operation) {
@@ -1001,12 +1025,13 @@ async function writePrivateAtomic(path5, bytes, options = {}) {
1001
1025
  });
1002
1026
  }
1003
1027
  }
1004
- var windowsPrivateFiles, migrationNotices, backend, PrivateFileError, safeParentOptionsForTest;
1028
+ var windowsPrivateFiles, migrationNotices, backend, PRIVATE_FILES_UNAVAILABLE_REASON, PrivateFileError, safeParentOptionsForTest;
1005
1029
  var init_private_files = __esm({
1006
1030
  "../core/dist/common-auth-embedded/fs/private-files.js"() {
1007
1031
  "use strict";
1008
1032
  windowsPrivateFiles = process.platform === "win32";
1009
1033
  migrationNotices = /* @__PURE__ */ new Set();
1034
+ PRIVATE_FILES_UNAVAILABLE_REASON = "native-addon-unavailable";
1010
1035
  PrivateFileError = class extends Error {
1011
1036
  path;
1012
1037
  stage;
@@ -1021,7 +1046,7 @@ var init_private_files = __esm({
1021
1046
  orphanPath;
1022
1047
  constructor(path5, stage, cause) {
1023
1048
  const detail = cause;
1024
- super(`Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`, { cause });
1049
+ super(detail?.code === "ERR_PRIVATE_FILES_UNAVAILABLE" ? `Private file refused at ${stage}: ${path5} (${PRIVATE_FILES_UNAVAILABLE_REASON}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.` : `Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
1025
1050
  this.path = path5;
1026
1051
  this.stage = stage;
1027
1052
  this.name = "PrivateFileError";
@@ -1132,7 +1157,7 @@ var init_atomic_write = __esm({
1132
1157
  // ../core/dist/common-auth-embedded/fs/refresh-file-lock.js
1133
1158
  import { randomUUID as randomUUID9 } from "node:crypto";
1134
1159
  import { mkdir as mkdir7, open as open4, readFile as readFile5, rename as rename5, rm as rm4, stat as stat3 } from "node:fs/promises";
1135
- import { dirname as dirname7, join as join4 } from "node:path";
1160
+ import { dirname as dirname7, join as join5 } from "node:path";
1136
1161
  async function createExclusiveText(path5, text2) {
1137
1162
  const handle = await open4(path5, "wx", 384);
1138
1163
  try {
@@ -1150,7 +1175,7 @@ function acquireRefreshFileLock(options) {
1150
1175
  }
1151
1176
  async function acquireRefreshFileLockWithClock(options) {
1152
1177
  const lockPath = lockPathFor(options.path, options.name);
1153
- const legacyOwnerPath = join4(lockPath, "owner.json");
1178
+ const legacyOwnerPath = join5(lockPath, "owner.json");
1154
1179
  const ownerId = randomUUID9();
1155
1180
  const now = options.now ?? Date.now;
1156
1181
  let renewTimer = null;
@@ -1193,7 +1218,7 @@ async function acquireRefreshFileLockWithClock(options) {
1193
1218
  let terminalIOError;
1194
1219
  let renewalInFlight = null;
1195
1220
  const evictPath = `${lockPath}.evicting`;
1196
- const evictOwnerPath = join4(evictPath, "owner.json");
1221
+ const evictOwnerPath = join5(evictPath, "owner.json");
1197
1222
  const evictOwnerId = randomUUID9();
1198
1223
  const EVICT_TTL = 5e3;
1199
1224
  const MAX_STEAL_ATTEMPTS = 8;
@@ -8862,7 +8887,7 @@ var init_any_signal = __esm({
8862
8887
  import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID12 } from "node:crypto";
8863
8888
  import { constants as fsConstants } from "node:fs";
8864
8889
  import { chmod as chmod2, mkdir as mkdir8, open as open6, readFile as readFile6, realpath as realpath3, rename as rename6, stat as stat4, unlink as unlink6 } from "node:fs/promises";
8865
- import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join5, resolve as resolve5 } from "node:path";
8890
+ import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve5 } from "node:path";
8866
8891
  import { ClaustrumCredentialError as ClaustrumCredentialError2, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8867
8892
  function classifyEnrollmentError(error) {
8868
8893
  if (!(error instanceof ClaustrumCredentialError2))
@@ -8888,7 +8913,7 @@ function getClaustrumEnrollmentPaths(tokenPath) {
8888
8913
  const extension = extname(tokenPath) || ".json";
8889
8914
  const stem = basename3(tokenPath, extname(tokenPath));
8890
8915
  return {
8891
- statePath: join5(dirname9(tokenPath), `${stem}-state${extension}`),
8916
+ statePath: join6(dirname9(tokenPath), `${stem}-state${extension}`),
8892
8917
  tokenPath
8893
8918
  };
8894
8919
  }
@@ -8896,7 +8921,7 @@ function hostEnrollmentPaths(input2) {
8896
8921
  const override = input2.override?.trim();
8897
8922
  if (override && !isAbsolute2(override) && !input2.cwd)
8898
8923
  throw new ClaustrumConsumerError("invalid-state", "A relative Claustrum enrollment override needs a base directory");
8899
- const tokenPath = override ? isAbsolute2(override) ? override : resolve5(input2.cwd, override) : join5(input2.stateDir, `${input2.host}-enrollment.json`);
8924
+ const tokenPath = override ? isAbsolute2(override) ? override : resolve5(input2.cwd, override) : join6(input2.stateDir, `${input2.host}-enrollment.json`);
8900
8925
  return getClaustrumEnrollmentPaths(tokenPath);
8901
8926
  }
8902
8927
  function isRecord6(value) {
@@ -9129,7 +9154,7 @@ async function writeStateAtomic(path5, state, ancestorOptions = {}) {
9129
9154
  }
9130
9155
  if (windowsPrivateFiles)
9131
9156
  return writePrivateAtomic(path5, bytes);
9132
- const temporary = join5(parent, `.${basename3(path5)}.${process.pid}.${randomUUID12()}.tmp`);
9157
+ const temporary = join6(parent, `.${basename3(path5)}.${process.pid}.${randomUUID12()}.tmp`);
9133
9158
  let descriptor;
9134
9159
  let created = false;
9135
9160
  try {
@@ -9306,7 +9331,7 @@ async function disconnectClaustrumEnrollment(paths, proposedName) {
9306
9331
  await lock.release();
9307
9332
  }
9308
9333
  }
9309
- var ENROLLMENT_SCHEMA, ENROLLMENT_FILE_MAX_BYTES, ENROLLMENT_LOCK_TTL_MS, TOKEN_RE, TERMINAL_ENROLLMENT_CODES, RETRYABLE_ENROLLMENT_CODES, ClaustrumEnrollmentManager;
9334
+ var ENROLLMENT_SCHEMA, ENROLLMENT_FILE_MAX_BYTES, ENROLLMENT_LOCK_TTL_MS, TOKEN_RE, UNSUPPORTED_ENROLLMENT_CODE, TERMINAL_ENROLLMENT_CODES, RETRYABLE_ENROLLMENT_CODES, ClaustrumEnrollmentManager;
9310
9335
  var init_enrollment = __esm({
9311
9336
  "../core/dist/common-auth-embedded/claustrum/enrollment.js"() {
9312
9337
  "use strict";
@@ -9317,7 +9342,13 @@ var init_enrollment = __esm({
9317
9342
  ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
9318
9343
  ENROLLMENT_LOCK_TTL_MS = 3e4;
9319
9344
  TOKEN_RE = /^[0-9a-f]{64}$/;
9345
+ UNSUPPORTED_ENROLLMENT_CODE = "unknown_method";
9320
9346
  TERMINAL_ENROLLMENT_CODES = /* @__PURE__ */ new Set([
9347
+ // The daemon's answer to an operation it does not implement: a vault built
9348
+ // before the enrollment ceremony. It arrives as a transport Error frame with
9349
+ // no class, which claustrum-client before 0.13.0 labels transient/retry, but
9350
+ // asking again can never succeed.
9351
+ UNSUPPORTED_ENROLLMENT_CODE,
9321
9352
  "invalid_params",
9322
9353
  "pending_exists",
9323
9354
  "not_found",
@@ -9451,6 +9482,18 @@ var init_enrollment = __esm({
9451
9482
  retryCode: refusal3.code
9452
9483
  };
9453
9484
  }
9485
+ if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE) {
9486
+ await lock.assertOwned();
9487
+ await unlink6(this.#paths.statePath).catch((cause) => {
9488
+ if (cause.code !== "ENOENT")
9489
+ throw cause;
9490
+ });
9491
+ return {
9492
+ state: "unavailable",
9493
+ proposedName: state.proposedName,
9494
+ code: refusal3.code
9495
+ };
9496
+ }
9454
9497
  return this.#block(state, refusal3.code);
9455
9498
  }
9456
9499
  }
@@ -11992,7 +12035,7 @@ var init_pi_slot = __esm({
11992
12035
 
11993
12036
  // src/plugin/index.ts
11994
12037
  import { createHash as createHash20, randomUUID as randomUUID20 } from "node:crypto";
11995
- import { join as join31, resolve as resolve19 } from "node:path";
12038
+ import { join as join33, resolve as resolve19 } from "node:path";
11996
12039
 
11997
12040
  // ../core/dist/abort-forwarding.js
11998
12041
  function forwardAbort(source, target) {
@@ -22493,15 +22536,15 @@ async function redactCredentialResponse(response, credentials, bufferedBody, pro
22493
22536
 
22494
22537
  // ../core/dist/pi-paths.js
22495
22538
  import { homedir } from "node:os";
22496
- import { dirname as dirname11, join as join6 } from "node:path";
22539
+ import { dirname as dirname11, join as join7 } from "node:path";
22497
22540
  function getPiConfigDir() {
22498
- return process.env.PI_AGENT_DIR?.trim() || join6(homedir(), ".pi", "agent");
22541
+ return process.env.PI_AGENT_DIR?.trim() || join7(homedir(), ".pi", "agent");
22499
22542
  }
22500
22543
  function getPiAntigravityAuthFile() {
22501
- return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join6(getPiConfigDir(), "antigravity-accounts.json");
22544
+ return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join7(getPiConfigDir(), "antigravity-accounts.json");
22502
22545
  }
22503
22546
  function getPiAntigravityVaultDir() {
22504
- return join6(dirname11(getPiAntigravityAuthFile()), "antigravity-auth-vault");
22547
+ return join7(dirname11(getPiAntigravityAuthFile()), "antigravity-auth-vault");
22505
22548
  }
22506
22549
 
22507
22550
  // ../core/dist/pre-response-deadline.js
@@ -23237,11 +23280,16 @@ function mostConstrainedWindow(windows2) {
23237
23280
  };
23238
23281
  }
23239
23282
  function poolForBucketId(bucketId) {
23240
- if (bucketId.startsWith("gemini-"))
23241
- return "gemini";
23242
- if (bucketId.startsWith("3p-"))
23243
- return "non-gemini";
23244
- return null;
23283
+ switch (bucketId) {
23284
+ case "gemini-5h":
23285
+ case "gemini-weekly":
23286
+ return "gemini";
23287
+ case "3p-5h":
23288
+ case "3p-weekly":
23289
+ return "non-gemini";
23290
+ default:
23291
+ return null;
23292
+ }
23245
23293
  }
23246
23294
  function parseDescriptionModelCount(description) {
23247
23295
  const prefixMatch = description.match(/^[^:]+:\s*/);
@@ -23262,31 +23310,60 @@ function windowDurationMs(window) {
23262
23310
  }
23263
23311
  }
23264
23312
  function aggregateQuotaSummary(response) {
23265
- const groups = {};
23266
- let totalCount = 0;
23313
+ const windowsByPool = {
23314
+ gemini: /* @__PURE__ */ new Map(),
23315
+ "non-gemini": /* @__PURE__ */ new Map()
23316
+ };
23317
+ const modelCounts = {
23318
+ gemini: 0,
23319
+ "non-gemini": 0
23320
+ };
23321
+ const seenBucketIds = /* @__PURE__ */ new Set();
23322
+ const duplicateBucketIds = /* @__PURE__ */ new Set();
23267
23323
  for (const group of response.groups) {
23268
- const windows2 = [];
23324
+ const contributingPools = /* @__PURE__ */ new Set();
23269
23325
  for (const bucket of group.buckets) {
23270
- const pool2 = poolForBucketId(bucket.bucketId);
23271
- if (!pool2)
23326
+ if (bucket.disabled === true)
23327
+ continue;
23328
+ const pool = poolForBucketId(bucket.bucketId);
23329
+ if (!pool)
23272
23330
  continue;
23273
- windows2.push({
23331
+ contributingPools.add(pool);
23332
+ const window = {
23274
23333
  window: bucket.window,
23275
23334
  remainingFraction: normalizeRemainingFraction(bucket.remainingFraction),
23276
23335
  resetTime: bucket.resetTime
23277
- });
23336
+ };
23337
+ const previous = windowsByPool[pool].get(bucket.bucketId);
23338
+ if (seenBucketIds.has(bucket.bucketId)) {
23339
+ duplicateBucketIds.add(bucket.bucketId);
23340
+ } else {
23341
+ seenBucketIds.add(bucket.bucketId);
23342
+ }
23343
+ if (!previous || window.remainingFraction < previous.remainingFraction) {
23344
+ windowsByPool[pool].set(bucket.bucketId, window);
23345
+ }
23278
23346
  }
23347
+ const modelCount = group.description ? parseDescriptionModelCount(group.description) : 0;
23348
+ for (const pool of contributingPools)
23349
+ modelCounts[pool] += modelCount;
23350
+ }
23351
+ if (duplicateBucketIds.size > 0) {
23352
+ log4.debug("duplicate quota summary bucket ids", {
23353
+ bucketIds: [...duplicateBucketIds].sort()
23354
+ });
23355
+ }
23356
+ const groups = {};
23357
+ let totalCount = 0;
23358
+ for (const pool of ["gemini", "non-gemini"]) {
23359
+ const windows2 = [...windowsByPool[pool].values()];
23279
23360
  if (windows2.length === 0)
23280
23361
  continue;
23281
23362
  windows2.sort((a, b) => windowDurationMs(a.window) - windowDurationMs(b.window));
23282
23363
  const constrained = mostConstrainedWindow(windows2);
23283
- const recognizedBucket = group.buckets.find((bucket) => poolForBucketId(bucket.bucketId));
23284
- if (!recognizedBucket)
23364
+ if (!constrained)
23285
23365
  continue;
23286
- const pool = poolForBucketId(recognizedBucket.bucketId);
23287
- if (!pool || !constrained)
23288
- continue;
23289
- const modelCount = group.description ? parseDescriptionModelCount(group.description) : 0;
23366
+ const modelCount = modelCounts[pool];
23290
23367
  groups[pool] = {
23291
23368
  remainingFraction: constrained.remainingFraction,
23292
23369
  resetTime: constrained.resetTime,
@@ -23649,6 +23726,7 @@ function toGeminiSchema(schema, options = {}) {
23649
23726
  }
23650
23727
  const numericConstraintHints = [];
23651
23728
  const inputSchema = mergeSchemaAllOf(schema, numericConstraintHints);
23729
+ const schemaType = typeof inputSchema.type === "string" ? inputSchema.type.toUpperCase() : void 0;
23652
23730
  let result = {};
23653
23731
  const propertyNames = /* @__PURE__ */ new Set();
23654
23732
  if (inputSchema.properties && typeof inputSchema.properties === "object") {
@@ -23657,6 +23735,12 @@ function toGeminiSchema(schema, options = {}) {
23657
23735
  }
23658
23736
  }
23659
23737
  for (const [key, value] of Object.entries(inputSchema)) {
23738
+ if (schemaType !== void 0) {
23739
+ if (key === "items" && schemaType !== "ARRAY")
23740
+ continue;
23741
+ if (schemaType !== "OBJECT" && ["properties", "required", "propertyOrdering"].includes(key))
23742
+ continue;
23743
+ }
23660
23744
  if (options.claudeValidated) {
23661
23745
  if (key === "title")
23662
23746
  continue;
@@ -24976,6 +25060,7 @@ function createAntigravityVaultAccountSource(options) {
24976
25060
  }
24977
25061
 
24978
25062
  // ../core/dist/vault-enrollment-authority.js
25063
+ var UNSUPPORTED_VAULT_CODE = "unknown_method";
24979
25064
  var VAULT_ACCOUNT_REMEDY = "Vault account access is unavailable. Connect accounts in the vault, or disconnect the vault to use local accounts.";
24980
25065
  async function enrollmentAuthority2(paths, proposedName, reader) {
24981
25066
  try {
@@ -25133,7 +25218,7 @@ import {
25133
25218
  writeFileSync
25134
25219
  } from "node:fs";
25135
25220
  import { homedir as homedir3 } from "node:os";
25136
- import { dirname as dirname14, join as join8, resolve as resolve11 } from "node:path";
25221
+ import { dirname as dirname14, join as join10, resolve as resolve11 } from "node:path";
25137
25222
 
25138
25223
  // src/common-auth-embedded/logger/engine.js
25139
25224
  import { appendFileSync as appendFileSync2, chmodSync as chmodSync2, existsSync as existsSync2, renameSync as renameSync2, statSync as statSync3 } from "node:fs";
@@ -25143,7 +25228,8 @@ import { dirname as dirname13, resolve as resolve10 } from "node:path";
25143
25228
  // src/common-auth-embedded/fs/private-files.js
25144
25229
  import { randomUUID as randomUUID13 } from "node:crypto";
25145
25230
  import { lstat as lstat4, readFile as readFile8, rename as rename7, unlink as unlink8 } from "node:fs/promises";
25146
- import { dirname as dirname12, resolve as resolve9 } from "node:path";
25231
+ import { tmpdir as tmpdir2 } from "node:os";
25232
+ import { dirname as dirname12, join as join8, resolve as resolve9 } from "node:path";
25147
25233
  var windowsPrivateFiles2 = process.platform === "win32";
25148
25234
  var migrationNotices2 = /* @__PURE__ */ new Set();
25149
25235
  function ioCode2(detail) {
@@ -25156,8 +25242,32 @@ function ioCode2(detail) {
25156
25242
  return detail?.code ?? "ERR_PRIVATE_FILE";
25157
25243
  }
25158
25244
  var backend2;
25245
+ var PRIVATE_FILES_UNAVAILABLE_REASON2 = "native-addon-unavailable";
25246
+ function privateFilesUnavailable2(cause) {
25247
+ return Object.assign(new Error("Windows private-files native addon is unavailable", { cause }), {
25248
+ code: "ERR_PRIVATE_FILES_UNAVAILABLE",
25249
+ reason: PRIVATE_FILES_UNAVAILABLE_REASON2
25250
+ });
25251
+ }
25252
+ function isUnavailable2(api, error) {
25253
+ return error instanceof api.PrivateFilesUnavailableError || error?.code === "ERR_PRIVATE_FILES_UNAVAILABLE";
25254
+ }
25255
+ async function assertNativeAddonLoads2(api) {
25256
+ try {
25257
+ await api.verifyPrivatePath(join8(tmpdir2(), `.common-auth-private-files-probe-${randomUUID13()}`), "file");
25258
+ } catch (error) {
25259
+ if (isUnavailable2(api, error))
25260
+ throw privateFilesUnavailable2(error);
25261
+ }
25262
+ }
25159
25263
  function loadBackend2() {
25160
- backend2 ??= import("@cortexkit/private-files");
25264
+ backend2 ??= import("@cortexkit/private-files").then(async (api) => {
25265
+ if (windowsPrivateFiles2)
25266
+ await assertNativeAddonLoads2(api);
25267
+ return api;
25268
+ }, (cause) => {
25269
+ throw windowsPrivateFiles2 ? privateFilesUnavailable2(cause) : cause;
25270
+ });
25161
25271
  return backend2;
25162
25272
  }
25163
25273
  var PrivateFileError2 = class extends Error {
@@ -25174,7 +25284,7 @@ var PrivateFileError2 = class extends Error {
25174
25284
  orphanPath;
25175
25285
  constructor(path5, stage, cause) {
25176
25286
  const detail = cause;
25177
- super(`Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`, { cause });
25287
+ super(detail?.code === "ERR_PRIVATE_FILES_UNAVAILABLE" ? `Private file refused at ${stage}: ${path5} (${PRIVATE_FILES_UNAVAILABLE_REASON2}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.` : `Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
25178
25288
  this.path = path5;
25179
25289
  this.stage = stage;
25180
25290
  this.name = "PrivateFileError";
@@ -25790,7 +25900,7 @@ import {
25790
25900
  unlinkSync
25791
25901
  } from "node:fs";
25792
25902
  import { homedir as homedir2 } from "node:os";
25793
- import { join as join7 } from "node:path";
25903
+ import { join as join9 } from "node:path";
25794
25904
  import { env } from "node:process";
25795
25905
 
25796
25906
  // src/plugin/logging-utils.ts
@@ -25922,16 +26032,16 @@ var liveLogFilePaths = /* @__PURE__ */ new Set();
25922
26032
  function getConfigDir() {
25923
26033
  const platform = process.platform;
25924
26034
  if (platform === "win32") {
25925
- return join7(
25926
- env.APPDATA || join7(homedir2(), "AppData", "Roaming"),
26035
+ return join9(
26036
+ env.APPDATA || join9(homedir2(), "AppData", "Roaming"),
25927
26037
  "opencode"
25928
26038
  );
25929
26039
  }
25930
- const xdgConfig2 = env.XDG_CONFIG_HOME || join7(homedir2(), ".config");
25931
- return join7(xdgConfig2, "opencode");
26040
+ const xdgConfig2 = env.XDG_CONFIG_HOME || join9(homedir2(), ".config");
26041
+ return join9(xdgConfig2, "opencode");
25932
26042
  }
25933
26043
  function getLogsDir(customLogDir) {
25934
- const logsDir = customLogDir || join7(getConfigDir(), "antigravity-logs");
26044
+ const logsDir = customLogDir || join9(getConfigDir(), "antigravity-logs");
25935
26045
  try {
25936
26046
  mkdirSync(logsDir, { recursive: true, mode: 448 });
25937
26047
  } catch {
@@ -25942,9 +26052,9 @@ function createLogFilePath(customLogDir) {
25942
26052
  const logsDir = getLogsDir(customLogDir);
25943
26053
  cleanupOldLogs(logsDir, 25);
25944
26054
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
25945
- let candidate = join7(logsDir, `antigravity-debug-${timestamp}.log`);
26055
+ let candidate = join9(logsDir, `antigravity-debug-${timestamp}.log`);
25946
26056
  for (let suffix = 2; liveLogFilePaths.has(candidate); suffix++) {
25947
- candidate = join7(logsDir, `antigravity-debug-${timestamp}-${suffix}.log`);
26057
+ candidate = join9(logsDir, `antigravity-debug-${timestamp}-${suffix}.log`);
25948
26058
  }
25949
26059
  return candidate;
25950
26060
  }
@@ -25952,7 +26062,7 @@ function cleanupOldLogs(logsDir, maxFiles) {
25952
26062
  try {
25953
26063
  const files = readdirSync(logsDir).filter(
25954
26064
  (file) => file.startsWith("antigravity-debug-") && file.endsWith(".log")
25955
- ).map((file) => join7(logsDir, file));
26065
+ ).map((file) => join9(logsDir, file));
25956
26066
  if (files.length <= maxFiles) {
25957
26067
  return;
25958
26068
  }
@@ -26531,7 +26641,7 @@ var GITIGNORE_ENTRIES = [
26531
26641
  "antigravity-logs/"
26532
26642
  ];
26533
26643
  async function ensureGitignore(configDir) {
26534
- const gitignorePath = join8(configDir, ".gitignore");
26644
+ const gitignorePath = join10(configDir, ".gitignore");
26535
26645
  try {
26536
26646
  let content;
26537
26647
  let existingLines = [];
@@ -26577,7 +26687,7 @@ async function ensureGitignore(configDir) {
26577
26687
  }
26578
26688
  }
26579
26689
  function ensureGitignoreSync(configDir) {
26580
- const gitignorePath = join8(configDir, ".gitignore");
26690
+ const gitignorePath = join10(configDir, ".gitignore");
26581
26691
  try {
26582
26692
  let content;
26583
26693
  let existingLines = [];
@@ -26616,8 +26726,8 @@ function ensureGitignoreSync(configDir) {
26616
26726
  }
26617
26727
  }
26618
26728
  function getLegacyWindowsConfigDir() {
26619
- return join8(
26620
- process.env.APPDATA || join8(homedir3(), "AppData", "Roaming"),
26729
+ return join10(
26730
+ process.env.APPDATA || join10(homedir3(), "AppData", "Roaming"),
26621
26731
  "opencode"
26622
26732
  );
26623
26733
  }
@@ -26625,15 +26735,15 @@ function getConfigDir2() {
26625
26735
  if (process.env.OPENCODE_CONFIG_DIR) {
26626
26736
  return process.env.OPENCODE_CONFIG_DIR;
26627
26737
  }
26628
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join8(homedir3(), ".config");
26629
- return join8(xdgConfig2, "opencode");
26738
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join10(homedir3(), ".config");
26739
+ return join10(xdgConfig2, "opencode");
26630
26740
  }
26631
26741
  function migrateLegacyWindowsConfig() {
26632
26742
  if (process.platform !== "win32") {
26633
26743
  return false;
26634
26744
  }
26635
- const newPath = join8(getConfigDir2(), "antigravity-accounts.json");
26636
- const legacyPath = join8(
26745
+ const newPath = join10(getConfigDir2(), "antigravity-accounts.json");
26746
+ const legacyPath = join10(
26637
26747
  getLegacyWindowsConfigDir(),
26638
26748
  "antigravity-accounts.json"
26639
26749
  );
@@ -26668,11 +26778,11 @@ function migrateLegacyWindowsConfig() {
26668
26778
  }
26669
26779
  }
26670
26780
  function getStoragePathWithMigration() {
26671
- const newPath = join8(getConfigDir2(), "antigravity-accounts.json");
26781
+ const newPath = join10(getConfigDir2(), "antigravity-accounts.json");
26672
26782
  if (process.platform === "win32") {
26673
26783
  migrateLegacyWindowsConfig();
26674
26784
  if (!existsSync3(newPath)) {
26675
- const legacyPath = join8(
26785
+ const legacyPath = join10(
26676
26786
  getLegacyWindowsConfigDir(),
26677
26787
  "antigravity-accounts.json"
26678
26788
  );
@@ -27008,7 +27118,7 @@ async function replacePoolLogins(repository, results, options = {}) {
27008
27118
  // src/sidebar-state.ts
27009
27119
  import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync2 } from "node:fs";
27010
27120
  import { homedir as homedir4 } from "node:os";
27011
- import { dirname as dirname15, join as join9 } from "node:path";
27121
+ import { dirname as dirname15, join as join11 } from "node:path";
27012
27122
 
27013
27123
  // ../../node_modules/.bun/xdg-basedir@5.1.0/node_modules/xdg-basedir/index.js
27014
27124
  import os from "os";
@@ -27067,8 +27177,8 @@ async function emitMergeStep(step) {
27067
27177
  function getSidebarStateFile() {
27068
27178
  const override = process.env[SIDEBAR_STATE_ENV];
27069
27179
  if (override && override.trim().length > 0) return override;
27070
- const base = xdgState ?? join9(homedir4(), ".local", "state");
27071
- return join9(base, SIDEBAR_STATE_DIR, SIDEBAR_STATE_FILENAME);
27180
+ const base = xdgState ?? join11(homedir4(), ".local", "state");
27181
+ return join11(base, SIDEBAR_STATE_DIR, SIDEBAR_STATE_FILENAME);
27072
27182
  }
27073
27183
  function readSidebarState(path5 = getSidebarStateFile()) {
27074
27184
  let raw;
@@ -29082,7 +29192,7 @@ async function startOAuthListener({
29082
29192
 
29083
29193
  // src/setup.ts
29084
29194
  import { lstat as lstat5, readFile as readFile13 } from "node:fs/promises";
29085
- import { join as join16, resolve as resolve13 } from "node:path";
29195
+ import { join as join18, resolve as resolve13 } from "node:path";
29086
29196
 
29087
29197
  // src/auth-method-labels.ts
29088
29198
  var OPENCODE2_POOL_AUTH_LABEL = "Google (antigravity-auth pool, browser)";
@@ -29328,7 +29438,7 @@ async function select2(terminal, items, options) {
29328
29438
  import { createHash as createHash10, randomBytes as randomBytes5, randomUUID as randomUUID16 } from "node:crypto";
29329
29439
  import { constants as fsConstants2 } from "node:fs";
29330
29440
  import { chmod as chmod3, mkdir as mkdir12, open as open10, readFile as readFile10, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
29331
- import { basename as basename4, dirname as dirname17, extname as extname2, isAbsolute as isAbsolute3, join as join11, resolve as resolve12 } from "node:path";
29441
+ import { basename as basename4, dirname as dirname17, extname as extname2, isAbsolute as isAbsolute3, join as join13, resolve as resolve12 } from "node:path";
29332
29442
  import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
29333
29443
 
29334
29444
  // src/common-auth-embedded/fs/lock-constants.js
@@ -29350,7 +29460,7 @@ var WRITER_LOCK_CONSTANTS2 = Object.freeze({
29350
29460
  // src/common-auth-embedded/fs/refresh-file-lock.js
29351
29461
  import { randomUUID as randomUUID15 } from "node:crypto";
29352
29462
  import { mkdir as mkdir11, open as open9, readFile as readFile9, rename as rename8, rm as rm5, stat as stat6 } from "node:fs/promises";
29353
- import { dirname as dirname16, join as join10 } from "node:path";
29463
+ import { dirname as dirname16, join as join12 } from "node:path";
29354
29464
 
29355
29465
  // src/common-auth-embedded/fs/with-lock.js
29356
29466
  function lockPathFor2(target, name) {
@@ -29385,7 +29495,7 @@ function acquireRefreshFileLock2(options) {
29385
29495
  }
29386
29496
  async function acquireRefreshFileLockWithClock2(options) {
29387
29497
  const lockPath = lockPathFor2(options.path, options.name);
29388
- const legacyOwnerPath = join10(lockPath, "owner.json");
29498
+ const legacyOwnerPath = join12(lockPath, "owner.json");
29389
29499
  const ownerId = randomUUID15();
29390
29500
  const now = options.now ?? Date.now;
29391
29501
  let renewTimer = null;
@@ -29428,7 +29538,7 @@ async function acquireRefreshFileLockWithClock2(options) {
29428
29538
  let terminalIOError;
29429
29539
  let renewalInFlight = null;
29430
29540
  const evictPath = `${lockPath}.evicting`;
29431
- const evictOwnerPath = join10(evictPath, "owner.json");
29541
+ const evictOwnerPath = join12(evictPath, "owner.json");
29432
29542
  const evictOwnerId = randomUUID15();
29433
29543
  const EVICT_TTL = 5e3;
29434
29544
  const MAX_STEAL_ATTEMPTS = 8;
@@ -29999,7 +30109,13 @@ var ENROLLMENT_SCHEMA2 = 1;
29999
30109
  var ENROLLMENT_FILE_MAX_BYTES2 = 16 * 1024;
30000
30110
  var ENROLLMENT_LOCK_TTL_MS2 = 3e4;
30001
30111
  var TOKEN_RE2 = /^[0-9a-f]{64}$/;
30112
+ var UNSUPPORTED_ENROLLMENT_CODE2 = "unknown_method";
30002
30113
  var TERMINAL_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
30114
+ // The daemon's answer to an operation it does not implement: a vault built
30115
+ // before the enrollment ceremony. It arrives as a transport Error frame with
30116
+ // no class, which claustrum-client before 0.13.0 labels transient/retry, but
30117
+ // asking again can never succeed.
30118
+ UNSUPPORTED_ENROLLMENT_CODE2,
30003
30119
  "invalid_params",
30004
30120
  "pending_exists",
30005
30121
  "not_found",
@@ -30029,7 +30145,7 @@ function getClaustrumEnrollmentPaths2(tokenPath) {
30029
30145
  const extension = extname2(tokenPath) || ".json";
30030
30146
  const stem = basename4(tokenPath, extname2(tokenPath));
30031
30147
  return {
30032
- statePath: join11(dirname17(tokenPath), `${stem}-state${extension}`),
30148
+ statePath: join13(dirname17(tokenPath), `${stem}-state${extension}`),
30033
30149
  tokenPath
30034
30150
  };
30035
30151
  }
@@ -30037,7 +30153,7 @@ function hostEnrollmentPaths2(input2) {
30037
30153
  const override = input2.override?.trim();
30038
30154
  if (override && !isAbsolute3(override) && !input2.cwd)
30039
30155
  throw new ClaustrumConsumerError2("invalid-state", "A relative Claustrum enrollment override needs a base directory");
30040
- const tokenPath = override ? isAbsolute3(override) ? override : resolve12(input2.cwd, override) : join11(input2.stateDir, `${input2.host}-enrollment.json`);
30156
+ const tokenPath = override ? isAbsolute3(override) ? override : resolve12(input2.cwd, override) : join13(input2.stateDir, `${input2.host}-enrollment.json`);
30041
30157
  return getClaustrumEnrollmentPaths2(tokenPath);
30042
30158
  }
30043
30159
  function isRecord10(value) {
@@ -30270,7 +30386,7 @@ async function writeStateAtomic2(path5, state, ancestorOptions = {}) {
30270
30386
  }
30271
30387
  if (windowsPrivateFiles2)
30272
30388
  return writePrivateAtomic2(path5, bytes);
30273
- const temporary = join11(parent, `.${basename4(path5)}.${process.pid}.${randomUUID16()}.tmp`);
30389
+ const temporary = join13(parent, `.${basename4(path5)}.${process.pid}.${randomUUID16()}.tmp`);
30274
30390
  let descriptor;
30275
30391
  let created = false;
30276
30392
  try {
@@ -30494,6 +30610,18 @@ var ClaustrumEnrollmentManager2 = class {
30494
30610
  retryCode: refusal3.code
30495
30611
  };
30496
30612
  }
30613
+ if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE2) {
30614
+ await lock.assertOwned();
30615
+ await unlink9(this.#paths.statePath).catch((cause) => {
30616
+ if (cause.code !== "ENOENT")
30617
+ throw cause;
30618
+ });
30619
+ return {
30620
+ state: "unavailable",
30621
+ proposedName: state.proposedName,
30622
+ code: refusal3.code
30623
+ };
30624
+ }
30497
30625
  return this.#block(state, refusal3.code);
30498
30626
  }
30499
30627
  }
@@ -30771,8 +30899,8 @@ function recordSetupEnrollment(failure2, enrollment) {
30771
30899
  // src/common-auth-embedded/setup/detect.js
30772
30900
  import { accessSync, constants as constants3, existsSync as existsSync5, readFileSync as readFileSync4, realpathSync, statSync as statSync5 } from "node:fs";
30773
30901
  import { mkdtemp, rm as rm6 } from "node:fs/promises";
30774
- import { tmpdir } from "node:os";
30775
- import { join as join12 } from "node:path";
30902
+ import { tmpdir as tmpdir3 } from "node:os";
30903
+ import { join as join14 } from "node:path";
30776
30904
  import { parse } from "jsonc-parser";
30777
30905
 
30778
30906
  // src/common-auth-embedded/setup/paths.js
@@ -30943,7 +31071,7 @@ async function detectHosts(plugin, io = {}) {
30943
31071
  return null;
30944
31072
  let root;
30945
31073
  try {
30946
- root = await mkdtemp(join12(tmpdir(), "common-auth-setup-version-"));
31074
+ root = await mkdtemp(join14(tmpdir3(), "common-auth-setup-version-"));
30947
31075
  const probeEnv = {
30948
31076
  ...env3,
30949
31077
  HOME: root,
@@ -31012,6 +31140,8 @@ import { writeEnrollmentTokenFile as writeEnrollmentTokenFile3 } from "@cortexki
31012
31140
  var WINDOWS_CIM_TIMEOUT_MS = 45e3;
31013
31141
  var HOSTS = /* @__PURE__ */ new Set(["opencode", "litecode", "opencode2", "pi"]);
31014
31142
  var RUNTIMES = /* @__PURE__ */ new Set(["node", "bun"]);
31143
+ var WINDOWS_FENCE_FILTER = [...HOSTS, ...RUNTIMES].map((name) => `Name LIKE '${name}%'`).join(" OR ");
31144
+ var WINDOWS_FENCE_QUERY = `$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${WINDOWS_FENCE_FILTER}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`;
31015
31145
  var PI_SCRIPT_PATTERN = /(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;
31016
31146
  function commandArguments(command) {
31017
31147
  return [...command.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2] ?? "");
@@ -31151,6 +31281,29 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
31151
31281
  }
31152
31282
  };
31153
31283
  try {
31284
+ if (windows2 && options.hostImagesOnly) {
31285
+ const details = await inspect("CIM", "powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_FENCE_QUERY], WINDOWS_CIM_TIMEOUT_MS);
31286
+ if (details.exitCode !== 0)
31287
+ throw new ProcessInspectionError(inspection);
31288
+ const value = JSON.parse(details.stdout);
31289
+ if (!value || typeof value !== "object" || !("complete" in value) || value.complete !== true || !("processes" in value))
31290
+ throw new ProcessInspectionError(inspection);
31291
+ const listed = value.processes;
31292
+ const rows = listed === null ? [] : Array.isArray(listed) ? listed : [listed];
31293
+ const processes2 = [];
31294
+ for (const row of rows) {
31295
+ if (!row || typeof row !== "object" || !("Name" in row) || typeof row.Name !== "string" || !("ProcessId" in row) || !Number.isSafeInteger(row.ProcessId) || row.ProcessId < 0 || !("CommandLine" in row))
31296
+ throw new ProcessInspectionError(inspection);
31297
+ const pid = row.ProcessId;
31298
+ if (!/^(?:node|bun)\.exe$/i.test(row.Name))
31299
+ processes2.push({ pid, command: row.Name });
31300
+ else if (typeof row.CommandLine === "string")
31301
+ processes2.push({ pid, command: row.CommandLine });
31302
+ else if (pid !== selfPid)
31303
+ throw new ProcessInspectionError(inspection);
31304
+ }
31305
+ return processes2;
31306
+ }
31154
31307
  const result = await inspect(windows2 ? "tasklist" : "ps", windows2 ? "tasklist.exe" : "ps", windows2 ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
31155
31308
  if (result.exitCode !== 0)
31156
31309
  throw new ProcessInspectionError(inspection);
@@ -31220,7 +31373,11 @@ function createProcessFence(runner = defaultCommandRunner, options = {}) {
31220
31373
  const isHost = (entry) => entry.pid !== selfPid && hostName(entry.command) !== null;
31221
31374
  return {
31222
31375
  async listRunningHosts(env3) {
31223
- return (await listSetupProcesses(runner, { ...options, env: env3 })).filter(isHost);
31376
+ return (await listSetupProcesses(runner, {
31377
+ ...options,
31378
+ env: env3,
31379
+ hostImagesOnly: true
31380
+ })).filter(isHost);
31224
31381
  },
31225
31382
  async previewRunningHosts(env3) {
31226
31383
  const processes = await listSetupProcesses(runner, {
@@ -31244,8 +31401,27 @@ async function assertHostsStopped(fence, env3) {
31244
31401
 
31245
31402
  // src/common-auth-embedded/setup/enroll.js
31246
31403
  var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
31404
+ var UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault does not support connecting plugins yet, so setup cannot connect to it. Run setup without --claustrum to use local accounts.";
31405
+ var ENROLLMENT_WAIT_MS = 3e5;
31406
+ var APPROVAL_POLL_MS = 1e3;
31407
+ var PROPOSE_BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
31408
+ function safeCode(code2) {
31409
+ return code2 && /^[a-z][a-z0-9_]{0,63}$/.test(code2) ? code2 : "unknown";
31410
+ }
31247
31411
  var HostNotEnrolledError = class extends Error {
31412
+ reason;
31413
+ lastErrorCode;
31414
+ constructor(message, details) {
31415
+ super(message);
31416
+ this.name = "HostNotEnrolledError";
31417
+ this.reason = details.reason;
31418
+ if (details.lastErrorCode !== void 0)
31419
+ this.lastErrorCode = safeCode(details.lastErrorCode);
31420
+ }
31248
31421
  };
31422
+ function approveCommand(requestId, name) {
31423
+ return `ck auth enroll approve --request-id ${requestId} --name ${name}`;
31424
+ }
31249
31425
  async function connectSetupHost(plugin, host, io, terminal, fence) {
31250
31426
  const { name, paths: input2 } = plugin.vault.hosts[host];
31251
31427
  const paths = hostEnrollmentPaths2(input2);
@@ -31254,54 +31430,94 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
31254
31430
  connectionFile: plugin.vault.connectionFile,
31255
31431
  handshakeTimeoutMs: 2e3
31256
31432
  }).catch(() => {
31257
- throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.");
31433
+ throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.", { reason: "connection-failed" });
31258
31434
  });
31435
+ const now = io.now ?? (() => performance.now());
31436
+ const wait2 = io.wait ?? delay;
31259
31437
  try {
31260
31438
  const manager = new ClaustrumEnrollmentManager2({
31261
31439
  proposedName: name,
31262
31440
  paths,
31263
- client: {
31264
- enrollPropose: async (input3) => {
31265
- await fence();
31266
- return client.enrollPropose(input3);
31267
- },
31268
- enrollPoll: async (input3) => {
31269
- await fence();
31270
- return client.enrollPoll(input3);
31271
- }
31272
- },
31441
+ // Each tick of the wait below checks the fence once, just before
31442
+ // reconcile proposes or polls. Checking again inside every vault call
31443
+ // doubled the process listings per tick, and on Windows each listing
31444
+ // starts PowerShell.
31445
+ client,
31273
31446
  writeTokenFile: async (path5, file) => {
31274
31447
  await fence();
31275
31448
  await writeEnrollmentTokenFile3(path5, file);
31276
31449
  }
31277
31450
  });
31451
+ printLine2(terminal, `Asking the vault to connect ${name}\u2026`);
31452
+ const deadline = now() + ENROLLMENT_WAIT_MS;
31278
31453
  let printedRequest;
31279
- for (let tick = 0; tick < 300; tick++) {
31454
+ let lastCode;
31455
+ let reportedCode;
31456
+ let failedProposals = 0;
31457
+ for (; ; ) {
31280
31458
  await fence();
31281
31459
  const status = await manager.reconcile();
31282
31460
  if (status.state === "approved") {
31283
31461
  printLine2(terminal, `Connected ${host} to Claustrum.`);
31284
31462
  return;
31285
31463
  }
31464
+ if (status.state === "unavailable" && status.code === UNSUPPORTED_ENROLLMENT_CODE2)
31465
+ throw new HostNotEnrolledError(UNSUPPORTED_VAULT_MESSAGE, {
31466
+ reason: "unsupported-vault",
31467
+ lastErrorCode: status.code
31468
+ });
31286
31469
  if (status.state !== "pending" && status.state !== "busy")
31287
- throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
31288
- if (status.state === "pending" && status.requestId && status.requestId !== printedRequest) {
31289
- if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
31290
- throw new HostNotEnrolledError("Invalid enrollment request id.");
31291
- printedRequest = status.requestId;
31292
- printLine2(terminal, "Waiting for approval. In another terminal, run:");
31293
- printLine2(terminal, ` ck auth enroll approve --request-id ${status.requestId} --name ${name}`);
31294
- printLine2(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
31295
- }
31296
- await (io.wait ?? delay)(1e3);
31297
- }
31298
- throw new HostNotEnrolledError("Claustrum approval is still pending; approve with ck and rerun setup.");
31470
+ throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.", {
31471
+ reason: "refused",
31472
+ ..."code" in status && { lastErrorCode: status.code }
31473
+ });
31474
+ let pause = APPROVAL_POLL_MS;
31475
+ if (status.state === "busy")
31476
+ lastCode = "busy";
31477
+ else if (status.retryCode)
31478
+ lastCode = status.retryCode;
31479
+ if (status.state === "pending" && status.requestId) {
31480
+ failedProposals = 0;
31481
+ if (status.requestId !== printedRequest) {
31482
+ if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
31483
+ throw new HostNotEnrolledError("Invalid enrollment request id.", {
31484
+ reason: "invalid-request"
31485
+ });
31486
+ printedRequest = status.requestId;
31487
+ printLine2(terminal, "Waiting for approval. In another terminal, run:");
31488
+ printLine2(terminal, ` ${approveCommand(status.requestId, name)}`);
31489
+ printLine2(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
31490
+ }
31491
+ } else if (status.state === "pending" && status.retryCode) {
31492
+ pause = PROPOSE_BACKOFF_MS[Math.min(failedProposals, PROPOSE_BACKOFF_MS.length - 1)] ?? APPROVAL_POLL_MS;
31493
+ failedProposals++;
31494
+ const code3 = safeCode(status.retryCode);
31495
+ if (code3 !== reportedCode) {
31496
+ reportedCode = code3;
31497
+ printLine2(terminal, `The vault has not created the request yet (${code3}); retrying.`);
31498
+ }
31499
+ }
31500
+ const remaining = deadline - now();
31501
+ if (remaining <= 0)
31502
+ break;
31503
+ await wait2(Math.min(pause, remaining));
31504
+ }
31505
+ if (printedRequest)
31506
+ throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
31507
+ reason: "approval-pending",
31508
+ ...lastCode !== void 0 && { lastErrorCode: lastCode }
31509
+ });
31510
+ const code2 = safeCode(lastCode);
31511
+ throw new HostNotEnrolledError(`The vault never created the enrollment request (last error: ${code2}). Check that ck is running, then rerun setup.`, { reason: "request-not-created", lastErrorCode: code2 });
31299
31512
  } catch (error) {
31300
- if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError)
31513
+ if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError || // Built above from fixed text and vetted values only.
31514
+ error instanceof HostNotEnrolledError)
31301
31515
  throw error;
31302
- if (error instanceof HostNotEnrolledError)
31303
- throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE);
31304
- throw new Error(ENROLLMENT_INCOMPLETE_MESSAGE);
31516
+ const code2 = error?.code;
31517
+ throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE, {
31518
+ reason: "incomplete",
31519
+ ...typeof code2 === "string" && { lastErrorCode: code2 }
31520
+ });
31305
31521
  } finally {
31306
31522
  client.close();
31307
31523
  }
@@ -31339,7 +31555,7 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
31339
31555
  // src/common-auth-embedded/setup/config-write.js
31340
31556
  import { randomUUID as randomUUID17 } from "node:crypto";
31341
31557
  import { mkdir as mkdir13, open as open11, rename as rename10, stat as stat9, unlink as unlink10 } from "node:fs/promises";
31342
- import { basename as basename5, dirname as dirname18, join as join13 } from "node:path";
31558
+ import { basename as basename5, dirname as dirname18, join as join15 } from "node:path";
31343
31559
  import { setTimeout as delay2 } from "node:timers/promises";
31344
31560
  async function writeHostConfigAtomic(file, content, options = {}) {
31345
31561
  const windows2 = (options.platform ?? process.platform) === "win32";
@@ -31354,7 +31570,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
31354
31570
  throw error;
31355
31571
  }
31356
31572
  }
31357
- const stage = join13(parent, `.${basename5(file)}.${(options.stageName ?? randomUUID17)()}.tmp`);
31573
+ const stage = join15(parent, `.${basename5(file)}.${(options.stageName ?? randomUUID17)()}.tmp`);
31358
31574
  let created = false;
31359
31575
  try {
31360
31576
  const handle = await open11(stage, "wx", mode ?? 438);
@@ -31721,11 +31937,11 @@ ${write.content}`);
31721
31937
  // src/plugin/vault-activation.ts
31722
31938
  import { readFile as readFile11 } from "node:fs/promises";
31723
31939
  import { homedir as homedir6 } from "node:os";
31724
- import { join as join14 } from "node:path";
31940
+ import { join as join16 } from "node:path";
31725
31941
  var V1_VAULT_ACTIVATION_LABEL = "Activate approved Antigravity vault";
31726
31942
  function nativeOpenCodeAuthPath(env3 = process.env, home = homedir6()) {
31727
- return join14(
31728
- env3.XDG_DATA_HOME || join14(home, ".local", "share"),
31943
+ return join16(
31944
+ env3.XDG_DATA_HOME || join16(home, ".local", "share"),
31729
31945
  "opencode",
31730
31946
  "auth.json"
31731
31947
  );
@@ -31772,7 +31988,7 @@ function createV1VaultActivationMethod(input2) {
31772
31988
 
31773
31989
  // src/plugin/vault-custody.ts
31774
31990
  import { chmod as chmod4, mkdir as mkdir14, readFile as readFile12 } from "node:fs/promises";
31775
- import { dirname as dirname19, join as join15 } from "node:path";
31991
+ import { dirname as dirname19, join as join17 } from "node:path";
31776
31992
 
31777
31993
  // src/plugin/shared/vault-request-credentials.ts
31778
31994
  function vaultAccountRows(routes) {
@@ -32233,12 +32449,12 @@ var OPENCODE_VAULT_HOST = "opencode";
32233
32449
  var OPENCODE_VAULT_ENROLLMENT_NAME = getAntigravityVaultEnrollmentName(OPENCODE_VAULT_HOST);
32234
32450
  var OPENCODE_VAULT_DIR_NAME = "antigravity-auth-vault";
32235
32451
  function openCodeVaultPaths(accountFile) {
32236
- const dir = join15(dirname19(accountFile), OPENCODE_VAULT_DIR_NAME);
32452
+ const dir = join17(dirname19(accountFile), OPENCODE_VAULT_DIR_NAME);
32237
32453
  return {
32238
32454
  dir,
32239
- modeFile: join15(dir, "opencode-mode.json"),
32240
- rosterFile: join15(dir, "opencode-roster.json"),
32241
- stateFile: join15(dir, "opencode-state.json")
32455
+ modeFile: join17(dir, "opencode-mode.json"),
32456
+ rosterFile: join17(dir, "opencode-roster.json"),
32457
+ stateFile: join17(dir, "opencode-state.json")
32242
32458
  };
32243
32459
  }
32244
32460
  async function ensureVaultDir(dir) {
@@ -32586,6 +32802,9 @@ async function refusalOr(step) {
32586
32802
  }
32587
32803
  return "Done. Start a new request to use the change.";
32588
32804
  }
32805
+ function isUnsupportedEnrollment(status) {
32806
+ return status.state === "unavailable" && status.code === UNSUPPORTED_VAULT_CODE;
32807
+ }
32589
32808
  function describeEnrollment(status) {
32590
32809
  switch (status.state) {
32591
32810
  case "idle":
@@ -32599,7 +32818,7 @@ function describeEnrollment(status) {
32599
32818
  case "blocked":
32600
32819
  return `blocked (${status.code})`;
32601
32820
  case "unavailable":
32602
- return `vault unavailable (${status.code})`;
32821
+ return isUnsupportedEnrollment(status) ? "this vault can't connect plugins yet" : `vault unavailable (${status.code})`;
32603
32822
  case "busy":
32604
32823
  return "another setup step is running";
32605
32824
  }
@@ -32666,10 +32885,15 @@ function enrollmentGuidance(status) {
32666
32885
  return [
32667
32886
  "Resolve the enrollment problem with the vault operator, then request vault access again."
32668
32887
  ];
32669
- if (status.state === "unavailable")
32888
+ if (status.state === "unavailable") {
32889
+ if (isUnsupportedEnrollment(status))
32890
+ return [
32891
+ "This Claustrum vault is too old to connect plugins. Ask the vault operator to update Claustrum, or keep using your local accounts."
32892
+ ];
32670
32893
  return [
32671
32894
  "Check that the vault is running and its connection file is available, then request vault access again."
32672
32895
  ];
32896
+ }
32673
32897
  if (status.state === "busy")
32674
32898
  return [
32675
32899
  "Another enrollment operation is running. OpenCode will keep checking its outcome in the background."
@@ -32702,7 +32926,7 @@ function statusLines(status) {
32702
32926
  // src/setup.ts
32703
32927
  var PI_PLACEHOLDER_KEY = "antigravity-vault-custody";
32704
32928
  function nativeAuthPath(host, context) {
32705
- return host === "opencode" ? nativeOpenCodeAuthPath() : join16(context.piAgentDir, "auth.json");
32929
+ return host === "opencode" ? nativeOpenCodeAuthPath() : join18(context.piAgentDir, "auth.json");
32706
32930
  }
32707
32931
  function provider(host) {
32708
32932
  return host === "opencode" ? OPENCODE_VAULT_PROVIDER : ANTIGRAVITY_PROVIDER_ID;
@@ -32823,7 +33047,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
32823
33047
  const { openPiSlot: openPiSlot2 } = await loadCommonAuthPiSlot();
32824
33048
  if ((await openPiSlot2({
32825
33049
  authPath: nativeAuthPath(host, context),
32826
- stashPath: join16(piDir, "google-login-stash.json"),
33050
+ stashPath: join18(piDir, "google-login-stash.json"),
32827
33051
  provider: ANTIGRAVITY_PROVIDER_ID,
32828
33052
  placeholderKey: PI_PLACEHOLDER_KEY
32829
33053
  }).inspect()).slot === "placeholder")
@@ -32860,7 +33084,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
32860
33084
  const { openPiSlot: openPiSlot2 } = await loadCommonAuthPiSlot();
32861
33085
  const inspection = await openPiSlot2({
32862
33086
  authPath: nativeAuthPath("pi", context),
32863
- stashPath: join16(piDir, "google-login-stash.json"),
33087
+ stashPath: join18(piDir, "google-login-stash.json"),
32864
33088
  provider: ANTIGRAVITY_PROVIDER_ID,
32865
33089
  placeholderKey: PI_PLACEHOLDER_KEY
32866
33090
  }).inspect();
@@ -32979,7 +33203,7 @@ Setup has not completed the OpenCode 2 native Google connection.
32979
33203
  await assertSetupHostsStopped();
32980
33204
  await openPiSlot2({
32981
33205
  authPath: nativeAuthPath(host, context),
32982
- stashPath: join16(piDir, "google-login-stash.json"),
33206
+ stashPath: join18(piDir, "google-login-stash.json"),
32983
33207
  provider: ANTIGRAVITY_PROVIDER_ID,
32984
33208
  placeholderKey: PI_PLACEHOLDER_KEY
32985
33209
  }).enterVault();
@@ -33999,8 +34223,8 @@ function isTuiConnected(sessionId) {
33999
34223
 
34000
34224
  // src/rpc/rpc-dir.ts
34001
34225
  import { createHash as createHash11 } from "node:crypto";
34002
- import { homedir as homedir8, tmpdir as tmpdir2 } from "node:os";
34003
- import { isAbsolute as isAbsolute4, join as join20, resolve as resolve15 } from "node:path";
34226
+ import { homedir as homedir8, tmpdir as tmpdir4 } from "node:os";
34227
+ import { isAbsolute as isAbsolute4, join as join22, resolve as resolve15 } from "node:path";
34004
34228
  var RPC_DIR_ENV = "ANTIGRAVITY_AUTH_RPC_DIR";
34005
34229
  function getRpcDir(projectDirectory) {
34006
34230
  const override = process.env[RPC_DIR_ENV]?.trim();
@@ -34008,8 +34232,8 @@ function getRpcDir(projectDirectory) {
34008
34232
  return isAbsolute4(override) ? override : resolve15(projectDirectory, override);
34009
34233
  }
34010
34234
  const projectHash = createHash11("sha256").update(resolve15(projectDirectory)).digest("hex").slice(0, 16);
34011
- const stateHome = process.env.XDG_STATE_HOME ?? join20(homedir8(), ".local", "state");
34012
- return join20(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
34235
+ const stateHome = process.env.XDG_STATE_HOME ?? join22(homedir8(), ".local", "state");
34236
+ return join22(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
34013
34237
  }
34014
34238
 
34015
34239
  // src/common-auth-embedded/rpc/notifications.js
@@ -34020,7 +34244,7 @@ function isSessionId(value) {
34020
34244
  // src/common-auth-embedded/rpc/port-file.js
34021
34245
  import { createHash as createHash12, randomUUID as randomUUID18 } from "node:crypto";
34022
34246
  import { chmod as chmod5, mkdir as mkdir15, open as open12, readdir, rename as rename11, rmdir as rmdir2, stat as stat10, unlink as unlink11 } from "node:fs/promises";
34023
- import { join as join21, resolve as resolve16 } from "node:path";
34247
+ import { join as join23, resolve as resolve16 } from "node:path";
34024
34248
  function isProbeablePid(pid) {
34025
34249
  return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0;
34026
34250
  }
@@ -34051,7 +34275,7 @@ async function removeCorruptPortFile(portFile, log16) {
34051
34275
  }
34052
34276
  async function writePortFile(dir, entry, options = {}) {
34053
34277
  const writeOnce = async () => {
34054
- const target = join21(dir, `port-${entry.pid}.json`);
34278
+ const target = join23(dir, `port-${entry.pid}.json`);
34055
34279
  if (windowsPrivateFiles2) {
34056
34280
  await ensurePrivateDirectory3(dir, options.secureDir ?? false);
34057
34281
  await options.beforeWrite?.();
@@ -34112,7 +34336,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
34112
34336
  if (!projectDir.isDirectory() || !isManagedDir(projectDir.name)) {
34113
34337
  continue;
34114
34338
  }
34115
- const dir = join21(root, projectDir.name);
34339
+ const dir = join23(root, projectDir.name);
34116
34340
  let names;
34117
34341
  try {
34118
34342
  names = await readdir(dir);
@@ -34124,7 +34348,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
34124
34348
  for (const name of names) {
34125
34349
  if (!name.startsWith("port-") || !name.endsWith(".json"))
34126
34350
  continue;
34127
- const portFile = join21(dir, name);
34351
+ const portFile = join23(dir, name);
34128
34352
  let raw;
34129
34353
  try {
34130
34354
  raw = await readPrivateText2(portFile);
@@ -34161,7 +34385,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
34161
34385
  import { randomBytes as randomBytes6, timingSafeEqual } from "node:crypto";
34162
34386
  import { unlink as unlink12 } from "node:fs/promises";
34163
34387
  import { createServer as createServer2 } from "node:http";
34164
- import { join as join22 } from "node:path";
34388
+ import { join as join24 } from "node:path";
34165
34389
  var RpcRequestError = class extends Error {
34166
34390
  status;
34167
34391
  constructor(status, message) {
@@ -34413,7 +34637,7 @@ async function startRpcServer(options) {
34413
34637
  for (const socket of connections)
34414
34638
  socket.destroy();
34415
34639
  });
34416
- const portFile = join22(options.dir, `port-${process.pid}.json`);
34640
+ const portFile = join24(options.dir, `port-${process.pid}.json`);
34417
34641
  const current = await readPrivateText2(portFile).then((raw) => JSON.parse(raw)).catch((error) => {
34418
34642
  if (error instanceof PrivateFileError2 && error.code !== "ENOENT")
34419
34643
  throw error;
@@ -35475,7 +35699,7 @@ import { createInterface as createInterface2 } from "node:readline/promises";
35475
35699
  // src/plugin/config/updater.ts
35476
35700
  import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync4 } from "node:fs";
35477
35701
  import { homedir as homedir9 } from "node:os";
35478
- import { dirname as dirname21, join as join23 } from "node:path";
35702
+ import { dirname as dirname21, join as join25 } from "node:path";
35479
35703
  var PLUGIN_NAME = "@cortexkit/opencode-antigravity-auth@latest";
35480
35704
  var SCHEMA_URL = "https://opencode.ai/config.json";
35481
35705
  var OPENCODE_JSON_FILENAME = "opencode.json";
@@ -35487,13 +35711,13 @@ function stripJsonCommentsAndTrailingCommas(json) {
35487
35711
  ).replace(/,(\s*[}\]])/g, "$1");
35488
35712
  }
35489
35713
  function getOpencodeConfigDir() {
35490
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join23(homedir9(), ".config");
35491
- return join23(xdgConfig2, "opencode");
35714
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join25(homedir9(), ".config");
35715
+ return join25(xdgConfig2, "opencode");
35492
35716
  }
35493
35717
  function getOpencodeConfigPath() {
35494
35718
  const configDir = getOpencodeConfigDir();
35495
- const jsoncPath = join23(configDir, OPENCODE_JSONC_FILENAME);
35496
- const jsonPath = join23(configDir, OPENCODE_JSON_FILENAME);
35719
+ const jsoncPath = join25(configDir, OPENCODE_JSONC_FILENAME);
35720
+ const jsonPath = join25(configDir, OPENCODE_JSON_FILENAME);
35497
35721
  if (existsSync8(jsoncPath)) {
35498
35722
  return jsoncPath;
35499
35723
  }
@@ -38214,21 +38438,21 @@ import {
38214
38438
  unlinkSync as unlinkSync3,
38215
38439
  writeFileSync as writeFileSync5
38216
38440
  } from "node:fs";
38217
- import { homedir as homedir10, tmpdir as tmpdir3 } from "node:os";
38218
- import { dirname as dirname22, join as join24 } from "node:path";
38441
+ import { homedir as homedir10, tmpdir as tmpdir5 } from "node:os";
38442
+ import { dirname as dirname22, join as join26 } from "node:path";
38219
38443
  function getConfigDir3() {
38220
38444
  const platform = process.platform;
38221
38445
  if (platform === "win32") {
38222
- return join24(
38223
- process.env.APPDATA || join24(homedir10(), "AppData", "Roaming"),
38446
+ return join26(
38447
+ process.env.APPDATA || join26(homedir10(), "AppData", "Roaming"),
38224
38448
  "opencode"
38225
38449
  );
38226
38450
  }
38227
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join24(homedir10(), ".config");
38228
- return join24(xdgConfig2, "opencode");
38451
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join26(homedir10(), ".config");
38452
+ return join26(xdgConfig2, "opencode");
38229
38453
  }
38230
38454
  function getSignatureCacheFilePath() {
38231
- return join24(getConfigDir3(), "antigravity-signature-cache.json");
38455
+ return join26(getConfigDir3(), "antigravity-signature-cache.json");
38232
38456
  }
38233
38457
  var SignatureCache = class {
38234
38458
  // In-memory cache: key -> entry with signature and optional thinking text
@@ -38511,8 +38735,8 @@ var SignatureCache = class {
38511
38735
  last_write: now
38512
38736
  }
38513
38737
  };
38514
- const tmpPath = join24(
38515
- tmpdir3(),
38738
+ const tmpPath = join26(
38739
+ tmpdir5(),
38516
38740
  `antigravity-cache-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`
38517
38741
  );
38518
38742
  writeFileSync5(tmpPath, JSON.stringify(cacheData, null, 2), "utf-8");
@@ -38579,7 +38803,7 @@ var SignatureCache = class {
38579
38803
  // src/plugin/config/loader.ts
38580
38804
  import { existsSync as existsSync10, readFileSync as readFileSync10, realpathSync as realpathSync3 } from "node:fs";
38581
38805
  import { homedir as homedir11 } from "node:os";
38582
- import { basename as basename6, dirname as dirname23, join as join25, resolve as resolve17 } from "node:path";
38806
+ import { basename as basename6, dirname as dirname23, join as join27, resolve as resolve17 } from "node:path";
38583
38807
 
38584
38808
  // src/plugin/config/schema.ts
38585
38809
  import { z } from "zod";
@@ -39074,14 +39298,14 @@ function getConfigDir4() {
39074
39298
  if (process.env.OPENCODE_CONFIG_DIR) {
39075
39299
  return process.env.OPENCODE_CONFIG_DIR;
39076
39300
  }
39077
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join25(homedir11(), ".config");
39078
- return join25(xdgConfig2, "opencode");
39301
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join27(homedir11(), ".config");
39302
+ return join27(xdgConfig2, "opencode");
39079
39303
  }
39080
39304
  function getUserConfigPath() {
39081
- return join25(getConfigDir4(), "antigravity.json");
39305
+ return join27(getConfigDir4(), "antigravity.json");
39082
39306
  }
39083
39307
  function getProjectConfigPath(directory) {
39084
- return join25(directory, ".opencode", "antigravity.json");
39308
+ return join27(directory, ".opencode", "antigravity.json");
39085
39309
  }
39086
39310
  function loadConfigFile(path5, log16) {
39087
39311
  try {
@@ -39142,7 +39366,7 @@ function canonicalizeOwnedPath(path5) {
39142
39366
  let current = absolute;
39143
39367
  for (; ; ) {
39144
39368
  try {
39145
- return join25(realpathSync3(current), ...missing.reverse());
39369
+ return join27(realpathSync3(current), ...missing.reverse());
39146
39370
  } catch {
39147
39371
  const parent = dirname23(current);
39148
39372
  if (parent === current) return absolute;
@@ -39448,9 +39672,9 @@ function clearSignatureCache(sessionId) {
39448
39672
  // src/plugin/image-saver.ts
39449
39673
  import { chmodSync as chmodSync4, existsSync as existsSync11, mkdirSync as mkdirSync6, writeFileSync as writeFileSync6 } from "node:fs";
39450
39674
  import { homedir as homedir12 } from "node:os";
39451
- import { join as join26 } from "node:path";
39675
+ import { join as join28 } from "node:path";
39452
39676
  function getImageOutputDir(outputDir) {
39453
- const resolved = outputDir ?? join26(homedir12(), ".opencode", "generated-images");
39677
+ const resolved = outputDir ?? join28(homedir12(), ".opencode", "generated-images");
39454
39678
  if (!existsSync11(resolved)) {
39455
39679
  mkdirSync6(resolved, { recursive: true, mode: 448 });
39456
39680
  }
@@ -39473,7 +39697,7 @@ function generateImageFilename(mimeType) {
39473
39697
  function saveImageToDisk(base64Data, mimeType, outputDir) {
39474
39698
  try {
39475
39699
  const resolvedOutputDir = getImageOutputDir(outputDir);
39476
- const filePath = join26(resolvedOutputDir, generateImageFilename(mimeType));
39700
+ const filePath = join28(resolvedOutputDir, generateImageFilename(mimeType));
39477
39701
  writeFileSync6(filePath, Buffer.from(base64Data, "base64"), { mode: 384 });
39478
39702
  chmodSync4(filePath, 384);
39479
39703
  return filePath;
@@ -39908,11 +40132,11 @@ data: ${JSON.stringify(syntheticUsage)}
39908
40132
  // src/plugin/gemini-dump.ts
39909
40133
  import { createHash as createHash14 } from "node:crypto";
39910
40134
  import { appendFileSync as appendFileSync4, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "node:fs";
39911
- import { tmpdir as tmpdir4 } from "node:os";
39912
- import { join as join27 } from "node:path";
40135
+ import { tmpdir as tmpdir6 } from "node:os";
40136
+ import { join as join29 } from "node:path";
39913
40137
  var DUMP_STATUS_TITLE = "## Gemini Dump Status";
39914
40138
  var DUMP_DIR_ENV = "OPENCODE_ANTIGRAVITY_GEMINI_DUMP_DIR";
39915
- var DEFAULT_DUMP_DIR = join27(tmpdir4(), "opencode-antigravity-gemini-dumps");
40139
+ var DEFAULT_DUMP_DIR = join29(tmpdir6(), "opencode-antigravity-gemini-dumps");
39916
40140
  var DUMP_DIR_MODE = 448;
39917
40141
  var DUMP_FILE_MODE = 384;
39918
40142
  var nextDumpId = 0;
@@ -40066,7 +40290,7 @@ function writeGeminiDump(input2) {
40066
40290
  nextDumpId += 1;
40067
40291
  const id = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-${String(nextDumpId).padStart(5, "0")}-${input2.streaming ? "stream" : "json"}`;
40068
40292
  const dumpDir = getGeminiDumpDirectory();
40069
- const prefix = join27(dumpDir, id);
40293
+ const prefix = join29(dumpDir, id);
40070
40294
  mkdirSync7(dumpDir, { recursive: true, mode: DUMP_DIR_MODE });
40071
40295
  const context = {
40072
40296
  id,
@@ -40150,21 +40374,21 @@ import {
40150
40374
  unlinkSync as unlinkSync4,
40151
40375
  writeFileSync as writeFileSync8
40152
40376
  } from "node:fs";
40153
- import { join as join29 } from "node:path";
40377
+ import { join as join31 } from "node:path";
40154
40378
 
40155
40379
  // src/plugin/recovery/constants.ts
40156
40380
  import { homedir as homedir13 } from "node:os";
40157
- import { join as join28 } from "node:path";
40381
+ import { join as join30 } from "node:path";
40158
40382
  function getXdgData() {
40159
40383
  const platform = process.platform;
40160
40384
  if (platform === "win32") {
40161
- return process.env.APPDATA || join28(homedir13(), "AppData", "Roaming");
40385
+ return process.env.APPDATA || join30(homedir13(), "AppData", "Roaming");
40162
40386
  }
40163
- return process.env.XDG_DATA_HOME || join28(homedir13(), ".local", "share");
40387
+ return process.env.XDG_DATA_HOME || join30(homedir13(), ".local", "share");
40164
40388
  }
40165
- var OPENCODE_STORAGE = join28(getXdgData(), "opencode", "storage");
40166
- var MESSAGE_STORAGE = join28(OPENCODE_STORAGE, "message");
40167
- var PART_STORAGE = join28(OPENCODE_STORAGE, "part");
40389
+ var OPENCODE_STORAGE = join30(getXdgData(), "opencode", "storage");
40390
+ var MESSAGE_STORAGE = join30(OPENCODE_STORAGE, "message");
40391
+ var PART_STORAGE = join30(OPENCODE_STORAGE, "part");
40168
40392
  var THINKING_TYPES = /* @__PURE__ */ new Set([
40169
40393
  "thinking",
40170
40394
  "redacted_thinking",
@@ -40174,13 +40398,13 @@ var THINKING_TYPES = /* @__PURE__ */ new Set([
40174
40398
  // src/plugin/recovery/storage.ts
40175
40399
  function getMessageDir(sessionID) {
40176
40400
  if (!existsSync12(MESSAGE_STORAGE)) return "";
40177
- const directPath = join29(MESSAGE_STORAGE, sessionID);
40401
+ const directPath = join31(MESSAGE_STORAGE, sessionID);
40178
40402
  if (existsSync12(directPath)) {
40179
40403
  return directPath;
40180
40404
  }
40181
40405
  try {
40182
40406
  for (const dir of readdirSync2(MESSAGE_STORAGE)) {
40183
- const sessionPath = join29(MESSAGE_STORAGE, dir, sessionID);
40407
+ const sessionPath = join31(MESSAGE_STORAGE, dir, sessionID);
40184
40408
  if (existsSync12(sessionPath)) {
40185
40409
  return sessionPath;
40186
40410
  }
@@ -40197,7 +40421,7 @@ function readMessages(sessionID) {
40197
40421
  for (const file of readdirSync2(messageDir)) {
40198
40422
  if (!file.endsWith(".json")) continue;
40199
40423
  try {
40200
- const content = readFileSync11(join29(messageDir, file), "utf-8");
40424
+ const content = readFileSync11(join31(messageDir, file), "utf-8");
40201
40425
  messages.push(JSON.parse(content));
40202
40426
  } catch {
40203
40427
  }
@@ -40213,14 +40437,14 @@ function readMessages(sessionID) {
40213
40437
  });
40214
40438
  }
40215
40439
  function readParts(messageID) {
40216
- const partDir = join29(PART_STORAGE, messageID);
40440
+ const partDir = join31(PART_STORAGE, messageID);
40217
40441
  if (!existsSync12(partDir)) return [];
40218
40442
  const parts = [];
40219
40443
  try {
40220
40444
  for (const file of readdirSync2(partDir)) {
40221
40445
  if (!file.endsWith(".json")) continue;
40222
40446
  try {
40223
- const content = readFileSync11(join29(partDir, file), "utf-8");
40447
+ const content = readFileSync11(join31(partDir, file), "utf-8");
40224
40448
  parts.push(JSON.parse(content));
40225
40449
  } catch {
40226
40450
  }
@@ -40262,7 +40486,7 @@ function findMessagesWithOrphanThinking(sessionID) {
40262
40486
  return result;
40263
40487
  }
40264
40488
  function prependThinkingPart(sessionID, messageID) {
40265
- const partDir = join29(PART_STORAGE, messageID);
40489
+ const partDir = join31(PART_STORAGE, messageID);
40266
40490
  try {
40267
40491
  if (!existsSync12(partDir)) {
40268
40492
  mkdirSync8(partDir, { recursive: true });
@@ -40277,7 +40501,7 @@ function prependThinkingPart(sessionID, messageID) {
40277
40501
  synthetic: true
40278
40502
  };
40279
40503
  writeFileSync8(
40280
- join29(partDir, `${partId}.json`),
40504
+ join31(partDir, `${partId}.json`),
40281
40505
  JSON.stringify(part, null, 2)
40282
40506
  );
40283
40507
  return true;
@@ -40286,14 +40510,14 @@ function prependThinkingPart(sessionID, messageID) {
40286
40510
  }
40287
40511
  }
40288
40512
  function stripThinkingParts(messageID) {
40289
- const partDir = join29(PART_STORAGE, messageID);
40513
+ const partDir = join31(PART_STORAGE, messageID);
40290
40514
  if (!existsSync12(partDir)) return false;
40291
40515
  let anyRemoved = false;
40292
40516
  try {
40293
40517
  for (const file of readdirSync2(partDir)) {
40294
40518
  if (!file.endsWith(".json")) continue;
40295
40519
  try {
40296
- const filePath = join29(partDir, file);
40520
+ const filePath = join31(partDir, file);
40297
40521
  const content = readFileSync11(filePath, "utf-8");
40298
40522
  const part = JSON.parse(content);
40299
40523
  if (THINKING_TYPES.has(part.type)) {
@@ -45944,15 +46168,15 @@ function projectCommandAccountRows(storage) {
45944
46168
 
45945
46169
  // src/plugin/dependencies.ts
45946
46170
  import { homedir as homedir14 } from "node:os";
45947
- import { join as join30 } from "node:path";
46171
+ import { join as join32 } from "node:path";
45948
46172
  function defaultFilesystemRoots() {
45949
- const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join30(homedir14(), ".config");
45950
- const xdgState2 = process.env.XDG_STATE_HOME ?? join30(homedir14(), ".local", "state");
46173
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join32(homedir14(), ".config");
46174
+ const xdgState2 = process.env.XDG_STATE_HOME ?? join32(homedir14(), ".local", "state");
45951
46175
  return {
45952
46176
  projectRoot: process.cwd(),
45953
- userConfigRoot: join30(xdgConfig2, "opencode"),
45954
- sidebarStateRoot: join30(xdgState2, "cortexkit", "antigravity-auth"),
45955
- rpcRoot: join30(xdgState2, "cortexkit", "antigravity-auth", "rpc")
46177
+ userConfigRoot: join32(xdgConfig2, "opencode"),
46178
+ sidebarStateRoot: join32(xdgState2, "cortexkit", "antigravity-auth"),
46179
+ rpcRoot: join32(xdgState2, "cortexkit", "antigravity-auth", "rpc")
45956
46180
  };
45957
46181
  }
45958
46182
  function resolvePluginDependencies(overrides = {}) {
@@ -48558,8 +48782,8 @@ function extractRateLimitBodyInfo(body) {
48558
48782
  }
48559
48783
  }
48560
48784
  if (message) {
48561
- const afterMatch = message.match(/reset after\s+([0-9hms.]+)/i);
48562
- const rawDuration = afterMatch?.[1];
48785
+ const reset = message.match(/(?:reset after|resets? in)\s+([0-9hms.]+)/i);
48786
+ const rawDuration = reset?.[1];
48563
48787
  if (rawDuration) {
48564
48788
  const parsed = parseDurationToMs(rawDuration);
48565
48789
  if (parsed !== null) {
@@ -49088,6 +49312,19 @@ function createGoogleSearchTool({
49088
49312
  // src/plugin/lifecycle.ts
49089
49313
  var NOOP_DRAIN = async () => {
49090
49314
  };
49315
+ async function collectCleanupFailure(cleanup2, failures) {
49316
+ try {
49317
+ await cleanup2();
49318
+ } catch (error) {
49319
+ failures.push(error);
49320
+ }
49321
+ }
49322
+ function reportCleanupFailures(failures) {
49323
+ if (failures.length === 1) throw failures[0];
49324
+ if (failures.length > 1) {
49325
+ throw new AggregateError(failures, "Plugin cleanup failed");
49326
+ }
49327
+ }
49091
49328
  function createPluginLifecycle(options) {
49092
49329
  let accountManager = null;
49093
49330
  let refreshQueue = null;
@@ -49099,19 +49336,19 @@ function createPluginLifecycle(options) {
49099
49336
  const consumers = [];
49100
49337
  const drainSidebarWrites2 = options.drainSidebarWrites ?? NOOP_DRAIN;
49101
49338
  const retire2 = (manager, queue2, requests) => {
49102
- const queueDrained = Promise.resolve(queue2?.dispose());
49339
+ const queueDrained = (async () => {
49340
+ await queue2?.dispose();
49341
+ })();
49103
49342
  const record3 = {
49104
49343
  requests,
49105
49344
  done: (async () => {
49106
- const drained = await Promise.allSettled([
49107
- queueDrained,
49108
- requests?.retire()
49345
+ const failures = [];
49346
+ await Promise.all([
49347
+ collectCleanupFailure(() => queueDrained, failures),
49348
+ collectCleanupFailure(() => requests?.retire(), failures)
49109
49349
  ]);
49110
- await manager.dispose();
49111
- const failed = drained.find(
49112
- (outcome) => outcome.status === "rejected"
49113
- );
49114
- if (failed) throw failed.reason;
49350
+ await collectCleanupFailure(() => manager.dispose(), failures);
49351
+ reportCleanupFailures(failures);
49115
49352
  })()
49116
49353
  };
49117
49354
  retiring.add(record3);
@@ -49121,8 +49358,6 @@ function createPluginLifecycle(options) {
49121
49358
  if (!requests) retiring.delete(record3);
49122
49359
  }
49123
49360
  );
49124
- void queueDrained.catch(() => {
49125
- });
49126
49361
  return { queueDrained, done: record3.done };
49127
49362
  };
49128
49363
  const disposeAccountRuntime = async () => {
@@ -49134,23 +49369,26 @@ function createPluginLifecycle(options) {
49134
49369
  accountRequests = null;
49135
49370
  const retired = [...retiring];
49136
49371
  retiring.clear();
49372
+ const failures = [];
49137
49373
  const aborted = Promise.all([
49138
- oldRequests?.dispose(),
49139
- ...retired.map((record3) => record3.requests?.dispose())
49374
+ collectCleanupFailure(() => oldRequests?.dispose(), failures),
49375
+ ...retired.map(
49376
+ (record3) => collectCleanupFailure(() => record3.requests?.dispose(), failures)
49377
+ )
49140
49378
  ]);
49141
- const liveQueueDrained = Promise.resolve(oldQueue?.dispose());
49142
- void liveQueueDrained.catch(() => {
49143
- });
49144
- await aborted;
49145
- const retirements = await Promise.allSettled(
49146
- retired.map((record3) => record3.done)
49379
+ const liveQueueDrained = collectCleanupFailure(
49380
+ () => oldQueue?.dispose(),
49381
+ failures
49147
49382
  );
49148
- await liveQueueDrained;
49149
- await oldManager?.dispose();
49150
- const failed = retirements.find(
49151
- (outcome) => outcome.status === "rejected"
49152
- );
49153
- if (failed) throw failed.reason;
49383
+ await Promise.all([
49384
+ aborted,
49385
+ liveQueueDrained,
49386
+ ...retired.map(
49387
+ (record3) => collectCleanupFailure(() => record3.done, failures)
49388
+ )
49389
+ ]);
49390
+ await collectCleanupFailure(() => oldManager?.dispose(), failures);
49391
+ reportCleanupFailures(failures);
49154
49392
  };
49155
49393
  const register = (disposable, phase = "consumer") => {
49156
49394
  if (closing) {
@@ -49205,19 +49443,27 @@ function createPluginLifecycle(options) {
49205
49443
  failDisposal = reject;
49206
49444
  });
49207
49445
  void (async () => {
49208
- await disposeAccountRuntime();
49209
- await options.shutdownDiskSignatureCache();
49210
- options.sessionRegistry.clear();
49211
- options.clearFetchState();
49446
+ const failures = [];
49447
+ await collectCleanupFailure(disposeAccountRuntime, failures);
49448
+ await collectCleanupFailure(
49449
+ () => options.shutdownDiskSignatureCache(),
49450
+ failures
49451
+ );
49452
+ await collectCleanupFailure(
49453
+ () => options.sessionRegistry.clear(),
49454
+ failures
49455
+ );
49456
+ await collectCleanupFailure(() => options.clearFetchState(), failures);
49212
49457
  for (const disposable of producers) {
49213
- await disposable.dispose();
49458
+ await collectCleanupFailure(() => disposable.dispose(), failures);
49214
49459
  }
49215
49460
  producers.length = 0;
49216
- await drainSidebarWrites2();
49461
+ await collectCleanupFailure(drainSidebarWrites2, failures);
49217
49462
  for (const disposable of consumers) {
49218
- await disposable.dispose();
49463
+ await collectCleanupFailure(() => disposable.dispose(), failures);
49219
49464
  }
49220
49465
  consumers.length = 0;
49466
+ reportCleanupFailures(failures);
49221
49467
  })().then(finishDisposal, failDisposal);
49222
49468
  }
49223
49469
  return disposal;
@@ -49595,7 +49841,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
49595
49841
  lifecycle.register(vaultQuotaPoller, "producer");
49596
49842
  }
49597
49843
  const operatorSettings = createOperatorSettingsController({
49598
- projectConfigPath: join31(directory, ".opencode", "antigravity.json"),
49844
+ projectConfigPath: join33(directory, ".opencode", "antigravity.json"),
49599
49845
  // getUserConfigPath() already returns the full file path including
49600
49846
  // 'antigravity.json' — do NOT join again or the path double-nests
49601
49847
  // into <dir>/antigravity.json/antigravity.json.