@cortexkit/opencode-antigravity-auth 3.0.10 → 3.0.12

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 (110) hide show
  1. package/dist/cli.js +2077 -1451
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +207 -120
  4. package/dist/index.js +1526 -861
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +214 -127
  7. package/dist/server.js +1524 -859
  8. package/dist/server.js.map +4 -4
  9. package/dist/server.meta.json +1 -1
  10. package/dist/src/common-auth-embedded/claustrum/consumer.d.ts +7 -1
  11. package/dist/src/common-auth-embedded/claustrum/consumer.js +17 -2
  12. package/dist/src/common-auth-embedded/claustrum/enrollment.d.ts +5 -0
  13. package/dist/src/common-auth-embedded/claustrum/enrollment.js +27 -0
  14. package/dist/src/common-auth-embedded/claustrum/errors.d.ts +1 -1
  15. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  16. package/dist/src/common-auth-embedded/claustrum/index.js +1 -1
  17. package/dist/src/common-auth-embedded/claustrum/quota-writer.js +4 -54
  18. package/dist/src/common-auth-embedded/claustrum/roster.d.ts +31 -0
  19. package/dist/src/common-auth-embedded/claustrum/roster.js +72 -0
  20. package/dist/src/common-auth-embedded/commands/builtins.d.ts +37 -0
  21. package/dist/src/common-auth-embedded/commands/builtins.js +95 -13
  22. package/dist/src/common-auth-embedded/commands/index.d.ts +1 -1
  23. package/dist/src/common-auth-embedded/fs/private-files.d.ts +2 -0
  24. package/dist/src/common-auth-embedded/fs/private-files.js +49 -3
  25. package/dist/src/common-auth-embedded/opencode2/install.d.ts +3 -2
  26. package/dist/src/common-auth-embedded/opencode2/install.js +184 -63
  27. package/dist/src/common-auth-embedded/opencode2/types.d.ts +43 -6
  28. package/dist/src/common-auth-embedded/quota/pending.js +48 -0
  29. package/dist/src/common-auth-embedded/setup/enroll.d.ts +34 -0
  30. package/dist/src/common-auth-embedded/setup/enroll.js +116 -34
  31. package/dist/src/common-auth-embedded/setup/index.d.ts +1 -0
  32. package/dist/src/common-auth-embedded/setup/index.js +1 -0
  33. package/dist/src/common-auth-embedded/setup/process-fence.d.ts +7 -0
  34. package/dist/src/common-auth-embedded/setup/process-fence.js +56 -1
  35. package/dist/src/common-auth-embedded/setup/types.d.ts +5 -0
  36. package/dist/src/common-auth-embedded/source-output.json +121 -97
  37. package/dist/src/common-auth-embedded/store/attribution.d.ts +5 -0
  38. package/dist/src/common-auth-embedded/store/attribution.js +39 -25
  39. package/dist/src/common-auth-embedded/store/pool.d.ts +17 -0
  40. package/dist/src/common-auth-embedded/store/pool.js +18 -3
  41. package/dist/src/common-auth-embedded/store/pull.js +3 -1
  42. package/dist/src/common-auth-embedded/store/quota-writer.js +298 -0
  43. package/dist/src/common-auth-embedded/store/runtime.d.ts +2 -0
  44. package/dist/src/plugin/lifecycle.d.ts.map +1 -1
  45. package/dist/src/plugin/lifecycle.js +48 -27
  46. package/dist/src/plugin/lifecycle.js.map +1 -1
  47. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  48. package/dist/src/plugin/shared/request-services.js +3 -2
  49. package/dist/src/plugin/shared/request-services.js.map +1 -1
  50. package/dist/src/plugin/vault-custody.d.ts.map +1 -1
  51. package/dist/src/plugin/vault-custody.js +13 -3
  52. package/dist/src/plugin/vault-custody.js.map +1 -1
  53. package/dist/tui-build-map.json +5 -5
  54. package/dist/tui-ga-build-map.json +1 -1
  55. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +7 -1
  56. package/dist/types/src/common-auth-embedded/claustrum/enrollment.d.ts +5 -0
  57. package/dist/types/src/common-auth-embedded/claustrum/errors.d.ts +1 -1
  58. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  59. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +31 -0
  60. package/dist/types/src/common-auth-embedded/commands/builtins.d.ts +37 -0
  61. package/dist/types/src/common-auth-embedded/commands/index.d.ts +1 -1
  62. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +3 -2
  63. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +43 -6
  64. package/dist/types/src/common-auth-embedded/setup/enroll.d.ts +34 -0
  65. package/dist/types/src/common-auth-embedded/setup/index.d.ts +1 -0
  66. package/dist/types/src/common-auth-embedded/setup/process-fence.d.ts +7 -0
  67. package/dist/types/src/common-auth-embedded/setup/types.d.ts +5 -0
  68. package/dist/types/src/common-auth-embedded/store/attribution.d.ts +5 -0
  69. package/dist/types/src/common-auth-embedded/store/pool.d.ts +17 -0
  70. package/dist/types/src/common-auth-embedded/store/runtime.d.ts +2 -0
  71. package/dist/types/src/plugin/lifecycle.d.ts.map +1 -1
  72. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  73. package/dist/types/src/plugin/vault-custody.d.ts.map +1 -1
  74. package/package.json +2 -2
  75. package/src/common-auth-embedded/claustrum/consumer.d.ts +7 -1
  76. package/src/common-auth-embedded/claustrum/consumer.js +17 -2
  77. package/src/common-auth-embedded/claustrum/enrollment.d.ts +5 -0
  78. package/src/common-auth-embedded/claustrum/enrollment.js +27 -0
  79. package/src/common-auth-embedded/claustrum/errors.d.ts +1 -1
  80. package/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  81. package/src/common-auth-embedded/claustrum/index.js +1 -1
  82. package/src/common-auth-embedded/claustrum/quota-writer.js +4 -54
  83. package/src/common-auth-embedded/claustrum/roster.d.ts +31 -0
  84. package/src/common-auth-embedded/claustrum/roster.js +72 -0
  85. package/src/common-auth-embedded/commands/builtins.d.ts +37 -0
  86. package/src/common-auth-embedded/commands/builtins.js +95 -13
  87. package/src/common-auth-embedded/commands/index.d.ts +1 -1
  88. package/src/common-auth-embedded/fs/private-files.d.ts +2 -0
  89. package/src/common-auth-embedded/fs/private-files.js +49 -3
  90. package/src/common-auth-embedded/opencode2/install.d.ts +3 -2
  91. package/src/common-auth-embedded/opencode2/install.js +184 -63
  92. package/src/common-auth-embedded/opencode2/types.d.ts +43 -6
  93. package/src/common-auth-embedded/quota/pending.js +48 -0
  94. package/src/common-auth-embedded/setup/enroll.d.ts +34 -0
  95. package/src/common-auth-embedded/setup/enroll.js +116 -34
  96. package/src/common-auth-embedded/setup/index.d.ts +1 -0
  97. package/src/common-auth-embedded/setup/index.js +1 -0
  98. package/src/common-auth-embedded/setup/process-fence.d.ts +7 -0
  99. package/src/common-auth-embedded/setup/process-fence.js +56 -1
  100. package/src/common-auth-embedded/setup/types.d.ts +5 -0
  101. package/src/common-auth-embedded/source-output.json +121 -97
  102. package/src/common-auth-embedded/store/attribution.d.ts +5 -0
  103. package/src/common-auth-embedded/store/attribution.js +39 -25
  104. package/src/common-auth-embedded/store/pool.d.ts +17 -0
  105. package/src/common-auth-embedded/store/pool.js +18 -3
  106. package/src/common-auth-embedded/store/pull.js +3 -1
  107. package/src/common-auth-embedded/store/quota-writer.js +298 -0
  108. package/src/common-auth-embedded/store/runtime.d.ts +2 -0
  109. package/src/tui-compiled/common-auth-embedded/fs/private-files.js +49 -3
  110. package/src/tui-raw/common-auth-embedded/fs/private-files.js +49 -3
package/dist/server.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;
@@ -3171,13 +3196,40 @@ var init_runtime = __esm({
3171
3196
  });
3172
3197
 
3173
3198
  // ../core/dist/common-auth-embedded/store/attribution.js
3199
+ function assertQuotaEpoch(id, attribution) {
3200
+ if (!isCredentialEpoch(attribution?.credentialEpoch))
3201
+ throw refusal2("pull", id, "invalid-input", "the credential epoch the reading was issued for must be a positive safe integer");
3202
+ }
3203
+ function assertQuotaRow(id, attribution, row) {
3204
+ if (!row)
3205
+ throw unknownRow("pull", id);
3206
+ if (row.invalid)
3207
+ throw refusal2("pull", id, "invalid-row", `row ${id} is invalid`);
3208
+ if (!row.credential)
3209
+ throw refusal2("pull", id, "no-credential", `row ${id} holds no credential`);
3210
+ requireBound("pull", row);
3211
+ if (row.torn || !row.hasEntry || row.credentialEpoch !== attribution.credentialEpoch || row.identity !== attribution.identity)
3212
+ throw new PoolOperationError({
3213
+ operation: "pull",
3214
+ rowId: id,
3215
+ phase: "pull",
3216
+ retryable: true,
3217
+ kind: "attribution",
3218
+ message: `quota for ${id} was issued for a credential the row no longer holds`
3219
+ });
3220
+ }
3221
+ function mergedQuota(ctx, id, stored, observation) {
3222
+ const merged = ctx.codec.merge(stored, observation);
3223
+ if (!ctx.codec.validate(merged))
3224
+ throw refusal2("pull", id, "invalid-quota", "the quota codec rejected the merged map");
3225
+ return merged;
3226
+ }
3174
3227
  async function recordQuota(rt, id, attribution, observation) {
3175
3228
  const { ctx } = rt;
3176
3229
  const locks = new LockStack(ctx.lockDefaults, ctx.lockEnv);
3177
3230
  const progress = { writes: 0 };
3178
3231
  try {
3179
- if (!isCredentialEpoch(attribution?.credentialEpoch))
3180
- throw refusal2("pull", id, "invalid-input", "the credential epoch the reading was issued for must be a positive safe integer");
3232
+ assertQuotaEpoch(id, attribution);
3181
3233
  await withTransaction(
3182
3234
  ctx,
3183
3235
  locks,
@@ -3186,26 +3238,11 @@ async function recordQuota(rt, id, attribution, observation) {
3186
3238
  async (tx) => {
3187
3239
  tx.assertNotStaged(id);
3188
3240
  const row = tx.row(id);
3189
- if (!row)
3190
- throw unknownRow("pull", id);
3191
- if (row.invalid)
3192
- throw refusal2("pull", id, "invalid-row", `row ${id} is invalid`);
3193
- if (!row.credential)
3194
- throw refusal2("pull", id, "no-credential", `row ${id} holds no credential`);
3195
- requireBound("pull", row);
3241
+ assertQuotaRow(id, attribution, row);
3196
3242
  const entry = tx.entry(id);
3197
- if (row.torn || !entry || entry.credentialEpoch !== attribution.credentialEpoch || row.identity !== attribution.identity)
3198
- throw new PoolOperationError({
3199
- operation: "pull",
3200
- rowId: id,
3201
- phase: "pull",
3202
- retryable: true,
3203
- kind: "attribution",
3204
- message: `quota for ${id} was issued for a credential the row no longer holds`
3205
- });
3206
- const merged = ctx.codec.merge(entry.quota, observation);
3207
- if (!ctx.codec.validate(merged))
3208
- throw refusal2("pull", id, "invalid-quota", "the quota codec rejected the merged map");
3243
+ if (!entry)
3244
+ throw unknownRow("pull", id);
3245
+ const merged = mergedQuota(ctx, id, entry.quota, observation);
3209
3246
  tx.setEntry(id, { ...entry, quota: merged, needsFirstReading: false });
3210
3247
  await tx.commitConfig();
3211
3248
  },
@@ -4615,7 +4652,8 @@ var init_pull = __esm({
4615
4652
  cause
4616
4653
  });
4617
4654
  }
4618
- await recordQuota(rt, id, {
4655
+ const publish = rt.publishQuota ?? ((rowId2, attribution, value) => recordQuota(rt, rowId2, attribution, value));
4656
+ await publish(id, {
4619
4657
  credentialEpoch: request.credentialEpoch,
4620
4658
  ...request.identity !== void 0 ? { identity: request.identity } : {}
4621
4659
  }, observation);
@@ -4645,6 +4683,695 @@ var init_pull = __esm({
4645
4683
  }
4646
4684
  });
4647
4685
 
4686
+ // ../core/dist/common-auth-embedded/logger/capture-sink.js
4687
+ function createCaptureSink() {
4688
+ const records = [];
4689
+ const sink = (record3) => {
4690
+ records.push(record3);
4691
+ };
4692
+ return {
4693
+ records,
4694
+ sink,
4695
+ clear: () => {
4696
+ records.length = 0;
4697
+ }
4698
+ };
4699
+ }
4700
+ var init_capture_sink = __esm({
4701
+ "../core/dist/common-auth-embedded/logger/capture-sink.js"() {
4702
+ "use strict";
4703
+ }
4704
+ });
4705
+
4706
+ // ../core/dist/common-auth-embedded/logger/redact.js
4707
+ function isError(value) {
4708
+ return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
4709
+ }
4710
+ function createRedactor(options = {}) {
4711
+ const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
4712
+ function isSecretKey(key) {
4713
+ const normalized = key.toLowerCase().replace(/[-_]/g, "");
4714
+ return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
4715
+ }
4716
+ function errorEntries(error) {
4717
+ const fields2 = error;
4718
+ const entries = [
4719
+ ["name", error.name],
4720
+ ["message", error.message],
4721
+ ["stack", error.stack]
4722
+ ];
4723
+ for (const key of ["code", "status", "cause"])
4724
+ if (fields2[key] !== void 0)
4725
+ entries.push([key, fields2[key]]);
4726
+ const listed = new Set(entries.map(([key]) => key));
4727
+ for (const entry of Object.entries(error))
4728
+ if (!listed.has(entry[0]))
4729
+ entries.push(entry);
4730
+ return entries;
4731
+ }
4732
+ function walk(value, keys, seen, errorDepth = 0) {
4733
+ if (typeof value === "string") {
4734
+ return patterns.reduce((text2, pattern) => text2.replace(pattern, MASK), value);
4735
+ }
4736
+ if (!value || typeof value !== "object")
4737
+ return value;
4738
+ if (seen.has(value))
4739
+ return "[Circular]";
4740
+ seen.add(value);
4741
+ try {
4742
+ if (Array.isArray(value))
4743
+ return value.map((item) => walk(item, keys, seen, errorDepth));
4744
+ const error = isError(value);
4745
+ if (error && errorDepth >= MAX_ERROR_DEPTH)
4746
+ return "[Truncated]";
4747
+ const childDepth = error ? errorDepth + 1 : errorDepth;
4748
+ return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
4749
+ key,
4750
+ keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
4751
+ ]));
4752
+ } finally {
4753
+ seen.delete(value);
4754
+ }
4755
+ }
4756
+ return {
4757
+ redact: (value) => walk(value, true, /* @__PURE__ */ new WeakSet()),
4758
+ // Schema keys describe arguments, not credentials; only their string values are scrubbed.
4759
+ redactStrings: (value) => walk(value, false, /* @__PURE__ */ new WeakSet())
4760
+ };
4761
+ }
4762
+ var SECRET_KEY_EXACT, TOKEN_VALUE, MASK, MAX_ERROR_DEPTH, defaultRedactor, redact, redactStrings;
4763
+ var init_redact = __esm({
4764
+ "../core/dist/common-auth-embedded/logger/redact.js"() {
4765
+ "use strict";
4766
+ SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
4767
+ TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
4768
+ MASK = "***REDACTED***";
4769
+ MAX_ERROR_DEPTH = 8;
4770
+ defaultRedactor = createRedactor();
4771
+ redact = defaultRedactor.redact;
4772
+ redactStrings = defaultRedactor.redactStrings;
4773
+ }
4774
+ });
4775
+
4776
+ // ../core/dist/common-auth-embedded/logger/engine.js
4777
+ import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
4778
+ import { open as open5 } from "node:fs/promises";
4779
+ import { dirname as dirname8, resolve as resolve3 } from "node:path";
4780
+ function chmodPrivate(path5) {
4781
+ try {
4782
+ chmodSync(path5, 384);
4783
+ } catch {
4784
+ }
4785
+ }
4786
+ function rotateIfNeeded(f) {
4787
+ try {
4788
+ if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
4789
+ return;
4790
+ for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
4791
+ if (existsSync(`${f}.${i}`)) {
4792
+ const rotated2 = `${f}.${i + 1}`;
4793
+ renameSync(`${f}.${i}`, rotated2);
4794
+ chmodPrivate(rotated2);
4795
+ }
4796
+ }
4797
+ const rotated = `${f}.1`;
4798
+ renameSync(f, rotated);
4799
+ chmodPrivate(rotated);
4800
+ } catch {
4801
+ }
4802
+ }
4803
+ async function closeWindowsFile(sink) {
4804
+ const { file, handle } = sink;
4805
+ sink.file = void 0;
4806
+ sink.handle = void 0;
4807
+ if (file && handle)
4808
+ await privateOperation(file, "log-close", () => handle.close());
4809
+ }
4810
+ async function openWindowsFile(sink, file) {
4811
+ await ensurePrivateDirectory(dirname8(file));
4812
+ try {
4813
+ await verifyPrivate(file, "file", true);
4814
+ } catch (error) {
4815
+ if (error.code !== "ENOENT")
4816
+ throw error;
4817
+ try {
4818
+ await createPrivateBytes(file, "");
4819
+ } catch (creationError) {
4820
+ if (creationError.code !== "EEXIST")
4821
+ throw creationError;
4822
+ await verifyPrivate(file, "file", true);
4823
+ }
4824
+ }
4825
+ sink.handle = await privateOperation(file, "log-open", () => open5(file, "a"));
4826
+ sink.file = file;
4827
+ return sink.handle;
4828
+ }
4829
+ async function flushWindowsFile(sink, file, text2) {
4830
+ file = resolve3(file);
4831
+ try {
4832
+ if (sink.file !== file)
4833
+ await closeWindowsFile(sink);
4834
+ let handle = sink.handle ?? await openWindowsFile(sink, file);
4835
+ const info = await privateOperation(file, "log-stat", () => handle.stat());
4836
+ if (info.size >= MAX_BYTES) {
4837
+ await closeWindowsFile(sink);
4838
+ for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
4839
+ const source = i === 0 ? file : `${file}.${i}`;
4840
+ const target = `${file}.${i + 1}`;
4841
+ try {
4842
+ await verifyPrivate(source, "file", true);
4843
+ } catch (error) {
4844
+ if (error.code === "ENOENT")
4845
+ continue;
4846
+ throw error;
4847
+ }
4848
+ try {
4849
+ await verifyPrivate(target, "file", true);
4850
+ } catch (error) {
4851
+ if (error.code !== "ENOENT")
4852
+ throw error;
4853
+ }
4854
+ await replaceWindowsFile(source, target);
4855
+ await verifyPrivate(target, "file");
4856
+ }
4857
+ handle = await openWindowsFile(sink, file);
4858
+ }
4859
+ await privateOperation(file, "log-append", () => handle.appendFile(text2, "utf8"));
4860
+ } catch (error) {
4861
+ await closeWindowsFile(sink).catch(() => {
4862
+ });
4863
+ throw error;
4864
+ }
4865
+ }
4866
+ function safeSerialize(data) {
4867
+ try {
4868
+ return ` ${JSON.stringify(data)}`;
4869
+ } catch {
4870
+ return " [unserializable]";
4871
+ }
4872
+ }
4873
+ function createEngine(options) {
4874
+ let logFileSource;
4875
+ let initLevelSource;
4876
+ let runtimeLevel;
4877
+ let redactor = createRedactor();
4878
+ let captureSink;
4879
+ let buffer = [];
4880
+ let timer;
4881
+ let orderedSink = Promise.resolve();
4882
+ let sinkError;
4883
+ const windowsFile = {};
4884
+ function queueWindows(operation) {
4885
+ const next = orderedSink.then(operation);
4886
+ orderedSink = next.catch((error) => {
4887
+ sinkError = error;
4888
+ });
4889
+ return next;
4890
+ }
4891
+ function configure(next) {
4892
+ if (windowsPrivateFiles && next.file !== logFileSource)
4893
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
4894
+ });
4895
+ logFileSource = next.file;
4896
+ initLevelSource = next.level;
4897
+ redactor = createRedactor(next);
4898
+ captureSink = next.captureSink;
4899
+ }
4900
+ function setLogLevel3(l) {
4901
+ if (l === void 0 || l in ORDER)
4902
+ runtimeLevel = l;
4903
+ }
4904
+ function logFilePath() {
4905
+ if (logFileSource === void 0)
4906
+ return void 0;
4907
+ const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
4908
+ return resolved || void 0;
4909
+ }
4910
+ function configuredLevel() {
4911
+ if (runtimeLevel)
4912
+ return runtimeLevel;
4913
+ const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
4914
+ if (floor && floor in ORDER)
4915
+ return floor;
4916
+ return "info";
4917
+ }
4918
+ function flushLogs3(close = true) {
4919
+ if (timer) {
4920
+ clearTimeout(timer);
4921
+ timer = void 0;
4922
+ }
4923
+ if (!buffer.length) {
4924
+ if (windowsPrivateFiles)
4925
+ return queueWindows(async () => {
4926
+ if (close)
4927
+ await closeWindowsFile(windowsFile);
4928
+ if (sinkError)
4929
+ throw sinkError;
4930
+ });
4931
+ return;
4932
+ }
4933
+ let file;
4934
+ try {
4935
+ file = logFilePath();
4936
+ } catch {
4937
+ buffer = [];
4938
+ if (windowsPrivateFiles && close)
4939
+ return queueWindows(() => closeWindowsFile(windowsFile));
4940
+ return;
4941
+ }
4942
+ const text2 = buffer.join("");
4943
+ buffer = [];
4944
+ if (!file) {
4945
+ if (windowsPrivateFiles && close)
4946
+ return queueWindows(() => closeWindowsFile(windowsFile));
4947
+ return;
4948
+ }
4949
+ if (windowsPrivateFiles) {
4950
+ return queueWindows(async () => {
4951
+ try {
4952
+ await flushWindowsFile(windowsFile, file, text2);
4953
+ } finally {
4954
+ if (close)
4955
+ await closeWindowsFile(windowsFile);
4956
+ }
4957
+ });
4958
+ }
4959
+ try {
4960
+ rotateIfNeeded(file);
4961
+ if (existsSync(file))
4962
+ chmodPrivate(file);
4963
+ appendFileSync(file, text2, { encoding: "utf8", mode: 384 });
4964
+ } catch {
4965
+ }
4966
+ }
4967
+ function schedule2() {
4968
+ if (!timer)
4969
+ timer = setTimeout(() => {
4970
+ timer = void 0;
4971
+ const flushed = flushLogs3(false);
4972
+ if (flushed instanceof Promise)
4973
+ void flushed.catch(() => {
4974
+ });
4975
+ }, 500);
4976
+ }
4977
+ function emit(channel, level, message, data) {
4978
+ if (logFileSource === void 0 && captureSink === void 0)
4979
+ return;
4980
+ try {
4981
+ if (ORDER[level] > ORDER[configuredLevel()])
4982
+ return;
4983
+ const scrubbedMessage = redactor.redactStrings(message);
4984
+ let scrubbedData;
4985
+ try {
4986
+ scrubbedData = redactor.redact(data);
4987
+ } catch {
4988
+ scrubbedData = "[unserializable]";
4989
+ }
4990
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${level.toUpperCase()} [${channel}] ${scrubbedMessage}` + (data === void 0 ? "" : safeSerialize(scrubbedData)) + "\n";
4991
+ try {
4992
+ captureSink?.({
4993
+ channel,
4994
+ level,
4995
+ message: scrubbedMessage,
4996
+ data: scrubbedData
4997
+ });
4998
+ } catch {
4999
+ }
5000
+ if (logFileSource === void 0)
5001
+ return;
5002
+ buffer.push(line);
5003
+ if (buffer.length >= 50) {
5004
+ const flushed = flushLogs3(false);
5005
+ if (flushed instanceof Promise)
5006
+ void flushed.catch(() => {
5007
+ });
5008
+ } else
5009
+ schedule2();
5010
+ } catch {
5011
+ }
5012
+ }
5013
+ function createLogger5(channel) {
5014
+ return {
5015
+ error: (m, d) => emit(channel, "error", m, d),
5016
+ warn: (m, d) => emit(channel, "warn", m, d),
5017
+ info: (m, d) => emit(channel, "info", m, d),
5018
+ debug: (m, d) => emit(channel, "debug", m, d),
5019
+ trace: (m, d) => emit(channel, "trace", m, d)
5020
+ };
5021
+ }
5022
+ function reset() {
5023
+ if (windowsPrivateFiles)
5024
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
5025
+ });
5026
+ sinkError = void 0;
5027
+ buffer = [];
5028
+ if (timer) {
5029
+ clearTimeout(timer);
5030
+ timer = void 0;
5031
+ }
5032
+ logFileSource = void 0;
5033
+ initLevelSource = void 0;
5034
+ runtimeLevel = void 0;
5035
+ redactor = createRedactor();
5036
+ captureSink = void 0;
5037
+ }
5038
+ if (options)
5039
+ configure(options);
5040
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3, reset };
5041
+ }
5042
+ function createLoggerInstance(options) {
5043
+ const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine(options);
5044
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
5045
+ }
5046
+ function initLogger(options) {
5047
+ defaultEngine.configure(options);
5048
+ const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = defaultEngine;
5049
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
5050
+ }
5051
+ function setLogLevel(l) {
5052
+ defaultEngine.setLogLevel(l);
5053
+ }
5054
+ function flushLogs() {
5055
+ return defaultEngine.flushLogs();
5056
+ }
5057
+ function createLogger2(channel) {
5058
+ return defaultEngine.createLogger(channel);
5059
+ }
5060
+ async function flushForTest() {
5061
+ return defaultEngine.flushLogs();
5062
+ }
5063
+ function resetLoggerForTest() {
5064
+ defaultEngine.reset();
5065
+ }
5066
+ var ORDER, MAX_BYTES, ROTATE_KEEP, defaultEngine;
5067
+ var init_engine = __esm({
5068
+ "../core/dist/common-auth-embedded/logger/engine.js"() {
5069
+ "use strict";
5070
+ init_private_files();
5071
+ init_redact();
5072
+ ORDER = {
5073
+ error: 0,
5074
+ warn: 1,
5075
+ info: 2,
5076
+ debug: 3,
5077
+ trace: 4
5078
+ };
5079
+ MAX_BYTES = 5 * 1024 * 1024;
5080
+ ROTATE_KEEP = 3;
5081
+ defaultEngine = createEngine();
5082
+ }
5083
+ });
5084
+
5085
+ // ../core/dist/common-auth-embedded/logger/index.js
5086
+ var logger_exports = {};
5087
+ __export(logger_exports, {
5088
+ createCaptureSink: () => createCaptureSink,
5089
+ createLogger: () => createLogger2,
5090
+ createLoggerInstance: () => createLoggerInstance,
5091
+ createRedactor: () => createRedactor,
5092
+ flushForTest: () => flushForTest,
5093
+ flushLogs: () => flushLogs,
5094
+ initLogger: () => initLogger,
5095
+ redact: () => redact,
5096
+ redactStrings: () => redactStrings,
5097
+ resetLoggerForTest: () => resetLoggerForTest,
5098
+ setLogLevel: () => setLogLevel
5099
+ });
5100
+ var init_logger = __esm({
5101
+ "../core/dist/common-auth-embedded/logger/index.js"() {
5102
+ "use strict";
5103
+ init_capture_sink();
5104
+ init_engine();
5105
+ init_redact();
5106
+ }
5107
+ });
5108
+
5109
+ // ../core/dist/common-auth-embedded/store/quota-writer.js
5110
+ var COALESCE_MS, POOL_QUOTA_QUEUE_LIMIT, PoolQuotaWriter;
5111
+ var init_quota_writer = __esm({
5112
+ "../core/dist/common-auth-embedded/store/quota-writer.js"() {
5113
+ "use strict";
5114
+ init_logger();
5115
+ init_attribution();
5116
+ init_errors();
5117
+ init_mutate();
5118
+ init_refresh_lock();
5119
+ init_runtime();
5120
+ init_schema();
5121
+ COALESCE_MS = 100;
5122
+ POOL_QUOTA_QUEUE_LIMIT = 128;
5123
+ PoolQuotaWriter = class {
5124
+ rt;
5125
+ timeoutMs;
5126
+ pending = /* @__PURE__ */ new Map();
5127
+ warned = /* @__PURE__ */ new Set();
5128
+ wake = /* @__PURE__ */ new Set();
5129
+ logger;
5130
+ timer;
5131
+ running;
5132
+ closing;
5133
+ closed = false;
5134
+ stopped = false;
5135
+ failures = 0;
5136
+ constructor(rt, timeoutMs = 1e3) {
5137
+ this.rt = rt;
5138
+ this.timeoutMs = timeoutMs;
5139
+ this.logger = rt.ctx.logger ?? createLogger2("store");
5140
+ }
5141
+ async record(id, attribution, observation) {
5142
+ try {
5143
+ this.assertOpen(id);
5144
+ assertQuotaEpoch(id, attribution);
5145
+ const publication2 = structuredClone({
5146
+ id,
5147
+ attribution,
5148
+ observation
5149
+ });
5150
+ const { row, result } = await readRow(this.rt, "pull", id);
5151
+ assertQuotaRow(id, publication2.attribution, row);
5152
+ mergedQuota(this.rt.ctx, id, this.overlayRow({ ...row, quota: entryIn(result.config, id)?.quota }).quota, publication2.observation);
5153
+ await this.room(id);
5154
+ this.assertOpen(id);
5155
+ const queue2 = this.pending.get(id) ?? [];
5156
+ queue2.push(publication2);
5157
+ this.pending.set(id, queue2);
5158
+ if (queue2.length >= POOL_QUOTA_QUEUE_LIMIT)
5159
+ this.flushNow();
5160
+ else
5161
+ this.schedule(COALESCE_MS);
5162
+ } catch (error) {
5163
+ throw toFailure(error, "pull", id, { writes: 0 });
5164
+ }
5165
+ }
5166
+ queued(id) {
5167
+ return this.pending.get(id)?.length ?? 0;
5168
+ }
5169
+ // Waits while the row's queue is full, flushing at once on every wake-up,
5170
+ // for at most the store's own lock acquisition budget.
5171
+ async room(id) {
5172
+ if (this.queued(id) < POOL_QUOTA_QUEUE_LIMIT)
5173
+ return;
5174
+ const { ctx } = this.rt;
5175
+ const budget = Math.max(0, ...ctx.storeLocks.map((spec) => spec.timeoutMs ?? ctx.lockDefaults.timeoutMs));
5176
+ const deadline = performance.now() + budget;
5177
+ while (this.queued(id) >= POOL_QUOTA_QUEUE_LIMIT) {
5178
+ this.assertOpen(id);
5179
+ this.flushNow();
5180
+ const left = deadline - performance.now();
5181
+ if (left <= 0)
5182
+ 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);
5183
+ await new Promise((resolve20) => {
5184
+ const done = () => {
5185
+ clearTimeout(timer);
5186
+ this.wake.delete(done);
5187
+ resolve20();
5188
+ };
5189
+ const timer = setTimeout(done, left);
5190
+ this.wake.add(done);
5191
+ });
5192
+ }
5193
+ }
5194
+ assertOpen(id) {
5195
+ if (this.closed)
5196
+ throw refusal2("pull", id, "invalid-input", "pool quota writer is closed");
5197
+ }
5198
+ // What read() and load() show: the stored map, then each queued reading of
5199
+ // the row still bound to it, in arrival order through the codec's merge.
5200
+ // A reading the codec now refuses is left out, as the flush drops it.
5201
+ overlayRow(row) {
5202
+ let next = row;
5203
+ for (const publication2 of this.pending.get(row.id) ?? []) {
5204
+ try {
5205
+ assertQuotaRow(row.id, publication2.attribution, row);
5206
+ next = {
5207
+ ...next,
5208
+ quota: mergedQuota(this.rt.ctx, row.id, next.quota, publication2.observation),
5209
+ needsFirstReading: false
5210
+ };
5211
+ } catch {
5212
+ }
5213
+ }
5214
+ return next;
5215
+ }
5216
+ overlay(rows) {
5217
+ return rows.map((row) => this.overlayRow(row));
5218
+ }
5219
+ schedule(delay3) {
5220
+ if (this.running || this.timer || !this.pending.size || this.stopped)
5221
+ return;
5222
+ this.timer = setTimeout(() => {
5223
+ this.timer = void 0;
5224
+ this.flush();
5225
+ }, delay3);
5226
+ if (!this.closed)
5227
+ this.timer.unref?.();
5228
+ }
5229
+ // Starts a flush now rather than at the coalescing timer or retry backoff;
5230
+ // a flush already running is left to finish.
5231
+ flushNow() {
5232
+ if (this.running)
5233
+ return;
5234
+ clearTimeout(this.timer);
5235
+ this.timer = void 0;
5236
+ this.flush();
5237
+ }
5238
+ flush() {
5239
+ if (this.running || this.stopped || !this.pending.size)
5240
+ return;
5241
+ const batch = [...this.pending.values()].flat();
5242
+ const ctx = {
5243
+ ...this.rt.ctx,
5244
+ storeLocks: this.rt.ctx.storeLocks.map((spec) => ({
5245
+ ...spec,
5246
+ timeoutMs: Math.min(spec.timeoutMs ?? this.rt.ctx.lockDefaults.timeoutMs, 100)
5247
+ }))
5248
+ };
5249
+ const locks = new LockStack(ctx.lockDefaults, ctx.lockEnv);
5250
+ this.running = (async () => {
5251
+ try {
5252
+ await withTransaction(ctx, locks, { writes: 0 }, { operation: "pull", rowId: void 0 }, async (tx) => {
5253
+ if (this.stopped)
5254
+ return;
5255
+ let changed = false;
5256
+ for (const publication2 of batch) {
5257
+ const { id, attribution, observation } = publication2;
5258
+ const witness = JSON.stringify([
5259
+ id,
5260
+ attribution.credentialEpoch,
5261
+ attribution.identity
5262
+ ]);
5263
+ try {
5264
+ tx.assertNotStaged(id);
5265
+ assertQuotaRow(id, attribution, tx.row(id));
5266
+ } catch (error) {
5267
+ if (!(error instanceof PoolOperationError))
5268
+ throw error;
5269
+ if (!this.warned.has(witness)) {
5270
+ this.warned.add(witness);
5271
+ this.warn("pool quota publication dropped; account binding changed", { id, kind: error.kind });
5272
+ }
5273
+ continue;
5274
+ }
5275
+ const entry = tx.entry(id);
5276
+ if (!entry)
5277
+ continue;
5278
+ let quota;
5279
+ try {
5280
+ quota = mergedQuota(ctx, id, entry.quota, observation);
5281
+ } catch (error) {
5282
+ const key = `codec:${witness}`;
5283
+ if (!this.warned.has(key)) {
5284
+ this.warned.add(key);
5285
+ this.warn("pool quota publication dropped; the quota codec refused it", {
5286
+ id,
5287
+ error: error instanceof Error ? error.message : String(error)
5288
+ });
5289
+ }
5290
+ continue;
5291
+ }
5292
+ tx.setEntry(id, { ...entry, quota, needsFirstReading: false });
5293
+ changed = true;
5294
+ }
5295
+ if (changed && !this.stopped)
5296
+ await tx.commitConfig();
5297
+ }, { completeTorn: false });
5298
+ const flushed = new Set(batch);
5299
+ for (const [id, queue2] of this.pending) {
5300
+ const rest = queue2.filter((publication2) => !flushed.has(publication2));
5301
+ if (rest.length)
5302
+ this.pending.set(id, rest);
5303
+ else
5304
+ this.pending.delete(id);
5305
+ }
5306
+ this.failures = 0;
5307
+ } catch (error) {
5308
+ if (!this.stopped && this.failures++ === 0)
5309
+ this.warn("pool quota publication delayed; retrying", {
5310
+ error: error instanceof Error ? error.message : String(error)
5311
+ });
5312
+ } finally {
5313
+ await locks.releaseAll();
5314
+ this.running = void 0;
5315
+ for (const wake of this.wake)
5316
+ wake();
5317
+ const delay3 = this.failures ? Math.min(5e3, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS;
5318
+ this.schedule(delay3);
5319
+ }
5320
+ })();
5321
+ }
5322
+ warn(message, data) {
5323
+ try {
5324
+ this.logger.warn(message, data);
5325
+ } catch {
5326
+ }
5327
+ }
5328
+ close() {
5329
+ if (this.closing)
5330
+ return this.closing;
5331
+ this.closed = true;
5332
+ this.closing = this.drain();
5333
+ return this.closing;
5334
+ }
5335
+ async drain() {
5336
+ clearTimeout(this.timer);
5337
+ this.timer = void 0;
5338
+ let deadline;
5339
+ let wake;
5340
+ const drained = new Promise((done) => {
5341
+ wake = () => {
5342
+ if (!this.pending.size)
5343
+ done();
5344
+ };
5345
+ this.wake.add(wake);
5346
+ wake();
5347
+ });
5348
+ try {
5349
+ this.flush();
5350
+ await Promise.race([
5351
+ drained,
5352
+ new Promise((done) => {
5353
+ deadline = setTimeout(done, Math.max(0, this.timeoutMs));
5354
+ })
5355
+ ]);
5356
+ } finally {
5357
+ this.stopped = true;
5358
+ clearTimeout(deadline);
5359
+ clearTimeout(this.timer);
5360
+ this.wake.delete(wake);
5361
+ if (this.pending.size)
5362
+ this.warn("pool quota drain timed out; pending readings left", {
5363
+ accounts: this.pending.size,
5364
+ readings: [...this.pending.values()].reduce((sum, queue2) => sum + queue2.length, 0)
5365
+ });
5366
+ this.pending.clear();
5367
+ for (const wake2 of this.wake)
5368
+ wake2();
5369
+ }
5370
+ }
5371
+ };
5372
+ }
5373
+ });
5374
+
4648
5375
  // ../core/dist/common-auth-embedded/store/refresh.js
4649
5376
  import { randomUUID as randomUUID11 } from "node:crypto";
4650
5377
  function requireRefreshable(id, row) {
@@ -5008,9 +5735,17 @@ function openPoolStore(options) {
5008
5735
  rowLockOptions: options.rowLockOptions ?? {},
5009
5736
  firePull: (id, reason) => pulls.fire(id, reason)
5010
5737
  };
5738
+ const quotaWriter = options.coalesceQuota ? new PoolQuotaWriter(rt, options.quotaDrainTimeoutMs) : void 0;
5739
+ const record3 = (id, attribution, observation) => quotaWriter ? quotaWriter.record(id, attribution, observation) : recordQuota(rt, id, attribution, observation);
5740
+ rt.publishQuota = record3;
5741
+ const overlay = (result) => {
5742
+ if (result.status === "ready" && quotaWriter)
5743
+ return { ...result, rows: quotaWriter.overlay(result.rows) };
5744
+ return result;
5745
+ };
5011
5746
  return {
5012
5747
  async load() {
5013
- const result = await readPool(ctx);
5748
+ const result = overlay(await readPool(ctx));
5014
5749
  if (result.status === "ready") {
5015
5750
  for (const row of result.rows)
5016
5751
  if ((row.candidate || row.torn && row.enabled) && row.type === "oauth" && row.needsFirstReading)
@@ -5019,7 +5754,7 @@ function openPoolStore(options) {
5019
5754
  return toLoad(result);
5020
5755
  },
5021
5756
  async read() {
5022
- return toLoad(await readPool(ctx));
5757
+ return toLoad(overlay(await readPool(ctx)));
5023
5758
  },
5024
5759
  async initialize(input2 = {}) {
5025
5760
  return { status: await initializePool(ctx, input2.dropKeys ?? []) };
@@ -5038,7 +5773,9 @@ function openPoolStore(options) {
5038
5773
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
5039
5774
  recordIdentity: (id, identity, attribution, callOptions) => recordRowIdentity(rt, id, identity, attribution, callOptions),
5040
5775
  refresh: (id, provider2, callOptions) => refreshRow(rt, id, provider2, callOptions),
5041
- recordQuota: (id, attribution, observation) => recordQuota(rt, id, attribution, observation),
5776
+ recordQuota: record3,
5777
+ close: () => quotaWriter?.close() ?? Promise.resolve(),
5778
+ dispose: () => quotaWriter?.close() ?? Promise.resolve(),
5042
5779
  requestReading: (id) => pulls.fire(id, "admission"),
5043
5780
  pullsSettled: () => pulls.settled()
5044
5781
  };
@@ -5052,6 +5789,7 @@ var init_pool = __esm({
5052
5789
  init_provider_state();
5053
5790
  init_publication();
5054
5791
  init_pull();
5792
+ init_quota_writer();
5055
5793
  init_refresh();
5056
5794
  init_refresh_lock();
5057
5795
  init_rows();
@@ -5445,578 +6183,155 @@ function selectStickyCandidate(input2) {
5445
6183
  return leftScore - rightScore || left.candidate.configuredOrder - right.candidate.configuredOrder || compareAccountIds(left.candidate.accountId, right.candidate.accountId);
5446
6184
  });
5447
6185
  const selected = weighted[0];
5448
- if (selected) {
5449
- return {
5450
- accountId: selected.candidate.accountId,
5451
- quotaCheckedAt: selected.quotaCheckedAt,
5452
- source: "weighted"
5453
- };
5454
- }
5455
- }
5456
- input2.onEmptyWeightedSet?.();
5457
- const fallback = [...eligibleCandidates].sort((left, right) => {
5458
- const leftHasCredits = (left.resetCreditsApplicable ?? 0) > 0 ? 1 : 0;
5459
- const rightHasCredits = (right.resetCreditsApplicable ?? 0) > 0 ? 1 : 0;
5460
- return rightHasCredits - leftHasCredits || left.configuredOrder - right.configuredOrder || compareAccountIds(left.accountId, right.accountId);
5461
- })[0];
5462
- if (!fallback) {
5463
- throw new Error("Cannot select a sticky candidate: input.candidates is empty");
5464
- }
5465
- return {
5466
- accountId: fallback.accountId,
5467
- quotaCheckedAt: snapshotCheckedAt(fallback.quota, fallback.quotaCheckedAt),
5468
- source: "mode-fallback"
5469
- };
5470
- }
5471
- function routeSticky(input2) {
5472
- const admission = admit(input2);
5473
- const admitted = new Map(admission.admitted.map((row) => [row.id, row]));
5474
- const refusals = new Map(admission.refused.map((r) => [r.id, r]));
5475
- const excluded = new Set(admission.excluded.map((row) => row.id));
5476
- const validIds = new Set(input2.rows.map((row) => row.id));
5477
- const pinValid = input2.pin !== void 0 && isPinValid(input2.pin, validIds, input2.identities?.get(input2.pin.accountId));
5478
- if (pinValid && input2.pin) {
5479
- const pinned = admitted.get(input2.pin.accountId);
5480
- if (pinned && input2.killswitch?.get(pinned.id) !== false) {
5481
- return {
5482
- outcome: "dispatch",
5483
- accountId: pinned.id,
5484
- source: "pin",
5485
- ...pinned.projection?.checkedAt === void 0 ? {} : { quotaCheckedAt: pinned.projection.checkedAt },
5486
- pin: { action: "retain" },
5487
- refusedSelections: [],
5488
- admission
5489
- };
5490
- }
5491
- }
5492
- const pinRefusal = input2.pin ? refusals.get(input2.pin.accountId) : void 0;
5493
- const pinMoves = pinValid && input2.pin !== void 0 && input2.refusedPinPolicy === "move-on-confirmed-exhaustion" && (input2.killswitch?.get(input2.pin.accountId) === false || pinRefusal?.reason === "exhausted" || pinRefusal?.reason === "budget-spent");
5494
- const reserveFor = (row) => {
5495
- const perRow = typeof input2.rowReservePercent === "function" ? input2.rowReservePercent(row) : input2.rowReservePercent?.get(row.id);
5496
- return perRow ?? input2.reservePercent ?? {};
5497
- };
5498
- const scope = input2.scope;
5499
- let candidates = input2.rows.map((row, configuredOrder) => ({ row, configuredOrder })).filter(({ row }) => !excluded.has(row.id)).map(({ row, configuredOrder }) => {
5500
- const killswitchPasses = input2.killswitch?.get(row.id);
5501
- const credits = input2.resetCreditsApplicable?.get(row.id);
5502
- return {
5503
- accountId: row.id,
5504
- quota: row.kind === "api-key" ? void 0 : admitted.get(row.id)?.projection ?? projectQuota(row.quota, scope),
5505
- reservePercent: reserveFor(row),
5506
- configuredOrder,
5507
- ...credits === void 0 ? {} : { resetCreditsApplicable: credits },
5508
- ...killswitchPasses === void 0 ? {} : { killswitchPasses }
5509
- };
5510
- });
5511
- const refusedSelections = [];
5512
- const unplaced = pinValid ? { action: "retain" } : input2.pin ? { action: "clear" } : { action: "none" };
5513
- while (candidates.length > 0) {
5514
- const selection = selectStickyCandidate({
5515
- candidates,
5516
- pendingBytes: input2.pendingBytes ?? /* @__PURE__ */ new Map(),
5517
- requestBytes: input2.requestBytes,
5518
- now: input2.now,
5519
- ...input2.onEmptyWeightedSet ? { onEmptyWeightedSet: input2.onEmptyWeightedSet } : {}
5520
- });
5521
- if (!selection)
5522
- break;
5523
- const refusal3 = refusals.get(selection.accountId);
5524
- if (refusal3) {
5525
- refusedSelections.push(refusal3);
5526
- candidates = candidates.filter((candidate) => candidate.accountId !== selection.accountId);
5527
- continue;
5528
- }
5529
- const identity = input2.identities?.get(selection.accountId);
5530
- return {
5531
- outcome: "dispatch",
5532
- accountId: selection.accountId,
5533
- source: selection.source,
5534
- ...selection.quotaCheckedAt === void 0 ? {} : { quotaCheckedAt: selection.quotaCheckedAt },
5535
- pin: pinValid && !pinMoves ? { action: "retain" } : {
5536
- action: "assign",
5537
- pin: {
5538
- accountId: selection.accountId,
5539
- inputBytes: input2.requestBytes,
5540
- ...identity === void 0 ? {} : { wireIdentity: identity },
5541
- ...selection.quotaCheckedAt === void 0 ? {} : { quotaCheckedAt: selection.quotaCheckedAt }
5542
- }
5543
- },
5544
- refusedSelections,
5545
- admission
5546
- };
5547
- }
5548
- return {
5549
- outcome: "no-admissible-account",
5550
- pin: unplaced,
5551
- refusedSelections,
5552
- admission
5553
- };
5554
- }
5555
- var QUOTA_STALENESS_MS, MIN_RESET_HOURS, MIN_WEIGHT;
5556
- var init_sticky = __esm({
5557
- "../core/dist/common-auth-embedded/routing/sticky.js"() {
5558
- "use strict";
5559
- init_projection();
5560
- init_admission();
5561
- init_pins();
5562
- QUOTA_STALENESS_MS = 15 * 6e4;
5563
- MIN_RESET_HOURS = 1 / 60;
5564
- MIN_WEIGHT = 1e-6;
5565
- }
5566
- });
5567
-
5568
- // ../core/dist/common-auth-embedded/routing/index.js
5569
- var routing_exports = {};
5570
- __export(routing_exports, {
5571
- DEFAULT_FORMER_MAIN_ID: () => DEFAULT_FORMER_MAIN_ID,
5572
- MIN_RESET_HOURS: () => MIN_RESET_HOURS,
5573
- MIN_WEIGHT: () => MIN_WEIGHT,
5574
- QUOTA_STALENESS_MS: () => QUOTA_STALENESS_MS,
5575
- admit: () => admit,
5576
- decideStickyBreak: () => decideStickyBreak,
5577
- defaultStickyStatusClass: () => defaultStickyStatusClass,
5578
- exclusionFor: () => exclusionFor,
5579
- isPinValid: () => isPinValid,
5580
- nextOrderedAttempt: () => nextOrderedAttempt,
5581
- orderForPlacement: () => orderForPlacement,
5582
- pendingBytesForPins: () => pendingBytesForPins,
5583
- resolveRoutingMode: () => resolveRoutingMode,
5584
- routeOrdered: () => routeOrdered,
5585
- routeSticky: () => routeSticky,
5586
- selectStickyCandidate: () => selectStickyCandidate,
5587
- snapshotCheckedAt: () => snapshotCheckedAt,
5588
- sustainableWindowWeight: () => sustainableWindowWeight
5589
- });
5590
- var init_routing = __esm({
5591
- "../core/dist/common-auth-embedded/routing/index.js"() {
5592
- "use strict";
5593
- init_admission();
5594
- init_ordered();
5595
- init_pins();
5596
- init_sticky();
5597
- }
5598
- });
5599
-
5600
- // ../core/dist/common-auth-embedded/logger/capture-sink.js
5601
- function createCaptureSink() {
5602
- const records = [];
5603
- const sink = (record3) => {
5604
- records.push(record3);
5605
- };
5606
- return {
5607
- records,
5608
- sink,
5609
- clear: () => {
5610
- records.length = 0;
5611
- }
5612
- };
5613
- }
5614
- var init_capture_sink = __esm({
5615
- "../core/dist/common-auth-embedded/logger/capture-sink.js"() {
5616
- "use strict";
5617
- }
5618
- });
5619
-
5620
- // ../core/dist/common-auth-embedded/logger/redact.js
5621
- function isError(value) {
5622
- return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
5623
- }
5624
- function createRedactor(options = {}) {
5625
- const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
5626
- function isSecretKey(key) {
5627
- const normalized = key.toLowerCase().replace(/[-_]/g, "");
5628
- return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
5629
- }
5630
- function errorEntries(error) {
5631
- const fields2 = error;
5632
- const entries = [
5633
- ["name", error.name],
5634
- ["message", error.message],
5635
- ["stack", error.stack]
5636
- ];
5637
- for (const key of ["code", "status", "cause"])
5638
- if (fields2[key] !== void 0)
5639
- entries.push([key, fields2[key]]);
5640
- const listed = new Set(entries.map(([key]) => key));
5641
- for (const entry of Object.entries(error))
5642
- if (!listed.has(entry[0]))
5643
- entries.push(entry);
5644
- return entries;
5645
- }
5646
- function walk(value, keys, seen, errorDepth = 0) {
5647
- if (typeof value === "string") {
5648
- return patterns.reduce((text2, pattern) => text2.replace(pattern, MASK), value);
5649
- }
5650
- if (!value || typeof value !== "object")
5651
- return value;
5652
- if (seen.has(value))
5653
- return "[Circular]";
5654
- seen.add(value);
5655
- try {
5656
- if (Array.isArray(value))
5657
- return value.map((item) => walk(item, keys, seen, errorDepth));
5658
- const error = isError(value);
5659
- if (error && errorDepth >= MAX_ERROR_DEPTH)
5660
- return "[Truncated]";
5661
- const childDepth = error ? errorDepth + 1 : errorDepth;
5662
- return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
5663
- key,
5664
- keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
5665
- ]));
5666
- } finally {
5667
- seen.delete(value);
5668
- }
5669
- }
5670
- return {
5671
- redact: (value) => walk(value, true, /* @__PURE__ */ new WeakSet()),
5672
- // Schema keys describe arguments, not credentials; only their string values are scrubbed.
5673
- redactStrings: (value) => walk(value, false, /* @__PURE__ */ new WeakSet())
5674
- };
5675
- }
5676
- var SECRET_KEY_EXACT, TOKEN_VALUE, MASK, MAX_ERROR_DEPTH, defaultRedactor, redact, redactStrings;
5677
- var init_redact = __esm({
5678
- "../core/dist/common-auth-embedded/logger/redact.js"() {
5679
- "use strict";
5680
- SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
5681
- TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
5682
- MASK = "***REDACTED***";
5683
- MAX_ERROR_DEPTH = 8;
5684
- defaultRedactor = createRedactor();
5685
- redact = defaultRedactor.redact;
5686
- redactStrings = defaultRedactor.redactStrings;
5687
- }
5688
- });
5689
-
5690
- // ../core/dist/common-auth-embedded/logger/engine.js
5691
- import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
5692
- import { open as open5 } from "node:fs/promises";
5693
- import { dirname as dirname8, resolve as resolve3 } from "node:path";
5694
- function chmodPrivate(path5) {
5695
- try {
5696
- chmodSync(path5, 384);
5697
- } catch {
5698
- }
5699
- }
5700
- function rotateIfNeeded(f) {
5701
- try {
5702
- if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
5703
- return;
5704
- for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
5705
- if (existsSync(`${f}.${i}`)) {
5706
- const rotated2 = `${f}.${i + 1}`;
5707
- renameSync(`${f}.${i}`, rotated2);
5708
- chmodPrivate(rotated2);
5709
- }
5710
- }
5711
- const rotated = `${f}.1`;
5712
- renameSync(f, rotated);
5713
- chmodPrivate(rotated);
5714
- } catch {
5715
- }
5716
- }
5717
- async function closeWindowsFile(sink) {
5718
- const { file, handle } = sink;
5719
- sink.file = void 0;
5720
- sink.handle = void 0;
5721
- if (file && handle)
5722
- await privateOperation(file, "log-close", () => handle.close());
5723
- }
5724
- async function openWindowsFile(sink, file) {
5725
- await ensurePrivateDirectory(dirname8(file));
5726
- try {
5727
- await verifyPrivate(file, "file", true);
5728
- } catch (error) {
5729
- if (error.code !== "ENOENT")
5730
- throw error;
5731
- try {
5732
- await createPrivateBytes(file, "");
5733
- } catch (creationError) {
5734
- if (creationError.code !== "EEXIST")
5735
- throw creationError;
5736
- await verifyPrivate(file, "file", true);
5737
- }
5738
- }
5739
- sink.handle = await privateOperation(file, "log-open", () => open5(file, "a"));
5740
- sink.file = file;
5741
- return sink.handle;
5742
- }
5743
- async function flushWindowsFile(sink, file, text2) {
5744
- file = resolve3(file);
5745
- try {
5746
- if (sink.file !== file)
5747
- await closeWindowsFile(sink);
5748
- let handle = sink.handle ?? await openWindowsFile(sink, file);
5749
- const info = await privateOperation(file, "log-stat", () => handle.stat());
5750
- if (info.size >= MAX_BYTES) {
5751
- await closeWindowsFile(sink);
5752
- for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
5753
- const source = i === 0 ? file : `${file}.${i}`;
5754
- const target = `${file}.${i + 1}`;
5755
- try {
5756
- await verifyPrivate(source, "file", true);
5757
- } catch (error) {
5758
- if (error.code === "ENOENT")
5759
- continue;
5760
- throw error;
5761
- }
5762
- try {
5763
- await verifyPrivate(target, "file", true);
5764
- } catch (error) {
5765
- if (error.code !== "ENOENT")
5766
- throw error;
5767
- }
5768
- await replaceWindowsFile(source, target);
5769
- await verifyPrivate(target, "file");
5770
- }
5771
- handle = await openWindowsFile(sink, file);
5772
- }
5773
- await privateOperation(file, "log-append", () => handle.appendFile(text2, "utf8"));
5774
- } catch (error) {
5775
- await closeWindowsFile(sink).catch(() => {
5776
- });
5777
- throw error;
5778
- }
5779
- }
5780
- function safeSerialize(data) {
5781
- try {
5782
- return ` ${JSON.stringify(data)}`;
5783
- } catch {
5784
- return " [unserializable]";
5785
- }
5786
- }
5787
- function createEngine(options) {
5788
- let logFileSource;
5789
- let initLevelSource;
5790
- let runtimeLevel;
5791
- let redactor = createRedactor();
5792
- let captureSink;
5793
- let buffer = [];
5794
- let timer;
5795
- let orderedSink = Promise.resolve();
5796
- let sinkError;
5797
- const windowsFile = {};
5798
- function queueWindows(operation) {
5799
- const next = orderedSink.then(operation);
5800
- orderedSink = next.catch((error) => {
5801
- sinkError = error;
5802
- });
5803
- return next;
5804
- }
5805
- function configure(next) {
5806
- if (windowsPrivateFiles && next.file !== logFileSource)
5807
- void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
5808
- });
5809
- logFileSource = next.file;
5810
- initLevelSource = next.level;
5811
- redactor = createRedactor(next);
5812
- captureSink = next.captureSink;
5813
- }
5814
- function setLogLevel3(l) {
5815
- if (l === void 0 || l in ORDER)
5816
- runtimeLevel = l;
5817
- }
5818
- function logFilePath() {
5819
- if (logFileSource === void 0)
5820
- return void 0;
5821
- const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
5822
- return resolved || void 0;
5823
- }
5824
- function configuredLevel() {
5825
- if (runtimeLevel)
5826
- return runtimeLevel;
5827
- const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
5828
- if (floor && floor in ORDER)
5829
- return floor;
5830
- return "info";
5831
- }
5832
- function flushLogs3(close = true) {
5833
- if (timer) {
5834
- clearTimeout(timer);
5835
- timer = void 0;
5836
- }
5837
- if (!buffer.length) {
5838
- if (windowsPrivateFiles)
5839
- return queueWindows(async () => {
5840
- if (close)
5841
- await closeWindowsFile(windowsFile);
5842
- if (sinkError)
5843
- throw sinkError;
5844
- });
5845
- return;
5846
- }
5847
- let file;
5848
- try {
5849
- file = logFilePath();
5850
- } catch {
5851
- buffer = [];
5852
- if (windowsPrivateFiles && close)
5853
- return queueWindows(() => closeWindowsFile(windowsFile));
5854
- return;
5855
- }
5856
- const text2 = buffer.join("");
5857
- buffer = [];
5858
- if (!file) {
5859
- if (windowsPrivateFiles && close)
5860
- return queueWindows(() => closeWindowsFile(windowsFile));
5861
- return;
5862
- }
5863
- if (windowsPrivateFiles) {
5864
- return queueWindows(async () => {
5865
- try {
5866
- await flushWindowsFile(windowsFile, file, text2);
5867
- } finally {
5868
- if (close)
5869
- await closeWindowsFile(windowsFile);
5870
- }
5871
- });
5872
- }
5873
- try {
5874
- rotateIfNeeded(file);
5875
- if (existsSync(file))
5876
- chmodPrivate(file);
5877
- appendFileSync(file, text2, { encoding: "utf8", mode: 384 });
5878
- } catch {
6186
+ if (selected) {
6187
+ return {
6188
+ accountId: selected.candidate.accountId,
6189
+ quotaCheckedAt: selected.quotaCheckedAt,
6190
+ source: "weighted"
6191
+ };
5879
6192
  }
5880
6193
  }
5881
- function schedule2() {
5882
- if (!timer)
5883
- timer = setTimeout(() => {
5884
- timer = void 0;
5885
- const flushed = flushLogs3(false);
5886
- if (flushed instanceof Promise)
5887
- void flushed.catch(() => {
5888
- });
5889
- }, 500);
6194
+ input2.onEmptyWeightedSet?.();
6195
+ const fallback = [...eligibleCandidates].sort((left, right) => {
6196
+ const leftHasCredits = (left.resetCreditsApplicable ?? 0) > 0 ? 1 : 0;
6197
+ const rightHasCredits = (right.resetCreditsApplicable ?? 0) > 0 ? 1 : 0;
6198
+ return rightHasCredits - leftHasCredits || left.configuredOrder - right.configuredOrder || compareAccountIds(left.accountId, right.accountId);
6199
+ })[0];
6200
+ if (!fallback) {
6201
+ throw new Error("Cannot select a sticky candidate: input.candidates is empty");
5890
6202
  }
5891
- function emit(channel, level, message, data) {
5892
- if (logFileSource === void 0 && captureSink === void 0)
5893
- return;
5894
- try {
5895
- if (ORDER[level] > ORDER[configuredLevel()])
5896
- return;
5897
- const scrubbedMessage = redactor.redactStrings(message);
5898
- let scrubbedData;
5899
- try {
5900
- scrubbedData = redactor.redact(data);
5901
- } catch {
5902
- scrubbedData = "[unserializable]";
5903
- }
5904
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${level.toUpperCase()} [${channel}] ${scrubbedMessage}` + (data === void 0 ? "" : safeSerialize(scrubbedData)) + "\n";
5905
- try {
5906
- captureSink?.({
5907
- channel,
5908
- level,
5909
- message: scrubbedMessage,
5910
- data: scrubbedData
5911
- });
5912
- } catch {
5913
- }
5914
- if (logFileSource === void 0)
5915
- return;
5916
- buffer.push(line);
5917
- if (buffer.length >= 50) {
5918
- const flushed = flushLogs3(false);
5919
- if (flushed instanceof Promise)
5920
- void flushed.catch(() => {
5921
- });
5922
- } else
5923
- schedule2();
5924
- } catch {
6203
+ return {
6204
+ accountId: fallback.accountId,
6205
+ quotaCheckedAt: snapshotCheckedAt(fallback.quota, fallback.quotaCheckedAt),
6206
+ source: "mode-fallback"
6207
+ };
6208
+ }
6209
+ function routeSticky(input2) {
6210
+ const admission = admit(input2);
6211
+ const admitted = new Map(admission.admitted.map((row) => [row.id, row]));
6212
+ const refusals = new Map(admission.refused.map((r) => [r.id, r]));
6213
+ const excluded = new Set(admission.excluded.map((row) => row.id));
6214
+ const validIds = new Set(input2.rows.map((row) => row.id));
6215
+ const pinValid = input2.pin !== void 0 && isPinValid(input2.pin, validIds, input2.identities?.get(input2.pin.accountId));
6216
+ if (pinValid && input2.pin) {
6217
+ const pinned = admitted.get(input2.pin.accountId);
6218
+ if (pinned && input2.killswitch?.get(pinned.id) !== false) {
6219
+ return {
6220
+ outcome: "dispatch",
6221
+ accountId: pinned.id,
6222
+ source: "pin",
6223
+ ...pinned.projection?.checkedAt === void 0 ? {} : { quotaCheckedAt: pinned.projection.checkedAt },
6224
+ pin: { action: "retain" },
6225
+ refusedSelections: [],
6226
+ admission
6227
+ };
5925
6228
  }
5926
6229
  }
5927
- function createLogger5(channel) {
6230
+ const pinRefusal = input2.pin ? refusals.get(input2.pin.accountId) : void 0;
6231
+ const pinMoves = pinValid && input2.pin !== void 0 && input2.refusedPinPolicy === "move-on-confirmed-exhaustion" && (input2.killswitch?.get(input2.pin.accountId) === false || pinRefusal?.reason === "exhausted" || pinRefusal?.reason === "budget-spent");
6232
+ const reserveFor = (row) => {
6233
+ const perRow = typeof input2.rowReservePercent === "function" ? input2.rowReservePercent(row) : input2.rowReservePercent?.get(row.id);
6234
+ return perRow ?? input2.reservePercent ?? {};
6235
+ };
6236
+ const scope = input2.scope;
6237
+ let candidates = input2.rows.map((row, configuredOrder) => ({ row, configuredOrder })).filter(({ row }) => !excluded.has(row.id)).map(({ row, configuredOrder }) => {
6238
+ const killswitchPasses = input2.killswitch?.get(row.id);
6239
+ const credits = input2.resetCreditsApplicable?.get(row.id);
5928
6240
  return {
5929
- error: (m, d) => emit(channel, "error", m, d),
5930
- warn: (m, d) => emit(channel, "warn", m, d),
5931
- info: (m, d) => emit(channel, "info", m, d),
5932
- debug: (m, d) => emit(channel, "debug", m, d),
5933
- trace: (m, d) => emit(channel, "trace", m, d)
6241
+ accountId: row.id,
6242
+ quota: row.kind === "api-key" ? void 0 : admitted.get(row.id)?.projection ?? projectQuota(row.quota, scope),
6243
+ reservePercent: reserveFor(row),
6244
+ configuredOrder,
6245
+ ...credits === void 0 ? {} : { resetCreditsApplicable: credits },
6246
+ ...killswitchPasses === void 0 ? {} : { killswitchPasses }
5934
6247
  };
5935
- }
5936
- function reset() {
5937
- if (windowsPrivateFiles)
5938
- void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
5939
- });
5940
- sinkError = void 0;
5941
- buffer = [];
5942
- if (timer) {
5943
- clearTimeout(timer);
5944
- timer = void 0;
6248
+ });
6249
+ const refusedSelections = [];
6250
+ const unplaced = pinValid ? { action: "retain" } : input2.pin ? { action: "clear" } : { action: "none" };
6251
+ while (candidates.length > 0) {
6252
+ const selection = selectStickyCandidate({
6253
+ candidates,
6254
+ pendingBytes: input2.pendingBytes ?? /* @__PURE__ */ new Map(),
6255
+ requestBytes: input2.requestBytes,
6256
+ now: input2.now,
6257
+ ...input2.onEmptyWeightedSet ? { onEmptyWeightedSet: input2.onEmptyWeightedSet } : {}
6258
+ });
6259
+ if (!selection)
6260
+ break;
6261
+ const refusal3 = refusals.get(selection.accountId);
6262
+ if (refusal3) {
6263
+ refusedSelections.push(refusal3);
6264
+ candidates = candidates.filter((candidate) => candidate.accountId !== selection.accountId);
6265
+ continue;
5945
6266
  }
5946
- logFileSource = void 0;
5947
- initLevelSource = void 0;
5948
- runtimeLevel = void 0;
5949
- redactor = createRedactor();
5950
- captureSink = void 0;
6267
+ const identity = input2.identities?.get(selection.accountId);
6268
+ return {
6269
+ outcome: "dispatch",
6270
+ accountId: selection.accountId,
6271
+ source: selection.source,
6272
+ ...selection.quotaCheckedAt === void 0 ? {} : { quotaCheckedAt: selection.quotaCheckedAt },
6273
+ pin: pinValid && !pinMoves ? { action: "retain" } : {
6274
+ action: "assign",
6275
+ pin: {
6276
+ accountId: selection.accountId,
6277
+ inputBytes: input2.requestBytes,
6278
+ ...identity === void 0 ? {} : { wireIdentity: identity },
6279
+ ...selection.quotaCheckedAt === void 0 ? {} : { quotaCheckedAt: selection.quotaCheckedAt }
6280
+ }
6281
+ },
6282
+ refusedSelections,
6283
+ admission
6284
+ };
5951
6285
  }
5952
- if (options)
5953
- configure(options);
5954
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3, reset };
5955
- }
5956
- function createLoggerInstance(options) {
5957
- const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine(options);
5958
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
5959
- }
5960
- function initLogger(options) {
5961
- defaultEngine.configure(options);
5962
- const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = defaultEngine;
5963
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
5964
- }
5965
- function setLogLevel(l) {
5966
- defaultEngine.setLogLevel(l);
5967
- }
5968
- function flushLogs() {
5969
- return defaultEngine.flushLogs();
5970
- }
5971
- function createLogger2(channel) {
5972
- return defaultEngine.createLogger(channel);
5973
- }
5974
- async function flushForTest() {
5975
- return defaultEngine.flushLogs();
5976
- }
5977
- function resetLoggerForTest() {
5978
- defaultEngine.reset();
6286
+ return {
6287
+ outcome: "no-admissible-account",
6288
+ pin: unplaced,
6289
+ refusedSelections,
6290
+ admission
6291
+ };
5979
6292
  }
5980
- var ORDER, MAX_BYTES, ROTATE_KEEP, defaultEngine;
5981
- var init_engine = __esm({
5982
- "../core/dist/common-auth-embedded/logger/engine.js"() {
6293
+ var QUOTA_STALENESS_MS, MIN_RESET_HOURS, MIN_WEIGHT;
6294
+ var init_sticky = __esm({
6295
+ "../core/dist/common-auth-embedded/routing/sticky.js"() {
5983
6296
  "use strict";
5984
- init_private_files();
5985
- init_redact();
5986
- ORDER = {
5987
- error: 0,
5988
- warn: 1,
5989
- info: 2,
5990
- debug: 3,
5991
- trace: 4
5992
- };
5993
- MAX_BYTES = 5 * 1024 * 1024;
5994
- ROTATE_KEEP = 3;
5995
- defaultEngine = createEngine();
6297
+ init_projection();
6298
+ init_admission();
6299
+ init_pins();
6300
+ QUOTA_STALENESS_MS = 15 * 6e4;
6301
+ MIN_RESET_HOURS = 1 / 60;
6302
+ MIN_WEIGHT = 1e-6;
5996
6303
  }
5997
6304
  });
5998
6305
 
5999
- // ../core/dist/common-auth-embedded/logger/index.js
6000
- var logger_exports = {};
6001
- __export(logger_exports, {
6002
- createCaptureSink: () => createCaptureSink,
6003
- createLogger: () => createLogger2,
6004
- createLoggerInstance: () => createLoggerInstance,
6005
- createRedactor: () => createRedactor,
6006
- flushForTest: () => flushForTest,
6007
- flushLogs: () => flushLogs,
6008
- initLogger: () => initLogger,
6009
- redact: () => redact,
6010
- redactStrings: () => redactStrings,
6011
- resetLoggerForTest: () => resetLoggerForTest,
6012
- setLogLevel: () => setLogLevel
6306
+ // ../core/dist/common-auth-embedded/routing/index.js
6307
+ var routing_exports = {};
6308
+ __export(routing_exports, {
6309
+ DEFAULT_FORMER_MAIN_ID: () => DEFAULT_FORMER_MAIN_ID,
6310
+ MIN_RESET_HOURS: () => MIN_RESET_HOURS,
6311
+ MIN_WEIGHT: () => MIN_WEIGHT,
6312
+ QUOTA_STALENESS_MS: () => QUOTA_STALENESS_MS,
6313
+ admit: () => admit,
6314
+ decideStickyBreak: () => decideStickyBreak,
6315
+ defaultStickyStatusClass: () => defaultStickyStatusClass,
6316
+ exclusionFor: () => exclusionFor,
6317
+ isPinValid: () => isPinValid,
6318
+ nextOrderedAttempt: () => nextOrderedAttempt,
6319
+ orderForPlacement: () => orderForPlacement,
6320
+ pendingBytesForPins: () => pendingBytesForPins,
6321
+ resolveRoutingMode: () => resolveRoutingMode,
6322
+ routeOrdered: () => routeOrdered,
6323
+ routeSticky: () => routeSticky,
6324
+ selectStickyCandidate: () => selectStickyCandidate,
6325
+ snapshotCheckedAt: () => snapshotCheckedAt,
6326
+ sustainableWindowWeight: () => sustainableWindowWeight
6013
6327
  });
6014
- var init_logger = __esm({
6015
- "../core/dist/common-auth-embedded/logger/index.js"() {
6328
+ var init_routing = __esm({
6329
+ "../core/dist/common-auth-embedded/routing/index.js"() {
6016
6330
  "use strict";
6017
- init_capture_sink();
6018
- init_engine();
6019
- init_redact();
6331
+ init_admission();
6332
+ init_ordered();
6333
+ init_pins();
6334
+ init_sticky();
6020
6335
  }
6021
6336
  });
6022
6337
 
@@ -6313,13 +6628,16 @@ function addedText(name, result) {
6313
6628
  function failureMessage(error) {
6314
6629
  return projectFailure(error).text;
6315
6630
  }
6316
- async function snapshot(store) {
6631
+ async function snapshot(options) {
6632
+ const { store } = options;
6317
6633
  const load = await store.read();
6318
6634
  const read = await store.readSettings();
6635
+ const vault = await options.routing?.vaultOrder?.();
6319
6636
  return {
6320
6637
  load,
6321
6638
  rows: distinctRows(load),
6322
- settings: read.status === "error" ? {} : read.settings
6639
+ settings: read.status === "error" ? {} : read.settings,
6640
+ ...vault ? { vault } : {}
6323
6641
  };
6324
6642
  }
6325
6643
  function accountView(row, options) {
@@ -6526,6 +6844,57 @@ function quotaSection2(options, snap) {
6526
6844
  }
6527
6845
  };
6528
6846
  }
6847
+ async function reorderVault(vault, order) {
6848
+ try {
6849
+ return await vault.reorder(order);
6850
+ } catch (error) {
6851
+ if (error instanceof Error && error.name === "ClaustrumConsumerError" && error.kind === "invalid-order")
6852
+ throw new CommandError("vault-invalid-order", error.message, {
6853
+ cause: error
6854
+ });
6855
+ throw error;
6856
+ }
6857
+ }
6858
+ function invalidVaultOrder(message) {
6859
+ return new CommandError("vault-invalid-order", message);
6860
+ }
6861
+ function vaultNames(vault) {
6862
+ const rows = vault.rows.map((row) => ({
6863
+ id: row.id,
6864
+ label: row.label.trim() || row.id
6865
+ }));
6866
+ const matches2 = (entry) => rows.filter((row) => row.id === entry || row.label === entry);
6867
+ return {
6868
+ ids: rows.map((row) => row.id),
6869
+ nameOf: (id) => rows.find((row) => row.id === id)?.label ?? id,
6870
+ /**
6871
+ * What the order input starts with for an account: its label when
6872
+ * typing that label back names this account alone, else its route id
6873
+ * (two accounts sharing a label, or a label with a comma or line break
6874
+ * in it, either of which would split it into two entries).
6875
+ */
6876
+ entryOf: (id) => {
6877
+ const row = rows.find((entry) => entry.id === id);
6878
+ return row && !/[,\n]/.test(row.label) && matches2(row.label).length === 1 ? row.label : id;
6879
+ },
6880
+ /** The route ids the typed entries name, in order; refuses before any write. */
6881
+ resolve: (entries) => {
6882
+ const ids = [];
6883
+ for (const entry of entries) {
6884
+ const found = matches2(entry);
6885
+ if (found.length === 0)
6886
+ throw invalidVaultOrder(`"${entry}" is not a vault account.`);
6887
+ if (found.length > 1)
6888
+ throw invalidVaultOrder(`"${entry}" matches more than one vault account; enter those accounts by route id.`);
6889
+ const id = found[0].id;
6890
+ if (ids.includes(id))
6891
+ throw invalidVaultOrder(`"${entry}" names an account already in the order.`);
6892
+ ids.push(id);
6893
+ }
6894
+ return ids;
6895
+ }
6896
+ };
6897
+ }
6529
6898
  function routingSection2(options, snap) {
6530
6899
  const { store, extraLocks } = options;
6531
6900
  const locks = extraLocks ? { extraLocks } : {};
@@ -6537,14 +6906,16 @@ function routingSection2(options, snap) {
6537
6906
  const raw = record(snap.settings.routing).mode;
6538
6907
  const current = typeof raw === "string" && choices.some((choice) => choice.value === raw) ? raw : "ordered";
6539
6908
  const resolved = resolveRoutingMode(current);
6540
- const ids = snap.rows.map((row) => row.id);
6909
+ const vault = snap.vault ? vaultNames(snap.vault) : void 0;
6910
+ const ids = vault ? vault.ids : snap.rows.map((row) => row.id);
6911
+ const nameOf = (id) => vault ? vault.nameOf(id) : id;
6541
6912
  const tried = orderForPlacement(ids, resolved.placement, options.routing?.formerMainId ?? DEFAULT_FORMER_MAIN_ID);
6542
6913
  const label = choices.find((choice) => choice.value === current)?.label ?? current;
6543
6914
  const lines = [`Mode: ${label}`];
6544
6915
  if (ids.length > 0)
6545
- lines.push(`Roster order: ${ids.join(", ")}`);
6916
+ lines.push(`${vault ? "Vault account order" : "Roster order"}: ${ids.map(nameOf).join(", ")}`);
6546
6917
  if (resolved.mode === "ordered" && tried.join() !== ids.join())
6547
- lines.push(`Tried in order: ${tried.join(", ")}`);
6918
+ lines.push(`Tried in order: ${tried.map(nameOf).join(", ")}`);
6548
6919
  const actions = [
6549
6920
  {
6550
6921
  id: "mode",
@@ -6572,15 +6943,16 @@ function routingSection2(options, snap) {
6572
6943
  {
6573
6944
  kind: "text",
6574
6945
  id: "order",
6575
- label: "Account ids, first to last",
6576
- value: ids.join(", "),
6946
+ label: vault ? "Vault accounts, first to last, separated by commas" : "Account ids, first to last",
6947
+ value: vault ? ids.map(vault.entryOf).join(", ") : ids.join(", "),
6577
6948
  required: true
6578
6949
  }
6579
6950
  ],
6580
6951
  run: async ({ values }) => {
6581
- const order = String(values.order).split(/[\s,]+/).filter((id) => id.length > 0);
6582
- const result = await store.reorder(order, locks);
6583
- return result.outcome === "unchanged" ? "The order is unchanged." : `Order set to ${result.ids.join(", ")}.`;
6952
+ const text2 = String(values.order);
6953
+ const entries = text2.split(vault ? /[,\n]+/ : /[\s,]+/).map((entry) => entry.trim()).filter((entry) => entry.length > 0);
6954
+ const result = snap.vault && vault ? await reorderVault(snap.vault, vault.resolve(entries)) : await store.reorder(entries, locks);
6955
+ return result.outcome === "unchanged" ? "The order is unchanged." : `Order set to ${result.ids.map(nameOf).join(", ")}.`;
6584
6956
  }
6585
6957
  });
6586
6958
  return {
@@ -6709,7 +7081,7 @@ function limitsSection2(options, snap) {
6709
7081
  };
6710
7082
  }
6711
7083
  async function builtinSections(options) {
6712
- const snap = await snapshot(options.store);
7084
+ const snap = await snapshot(options);
6713
7085
  return [
6714
7086
  accountsSection2(options, snap),
6715
7087
  quotaSection2(options, snap),
@@ -8862,7 +9234,7 @@ var init_any_signal = __esm({
8862
9234
  import { createHash as createHash6, randomBytes as randomBytes4, randomUUID as randomUUID12 } from "node:crypto";
8863
9235
  import { constants as fsConstants } from "node:fs";
8864
9236
  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";
9237
+ import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve5 } from "node:path";
8866
9238
  import { ClaustrumCredentialError as ClaustrumCredentialError2, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8867
9239
  function classifyEnrollmentError(error) {
8868
9240
  if (!(error instanceof ClaustrumCredentialError2))
@@ -8888,7 +9260,7 @@ function getClaustrumEnrollmentPaths(tokenPath) {
8888
9260
  const extension = extname(tokenPath) || ".json";
8889
9261
  const stem = basename3(tokenPath, extname(tokenPath));
8890
9262
  return {
8891
- statePath: join5(dirname9(tokenPath), `${stem}-state${extension}`),
9263
+ statePath: join6(dirname9(tokenPath), `${stem}-state${extension}`),
8892
9264
  tokenPath
8893
9265
  };
8894
9266
  }
@@ -8896,7 +9268,7 @@ function hostEnrollmentPaths(input2) {
8896
9268
  const override = input2.override?.trim();
8897
9269
  if (override && !isAbsolute2(override) && !input2.cwd)
8898
9270
  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`);
9271
+ const tokenPath = override ? isAbsolute2(override) ? override : resolve5(input2.cwd, override) : join6(input2.stateDir, `${input2.host}-enrollment.json`);
8900
9272
  return getClaustrumEnrollmentPaths(tokenPath);
8901
9273
  }
8902
9274
  function isRecord6(value) {
@@ -9129,7 +9501,7 @@ async function writeStateAtomic(path5, state, ancestorOptions = {}) {
9129
9501
  }
9130
9502
  if (windowsPrivateFiles)
9131
9503
  return writePrivateAtomic(path5, bytes);
9132
- const temporary = join5(parent, `.${basename3(path5)}.${process.pid}.${randomUUID12()}.tmp`);
9504
+ const temporary = join6(parent, `.${basename3(path5)}.${process.pid}.${randomUUID12()}.tmp`);
9133
9505
  let descriptor;
9134
9506
  let created = false;
9135
9507
  try {
@@ -9306,7 +9678,7 @@ async function disconnectClaustrumEnrollment(paths, proposedName) {
9306
9678
  await lock.release();
9307
9679
  }
9308
9680
  }
9309
- var ENROLLMENT_SCHEMA, ENROLLMENT_FILE_MAX_BYTES, ENROLLMENT_LOCK_TTL_MS, TOKEN_RE, TERMINAL_ENROLLMENT_CODES, RETRYABLE_ENROLLMENT_CODES, ClaustrumEnrollmentManager;
9681
+ var ENROLLMENT_SCHEMA, ENROLLMENT_FILE_MAX_BYTES, ENROLLMENT_LOCK_TTL_MS, TOKEN_RE, UNSUPPORTED_ENROLLMENT_CODE, TERMINAL_ENROLLMENT_CODES, RETRYABLE_ENROLLMENT_CODES, ClaustrumEnrollmentManager;
9310
9682
  var init_enrollment = __esm({
9311
9683
  "../core/dist/common-auth-embedded/claustrum/enrollment.js"() {
9312
9684
  "use strict";
@@ -9317,7 +9689,13 @@ var init_enrollment = __esm({
9317
9689
  ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
9318
9690
  ENROLLMENT_LOCK_TTL_MS = 3e4;
9319
9691
  TOKEN_RE = /^[0-9a-f]{64}$/;
9692
+ UNSUPPORTED_ENROLLMENT_CODE = "unknown_method";
9320
9693
  TERMINAL_ENROLLMENT_CODES = /* @__PURE__ */ new Set([
9694
+ // The daemon's answer to an operation it does not implement: a vault built
9695
+ // before the enrollment ceremony. It arrives as a transport Error frame with
9696
+ // no class, which claustrum-client before 0.13.0 labels transient/retry, but
9697
+ // asking again can never succeed.
9698
+ UNSUPPORTED_ENROLLMENT_CODE,
9321
9699
  "invalid_params",
9322
9700
  "pending_exists",
9323
9701
  "not_found",
@@ -9451,6 +9829,18 @@ var init_enrollment = __esm({
9451
9829
  retryCode: refusal3.code
9452
9830
  };
9453
9831
  }
9832
+ if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE) {
9833
+ await lock.assertOwned();
9834
+ await unlink6(this.#paths.statePath).catch((cause) => {
9835
+ if (cause.code !== "ENOENT")
9836
+ throw cause;
9837
+ });
9838
+ return {
9839
+ state: "unavailable",
9840
+ proposedName: state.proposedName,
9841
+ code: refusal3.code
9842
+ };
9843
+ }
9454
9844
  return this.#block(state, refusal3.code);
9455
9845
  }
9456
9846
  }
@@ -10126,6 +10516,59 @@ var init_custody = __esm({
10126
10516
  }
10127
10517
  });
10128
10518
 
10519
+ // ../core/dist/common-auth-embedded/quota/pending.js
10520
+ function quotaFields(publication2, witness = "") {
10521
+ const result = /* @__PURE__ */ new Map();
10522
+ const { observation } = publication2;
10523
+ const add = (key, at, part) => result.set(`${witness}:${key}`, {
10524
+ at,
10525
+ order: 0,
10526
+ publication: { ...publication2, observation: part }
10527
+ });
10528
+ const keyFor = (scope, label) => JSON.stringify([scope ?? "all", label]);
10529
+ const read = /* @__PURE__ */ new Set();
10530
+ for (const reading of observation.readings ?? []) {
10531
+ const key = keyFor(reading.scope, reading.label);
10532
+ read.add(key);
10533
+ add(key, observation.checkedAt, {
10534
+ checkedAt: observation.checkedAt,
10535
+ readings: [{ ...reading }]
10536
+ });
10537
+ }
10538
+ for (const pair of observation.coverage ?? []) {
10539
+ const key = keyFor(pair.scope, pair.label);
10540
+ if (!read.has(key))
10541
+ add(key, observation.checkedAt, {
10542
+ checkedAt: observation.checkedAt,
10543
+ coverage: [{ ...pair }]
10544
+ });
10545
+ }
10546
+ if (observation.budget)
10547
+ add("budget", observation.checkedAt, {
10548
+ checkedAt: observation.checkedAt,
10549
+ budget: { ...observation.budget }
10550
+ });
10551
+ for (const [name, counter] of Object.entries(observation.counters ?? {})) {
10552
+ add(`counter:${name}`, counter.checkedAt, {
10553
+ checkedAt: observation.checkedAt,
10554
+ counters: { [name]: { ...counter } }
10555
+ });
10556
+ }
10557
+ if (observation.credits)
10558
+ add("credits", observation.credits.checkedAt, {
10559
+ checkedAt: observation.checkedAt,
10560
+ credits: { ...observation.credits }
10561
+ });
10562
+ if (!result.size)
10563
+ add("empty", observation.checkedAt, { checkedAt: observation.checkedAt });
10564
+ return result;
10565
+ }
10566
+ var init_pending = __esm({
10567
+ "../core/dist/common-auth-embedded/quota/pending.js"() {
10568
+ "use strict";
10569
+ }
10570
+ });
10571
+
10129
10572
  // ../core/dist/common-auth-embedded/claustrum/interlock.js
10130
10573
  function matches(entry, credentialId, accountIdentity) {
10131
10574
  if (entry.accountIdentity !== void 0 && accountIdentity !== void 0)
@@ -10426,6 +10869,52 @@ function acceptVaultRoute(path5, routeId) {
10426
10869
  };
10427
10870
  });
10428
10871
  }
10872
+ function invalidOrder(message) {
10873
+ return new ClaustrumConsumerError("invalid-order", message);
10874
+ }
10875
+ function vaultOrderProblem(rows, routeIds) {
10876
+ if (!Array.isArray(routeIds))
10877
+ return "route ids must be an array of route ids";
10878
+ const rosterIds = new Set(rows.map((row) => row.routeId));
10879
+ const given = /* @__PURE__ */ new Set();
10880
+ for (const id of routeIds) {
10881
+ if (typeof id !== "string")
10882
+ return "route ids must be an array of route ids";
10883
+ if (given.has(id))
10884
+ return `route id ${id} appears more than once`;
10885
+ if (!rosterIds.has(id))
10886
+ return `route id ${id} is not in the roster`;
10887
+ given.add(id);
10888
+ }
10889
+ const missing = [...rosterIds].filter((id) => !given.has(id)).length;
10890
+ if (missing > 0)
10891
+ return `the order leaves out ${missing} roster route id${missing === 1 ? "" : "s"}`;
10892
+ return void 0;
10893
+ }
10894
+ function reorderVaultRoster(path5, routeIds, options = {}) {
10895
+ return mutateVaultRoster(path5, (current) => {
10896
+ const rows = current?.rows ?? [];
10897
+ const problem = vaultOrderProblem(rows, routeIds);
10898
+ if (problem)
10899
+ throw invalidOrder(problem);
10900
+ const byId = /* @__PURE__ */ new Map();
10901
+ for (const row of rows) {
10902
+ const group = byId.get(row.routeId);
10903
+ if (group)
10904
+ group.push(row);
10905
+ else
10906
+ byId.set(row.routeId, [row]);
10907
+ }
10908
+ const ids = [...routeIds];
10909
+ const next = ids.flatMap((id) => byId.get(id) ?? []);
10910
+ if (!current || next.every((row, index) => row === rows[index]))
10911
+ return { result: { ids, outcome: "unchanged" } };
10912
+ return {
10913
+ next: { ...current, rows: next },
10914
+ result: { ids, outcome: "reordered" }
10915
+ };
10916
+ }, { ...options.signal && { signal: options.signal } });
10917
+ }
10429
10918
  function receiptFence(row, receipt2) {
10430
10919
  if (!memberIds(row).includes(receipt2.credentialId))
10431
10920
  return "refuse";
@@ -10571,8 +11060,8 @@ var init_roster = __esm({
10571
11060
  init_quota();
10572
11061
  init_errors2();
10573
11062
  init_interlock();
10574
- init_quota_writer();
10575
- init_quota_writer();
11063
+ init_quota_writer2();
11064
+ init_quota_writer2();
10576
11065
  DEFAULT_ROUTE_PREFIX = "vault:";
10577
11066
  SKIPPED_REASONS = /* @__PURE__ */ new Set([
10578
11067
  "empty credential id",
@@ -10621,56 +11110,12 @@ function retainVaultQuotaWriter(path5, listener) {
10621
11110
  })();
10622
11111
  }
10623
11112
  function fields(publication2) {
10624
- const result = /* @__PURE__ */ new Map();
10625
- const { observation } = publication2;
10626
- const witness = JSON.stringify([
11113
+ return quotaFields(publication2, JSON.stringify([
10627
11114
  publication2.routeId,
10628
11115
  publication2.receipt?.credentialId,
10629
11116
  publication2.receipt?.accountIdentitySource,
10630
11117
  publication2.receipt?.expectedAccountIdentity
10631
- ]);
10632
- const add = (key, at, part) => result.set(`${witness}:${key}`, {
10633
- at,
10634
- order: 0,
10635
- publication: { ...publication2, observation: part }
10636
- });
10637
- const keyFor = (scope, label) => JSON.stringify([scope ?? "all", label]);
10638
- const read = /* @__PURE__ */ new Set();
10639
- for (const reading of observation.readings ?? []) {
10640
- const key = keyFor(reading.scope, reading.label);
10641
- read.add(key);
10642
- add(key, observation.checkedAt, {
10643
- checkedAt: observation.checkedAt,
10644
- readings: [{ ...reading }]
10645
- });
10646
- }
10647
- for (const pair of observation.coverage ?? []) {
10648
- const key = keyFor(pair.scope, pair.label);
10649
- if (!read.has(key))
10650
- add(key, observation.checkedAt, {
10651
- checkedAt: observation.checkedAt,
10652
- coverage: [{ ...pair }]
10653
- });
10654
- }
10655
- if (observation.budget)
10656
- add("budget", observation.checkedAt, {
10657
- checkedAt: observation.checkedAt,
10658
- budget: { ...observation.budget }
10659
- });
10660
- for (const [name, counter] of Object.entries(observation.counters ?? {})) {
10661
- add(`counter:${name}`, counter.checkedAt, {
10662
- checkedAt: observation.checkedAt,
10663
- counters: { [name]: { ...counter } }
10664
- });
10665
- }
10666
- if (observation.credits)
10667
- add("credits", observation.credits.checkedAt, {
10668
- checkedAt: observation.checkedAt,
10669
- credits: { ...observation.credits }
10670
- });
10671
- if (!result.size)
10672
- add("empty", observation.checkedAt, { checkedAt: observation.checkedAt });
10673
- return result;
11118
+ ]));
10674
11119
  }
10675
11120
  function enqueueVaultQuota(path5, publication2) {
10676
11121
  if (!isQuotaObservation(publication2.observation))
@@ -10694,7 +11139,7 @@ function enqueueVaultQuota(path5, publication2) {
10694
11139
  writer.pending.set(account, pending);
10695
11140
  for (const listener of writer.listeners)
10696
11141
  listener(publication2);
10697
- schedule(writer, COALESCE_MS);
11142
+ schedule(writer, COALESCE_MS2);
10698
11143
  return Promise.resolve(true);
10699
11144
  }
10700
11145
  function orderedFields(pending) {
@@ -10759,7 +11204,7 @@ function flush(writer) {
10759
11204
  writer.running = void 0;
10760
11205
  for (const wake of writer.wake)
10761
11206
  wake();
10762
- const backoff = writer.failures ? Math.min(5e3, 100 * 2 ** Math.min(writer.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS;
11207
+ const backoff = writer.failures ? Math.min(5e3, 100 * 2 ** Math.min(writer.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS2;
10763
11208
  schedule(writer, backoff);
10764
11209
  }
10765
11210
  })();
@@ -10805,16 +11250,17 @@ async function drainVaultQuota(path5, timeoutMs = 1e3) {
10805
11250
  }
10806
11251
  }
10807
11252
  }
10808
- var writers, logger, COALESCE_MS;
10809
- var init_quota_writer = __esm({
11253
+ var writers, logger, COALESCE_MS2;
11254
+ var init_quota_writer2 = __esm({
10810
11255
  "../core/dist/common-auth-embedded/claustrum/quota-writer.js"() {
10811
11256
  "use strict";
10812
11257
  init_logger();
10813
11258
  init_quota();
11259
+ init_pending();
10814
11260
  init_roster();
10815
11261
  writers = /* @__PURE__ */ new Map();
10816
11262
  logger = createLogger2("claustrum");
10817
- COALESCE_MS = 100;
11263
+ COALESCE_MS2 = 100;
10818
11264
  }
10819
11265
  });
10820
11266
 
@@ -10829,7 +11275,7 @@ var init_consumer = __esm({
10829
11275
  init_enrollment();
10830
11276
  init_errors2();
10831
11277
  init_insula();
10832
- init_quota_writer();
11278
+ init_quota_writer2();
10833
11279
  init_roster();
10834
11280
  init_watch();
10835
11281
  ClaustrumConsumer = class {
@@ -11260,7 +11706,10 @@ var init_consumer = __esm({
11260
11706
  let current;
11261
11707
  try {
11262
11708
  current = await this.authorize(routeId, signal);
11263
- } catch {
11709
+ signal?.throwIfAborted();
11710
+ } catch (error) {
11711
+ if (signal?.aborted)
11712
+ throw error;
11264
11713
  }
11265
11714
  if (decideScopedRetryAfter401(options.site, served, current, this.#logger)) {
11266
11715
  await response.body?.cancel().catch(() => {
@@ -11290,6 +11739,17 @@ var init_consumer = __esm({
11290
11739
  await acceptVaultRoute(this.#options.rosterPath, routeId);
11291
11740
  this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
11292
11741
  }
11742
+ /**
11743
+ * Set the order vault accounts are tried in (`reorderVaultRoster`), then
11744
+ * re-read the roster, so the next routing decision in this process uses
11745
+ * the new order without waiting for a discovery. Never contacts the vault.
11746
+ */
11747
+ async reorder(routeIds) {
11748
+ this.#assertOpen();
11749
+ const result = await reorderVaultRoster(this.#options.rosterPath, routeIds);
11750
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
11751
+ return result;
11752
+ }
11293
11753
  /**
11294
11754
  * Store a quota or profile observation for a vault route. The receipt the
11295
11755
  * reading was taken with is required: the observation lands only while the
@@ -11405,6 +11865,7 @@ __export(claustrum_exports, {
11405
11865
  recordVaultAccountQuota: () => recordVaultAccountQuota,
11406
11866
  recordVaultQuota: () => recordVaultQuota,
11407
11867
  refreshVaultRoster: () => refreshVaultRoster,
11868
+ reorderVaultRoster: () => reorderVaultRoster,
11408
11869
  resetClaustrumEnrollmentState: () => resetClaustrumEnrollmentState,
11409
11870
  resolveVaultPrimary: () => resolveVaultPrimary,
11410
11871
  vaultRoutingRows: () => vaultRoutingRows
@@ -11427,7 +11888,7 @@ var init_claustrum = __esm({
11427
11888
  init_host_slot();
11428
11889
  init_insula();
11429
11890
  init_interlock();
11430
- init_quota_writer();
11891
+ init_quota_writer2();
11431
11892
  init_roster();
11432
11893
  init_watch();
11433
11894
  }
@@ -22495,15 +22956,15 @@ async function redactCredentialResponse(response, credentials, bufferedBody, pro
22495
22956
 
22496
22957
  // ../core/dist/pi-paths.js
22497
22958
  import { homedir } from "node:os";
22498
- import { dirname as dirname11, join as join6 } from "node:path";
22959
+ import { dirname as dirname11, join as join7 } from "node:path";
22499
22960
  function getPiConfigDir() {
22500
- return process.env.PI_AGENT_DIR?.trim() || join6(homedir(), ".pi", "agent");
22961
+ return process.env.PI_AGENT_DIR?.trim() || join7(homedir(), ".pi", "agent");
22501
22962
  }
22502
22963
  function getPiAntigravityAuthFile() {
22503
- return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join6(getPiConfigDir(), "antigravity-accounts.json");
22964
+ return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join7(getPiConfigDir(), "antigravity-accounts.json");
22504
22965
  }
22505
22966
  function getPiAntigravityVaultDir() {
22506
- return join6(dirname11(getPiAntigravityAuthFile()), "antigravity-auth-vault");
22967
+ return join7(dirname11(getPiAntigravityAuthFile()), "antigravity-auth-vault");
22507
22968
  }
22508
22969
 
22509
22970
  // ../core/dist/pre-response-deadline.js
@@ -23239,11 +23700,16 @@ function mostConstrainedWindow(windows2) {
23239
23700
  };
23240
23701
  }
23241
23702
  function poolForBucketId(bucketId) {
23242
- if (bucketId.startsWith("gemini-"))
23243
- return "gemini";
23244
- if (bucketId.startsWith("3p-"))
23245
- return "non-gemini";
23246
- return null;
23703
+ switch (bucketId) {
23704
+ case "gemini-5h":
23705
+ case "gemini-weekly":
23706
+ return "gemini";
23707
+ case "3p-5h":
23708
+ case "3p-weekly":
23709
+ return "non-gemini";
23710
+ default:
23711
+ return null;
23712
+ }
23247
23713
  }
23248
23714
  function parseDescriptionModelCount(description) {
23249
23715
  const prefixMatch = description.match(/^[^:]+:\s*/);
@@ -23264,31 +23730,60 @@ function windowDurationMs(window) {
23264
23730
  }
23265
23731
  }
23266
23732
  function aggregateQuotaSummary(response) {
23267
- const groups = {};
23268
- let totalCount = 0;
23733
+ const windowsByPool = {
23734
+ gemini: /* @__PURE__ */ new Map(),
23735
+ "non-gemini": /* @__PURE__ */ new Map()
23736
+ };
23737
+ const modelCounts = {
23738
+ gemini: 0,
23739
+ "non-gemini": 0
23740
+ };
23741
+ const seenBucketIds = /* @__PURE__ */ new Set();
23742
+ const duplicateBucketIds = /* @__PURE__ */ new Set();
23269
23743
  for (const group of response.groups) {
23270
- const windows2 = [];
23744
+ const contributingPools = /* @__PURE__ */ new Set();
23271
23745
  for (const bucket of group.buckets) {
23272
- const pool2 = poolForBucketId(bucket.bucketId);
23273
- if (!pool2)
23746
+ if (bucket.disabled === true)
23274
23747
  continue;
23275
- windows2.push({
23748
+ const pool = poolForBucketId(bucket.bucketId);
23749
+ if (!pool)
23750
+ continue;
23751
+ contributingPools.add(pool);
23752
+ const window = {
23276
23753
  window: bucket.window,
23277
23754
  remainingFraction: normalizeRemainingFraction(bucket.remainingFraction),
23278
23755
  resetTime: bucket.resetTime
23279
- });
23756
+ };
23757
+ const previous = windowsByPool[pool].get(bucket.bucketId);
23758
+ if (seenBucketIds.has(bucket.bucketId)) {
23759
+ duplicateBucketIds.add(bucket.bucketId);
23760
+ } else {
23761
+ seenBucketIds.add(bucket.bucketId);
23762
+ }
23763
+ if (!previous || window.remainingFraction < previous.remainingFraction) {
23764
+ windowsByPool[pool].set(bucket.bucketId, window);
23765
+ }
23280
23766
  }
23767
+ const modelCount = group.description ? parseDescriptionModelCount(group.description) : 0;
23768
+ for (const pool of contributingPools)
23769
+ modelCounts[pool] += modelCount;
23770
+ }
23771
+ if (duplicateBucketIds.size > 0) {
23772
+ log4.debug("duplicate quota summary bucket ids", {
23773
+ bucketIds: [...duplicateBucketIds].sort()
23774
+ });
23775
+ }
23776
+ const groups = {};
23777
+ let totalCount = 0;
23778
+ for (const pool of ["gemini", "non-gemini"]) {
23779
+ const windows2 = [...windowsByPool[pool].values()];
23281
23780
  if (windows2.length === 0)
23282
23781
  continue;
23283
23782
  windows2.sort((a, b) => windowDurationMs(a.window) - windowDurationMs(b.window));
23284
23783
  const constrained = mostConstrainedWindow(windows2);
23285
- const recognizedBucket = group.buckets.find((bucket) => poolForBucketId(bucket.bucketId));
23286
- if (!recognizedBucket)
23784
+ if (!constrained)
23287
23785
  continue;
23288
- const pool = poolForBucketId(recognizedBucket.bucketId);
23289
- if (!pool || !constrained)
23290
- continue;
23291
- const modelCount = group.description ? parseDescriptionModelCount(group.description) : 0;
23786
+ const modelCount = modelCounts[pool];
23292
23787
  groups[pool] = {
23293
23788
  remainingFraction: constrained.remainingFraction,
23294
23789
  resetTime: constrained.resetTime,
@@ -23651,6 +24146,7 @@ function toGeminiSchema(schema, options = {}) {
23651
24146
  }
23652
24147
  const numericConstraintHints = [];
23653
24148
  const inputSchema = mergeSchemaAllOf(schema, numericConstraintHints);
24149
+ const schemaType = typeof inputSchema.type === "string" ? inputSchema.type.toUpperCase() : void 0;
23654
24150
  let result = {};
23655
24151
  const propertyNames = /* @__PURE__ */ new Set();
23656
24152
  if (inputSchema.properties && typeof inputSchema.properties === "object") {
@@ -23659,6 +24155,12 @@ function toGeminiSchema(schema, options = {}) {
23659
24155
  }
23660
24156
  }
23661
24157
  for (const [key, value] of Object.entries(inputSchema)) {
24158
+ if (schemaType !== void 0) {
24159
+ if (key === "items" && schemaType !== "ARRAY")
24160
+ continue;
24161
+ if (schemaType !== "OBJECT" && ["properties", "required", "propertyOrdering"].includes(key))
24162
+ continue;
24163
+ }
23662
24164
  if (options.claudeValidated) {
23663
24165
  if (key === "title")
23664
24166
  continue;
@@ -24978,6 +25480,7 @@ function createAntigravityVaultAccountSource(options) {
24978
25480
  }
24979
25481
 
24980
25482
  // ../core/dist/vault-enrollment-authority.js
25483
+ var UNSUPPORTED_VAULT_CODE = "unknown_method";
24981
25484
  var VAULT_ACCOUNT_REMEDY = "Vault account access is unavailable. Connect accounts in the vault, or disconnect the vault to use local accounts.";
24982
25485
  async function enrollmentAuthority2(paths, proposedName, reader) {
24983
25486
  try {
@@ -25336,7 +25839,8 @@ import { dirname as dirname13, resolve as resolve10 } from "node:path";
25336
25839
  // src/common-auth-embedded/fs/private-files.js
25337
25840
  import { randomUUID as randomUUID13 } from "node:crypto";
25338
25841
  import { lstat as lstat4, readFile as readFile8, rename as rename7, unlink as unlink8 } from "node:fs/promises";
25339
- import { dirname as dirname12, resolve as resolve9 } from "node:path";
25842
+ import { tmpdir as tmpdir2 } from "node:os";
25843
+ import { dirname as dirname12, join as join8, resolve as resolve9 } from "node:path";
25340
25844
  var windowsPrivateFiles2 = process.platform === "win32";
25341
25845
  var migrationNotices2 = /* @__PURE__ */ new Set();
25342
25846
  function ioCode2(detail) {
@@ -25349,8 +25853,32 @@ function ioCode2(detail) {
25349
25853
  return detail?.code ?? "ERR_PRIVATE_FILE";
25350
25854
  }
25351
25855
  var backend2;
25856
+ var PRIVATE_FILES_UNAVAILABLE_REASON2 = "native-addon-unavailable";
25857
+ function privateFilesUnavailable2(cause) {
25858
+ return Object.assign(new Error("Windows private-files native addon is unavailable", { cause }), {
25859
+ code: "ERR_PRIVATE_FILES_UNAVAILABLE",
25860
+ reason: PRIVATE_FILES_UNAVAILABLE_REASON2
25861
+ });
25862
+ }
25863
+ function isUnavailable2(api, error) {
25864
+ return error instanceof api.PrivateFilesUnavailableError || error?.code === "ERR_PRIVATE_FILES_UNAVAILABLE";
25865
+ }
25866
+ async function assertNativeAddonLoads2(api) {
25867
+ try {
25868
+ await api.verifyPrivatePath(join8(tmpdir2(), `.common-auth-private-files-probe-${randomUUID13()}`), "file");
25869
+ } catch (error) {
25870
+ if (isUnavailable2(api, error))
25871
+ throw privateFilesUnavailable2(error);
25872
+ }
25873
+ }
25352
25874
  function loadBackend2() {
25353
- backend2 ??= import("@cortexkit/private-files");
25875
+ backend2 ??= import("@cortexkit/private-files").then(async (api) => {
25876
+ if (windowsPrivateFiles2)
25877
+ await assertNativeAddonLoads2(api);
25878
+ return api;
25879
+ }, (cause) => {
25880
+ throw windowsPrivateFiles2 ? privateFilesUnavailable2(cause) : cause;
25881
+ });
25354
25882
  return backend2;
25355
25883
  }
25356
25884
  var PrivateFileError2 = class extends Error {
@@ -25367,7 +25895,7 @@ var PrivateFileError2 = class extends Error {
25367
25895
  orphanPath;
25368
25896
  constructor(path5, stage, cause) {
25369
25897
  const detail = cause;
25370
- 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 });
25898
+ 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 });
25371
25899
  this.path = path5;
25372
25900
  this.stage = stage;
25373
25901
  this.name = "PrivateFileError";
@@ -25983,7 +26511,7 @@ import {
25983
26511
  unlinkSync as unlinkSync2
25984
26512
  } from "node:fs";
25985
26513
  import { homedir as homedir3 } from "node:os";
25986
- import { join as join8 } from "node:path";
26514
+ import { join as join10 } from "node:path";
25987
26515
  import { env } from "node:process";
25988
26516
 
25989
26517
  // src/plugin/logging-utils.ts
@@ -26120,7 +26648,7 @@ import {
26120
26648
  writeFileSync
26121
26649
  } from "node:fs";
26122
26650
  import { homedir as homedir2 } from "node:os";
26123
- import { dirname as dirname14, join as join7, resolve as resolve11 } from "node:path";
26651
+ import { dirname as dirname14, join as join9, resolve as resolve11 } from "node:path";
26124
26652
  var log5 = createLogger4("storage");
26125
26653
  var mutateAccountStorage2 = async (path5, mutate) => {
26126
26654
  await assertLegacyPoolInUse(path5);
@@ -26136,7 +26664,7 @@ var GITIGNORE_ENTRIES = [
26136
26664
  "antigravity-logs/"
26137
26665
  ];
26138
26666
  async function ensureGitignore(configDir) {
26139
- const gitignorePath = join7(configDir, ".gitignore");
26667
+ const gitignorePath = join9(configDir, ".gitignore");
26140
26668
  try {
26141
26669
  let content;
26142
26670
  let existingLines = [];
@@ -26182,7 +26710,7 @@ async function ensureGitignore(configDir) {
26182
26710
  }
26183
26711
  }
26184
26712
  function ensureGitignoreSync(configDir) {
26185
- const gitignorePath = join7(configDir, ".gitignore");
26713
+ const gitignorePath = join9(configDir, ".gitignore");
26186
26714
  try {
26187
26715
  let content;
26188
26716
  let existingLines = [];
@@ -26221,8 +26749,8 @@ function ensureGitignoreSync(configDir) {
26221
26749
  }
26222
26750
  }
26223
26751
  function getLegacyWindowsConfigDir() {
26224
- return join7(
26225
- process.env.APPDATA || join7(homedir2(), "AppData", "Roaming"),
26752
+ return join9(
26753
+ process.env.APPDATA || join9(homedir2(), "AppData", "Roaming"),
26226
26754
  "opencode"
26227
26755
  );
26228
26756
  }
@@ -26230,15 +26758,15 @@ function getConfigDir() {
26230
26758
  if (process.env.OPENCODE_CONFIG_DIR) {
26231
26759
  return process.env.OPENCODE_CONFIG_DIR;
26232
26760
  }
26233
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join7(homedir2(), ".config");
26234
- return join7(xdgConfig2, "opencode");
26761
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join9(homedir2(), ".config");
26762
+ return join9(xdgConfig2, "opencode");
26235
26763
  }
26236
26764
  function migrateLegacyWindowsConfig() {
26237
26765
  if (process.platform !== "win32") {
26238
26766
  return false;
26239
26767
  }
26240
- const newPath = join7(getConfigDir(), "antigravity-accounts.json");
26241
- const legacyPath = join7(
26768
+ const newPath = join9(getConfigDir(), "antigravity-accounts.json");
26769
+ const legacyPath = join9(
26242
26770
  getLegacyWindowsConfigDir(),
26243
26771
  "antigravity-accounts.json"
26244
26772
  );
@@ -26273,11 +26801,11 @@ function migrateLegacyWindowsConfig() {
26273
26801
  }
26274
26802
  }
26275
26803
  function getStoragePathWithMigration() {
26276
- const newPath = join7(getConfigDir(), "antigravity-accounts.json");
26804
+ const newPath = join9(getConfigDir(), "antigravity-accounts.json");
26277
26805
  if (process.platform === "win32") {
26278
26806
  migrateLegacyWindowsConfig();
26279
26807
  if (!existsSync3(newPath)) {
26280
- const legacyPath = join7(
26808
+ const legacyPath = join9(
26281
26809
  getLegacyWindowsConfigDir(),
26282
26810
  "antigravity-accounts.json"
26283
26811
  );
@@ -26443,16 +26971,16 @@ var liveLogFilePaths = /* @__PURE__ */ new Set();
26443
26971
  function getConfigDir2() {
26444
26972
  const platform = process.platform;
26445
26973
  if (platform === "win32") {
26446
- return join8(
26447
- env.APPDATA || join8(homedir3(), "AppData", "Roaming"),
26974
+ return join10(
26975
+ env.APPDATA || join10(homedir3(), "AppData", "Roaming"),
26448
26976
  "opencode"
26449
26977
  );
26450
26978
  }
26451
- const xdgConfig2 = env.XDG_CONFIG_HOME || join8(homedir3(), ".config");
26452
- return join8(xdgConfig2, "opencode");
26979
+ const xdgConfig2 = env.XDG_CONFIG_HOME || join10(homedir3(), ".config");
26980
+ return join10(xdgConfig2, "opencode");
26453
26981
  }
26454
26982
  function getLogsDir(customLogDir) {
26455
- const logsDir = customLogDir || join8(getConfigDir2(), "antigravity-logs");
26983
+ const logsDir = customLogDir || join10(getConfigDir2(), "antigravity-logs");
26456
26984
  try {
26457
26985
  mkdirSync2(logsDir, { recursive: true, mode: 448 });
26458
26986
  } catch {
@@ -26463,9 +26991,9 @@ function createLogFilePath(customLogDir) {
26463
26991
  const logsDir = getLogsDir(customLogDir);
26464
26992
  cleanupOldLogs(logsDir, 25);
26465
26993
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
26466
- let candidate = join8(logsDir, `antigravity-debug-${timestamp}.log`);
26994
+ let candidate = join10(logsDir, `antigravity-debug-${timestamp}.log`);
26467
26995
  for (let suffix = 2; liveLogFilePaths.has(candidate); suffix++) {
26468
- candidate = join8(logsDir, `antigravity-debug-${timestamp}-${suffix}.log`);
26996
+ candidate = join10(logsDir, `antigravity-debug-${timestamp}-${suffix}.log`);
26469
26997
  }
26470
26998
  return candidate;
26471
26999
  }
@@ -26473,7 +27001,7 @@ function cleanupOldLogs(logsDir, maxFiles) {
26473
27001
  try {
26474
27002
  const files = readdirSync(logsDir).filter(
26475
27003
  (file) => file.startsWith("antigravity-debug-") && file.endsWith(".log")
26476
- ).map((file) => join8(logsDir, file));
27004
+ ).map((file) => join10(logsDir, file));
26477
27005
  if (files.length <= maxFiles) {
26478
27006
  return;
26479
27007
  }
@@ -27939,7 +28467,7 @@ import { z as z4 } from "zod";
27939
28467
  // src/plugin/config/loader.ts
27940
28468
  import { existsSync as existsSync4, readFileSync as readFileSync2, realpathSync } from "node:fs";
27941
28469
  import { homedir as homedir4 } from "node:os";
27942
- import { basename as basename4, dirname as dirname15, join as join9, resolve as resolve12 } from "node:path";
28470
+ import { basename as basename4, dirname as dirname15, join as join11, resolve as resolve12 } from "node:path";
27943
28471
 
27944
28472
  // src/plugin/config/schema.ts
27945
28473
  import { z } from "zod";
@@ -28434,14 +28962,14 @@ function getConfigDir3() {
28434
28962
  if (process.env.OPENCODE_CONFIG_DIR) {
28435
28963
  return process.env.OPENCODE_CONFIG_DIR;
28436
28964
  }
28437
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join9(homedir4(), ".config");
28438
- return join9(xdgConfig2, "opencode");
28965
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join11(homedir4(), ".config");
28966
+ return join11(xdgConfig2, "opencode");
28439
28967
  }
28440
28968
  function getUserConfigPath() {
28441
- return join9(getConfigDir3(), "antigravity.json");
28969
+ return join11(getConfigDir3(), "antigravity.json");
28442
28970
  }
28443
28971
  function getProjectConfigPath(directory) {
28444
- return join9(directory, ".opencode", "antigravity.json");
28972
+ return join11(directory, ".opencode", "antigravity.json");
28445
28973
  }
28446
28974
  function loadConfigFile(path5, log16) {
28447
28975
  try {
@@ -28518,7 +29046,7 @@ function canonicalizeOwnedPath(path5) {
28518
29046
  let current = absolute;
28519
29047
  for (; ; ) {
28520
29048
  try {
28521
- return join9(realpathSync(current), ...missing.reverse());
29049
+ return join11(realpathSync(current), ...missing.reverse());
28522
29050
  } catch {
28523
29051
  const parent = dirname15(current);
28524
29052
  if (parent === current) return absolute;
@@ -29068,7 +29596,7 @@ async function replacePoolLogins(repository, results, options = {}) {
29068
29596
  // src/sidebar-state.ts
29069
29597
  import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync5 } from "node:fs";
29070
29598
  import { homedir as homedir5 } from "node:os";
29071
- import { dirname as dirname16, join as join10 } from "node:path";
29599
+ import { dirname as dirname16, join as join12 } from "node:path";
29072
29600
 
29073
29601
  // ../../node_modules/.bun/xdg-basedir@5.1.0/node_modules/xdg-basedir/index.js
29074
29602
  import os from "os";
@@ -29127,8 +29655,8 @@ async function emitMergeStep(step) {
29127
29655
  function getSidebarStateFile() {
29128
29656
  const override = process.env[SIDEBAR_STATE_ENV];
29129
29657
  if (override && override.trim().length > 0) return override;
29130
- const base = xdgState ?? join10(homedir5(), ".local", "state");
29131
- return join10(base, SIDEBAR_STATE_DIR, SIDEBAR_STATE_FILENAME);
29658
+ const base = xdgState ?? join12(homedir5(), ".local", "state");
29659
+ return join12(base, SIDEBAR_STATE_DIR, SIDEBAR_STATE_FILENAME);
29132
29660
  }
29133
29661
  function readSidebarState(path5 = getSidebarStateFile()) {
29134
29662
  let raw;
@@ -30593,21 +31121,21 @@ import {
30593
31121
  unlinkSync as unlinkSync3,
30594
31122
  writeFileSync as writeFileSync2
30595
31123
  } from "node:fs";
30596
- import { homedir as homedir6, tmpdir } from "node:os";
30597
- import { dirname as dirname17, join as join11 } from "node:path";
31124
+ import { homedir as homedir6, tmpdir as tmpdir3 } from "node:os";
31125
+ import { dirname as dirname17, join as join13 } from "node:path";
30598
31126
  function getConfigDir4() {
30599
31127
  const platform = process.platform;
30600
31128
  if (platform === "win32") {
30601
- return join11(
30602
- process.env.APPDATA || join11(homedir6(), "AppData", "Roaming"),
31129
+ return join13(
31130
+ process.env.APPDATA || join13(homedir6(), "AppData", "Roaming"),
30603
31131
  "opencode"
30604
31132
  );
30605
31133
  }
30606
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join11(homedir6(), ".config");
30607
- return join11(xdgConfig2, "opencode");
31134
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join13(homedir6(), ".config");
31135
+ return join13(xdgConfig2, "opencode");
30608
31136
  }
30609
31137
  function getSignatureCacheFilePath() {
30610
- return join11(getConfigDir4(), "antigravity-signature-cache.json");
31138
+ return join13(getConfigDir4(), "antigravity-signature-cache.json");
30611
31139
  }
30612
31140
  var SignatureCache = class {
30613
31141
  // In-memory cache: key -> entry with signature and optional thinking text
@@ -30890,8 +31418,8 @@ var SignatureCache = class {
30890
31418
  last_write: now
30891
31419
  }
30892
31420
  };
30893
- const tmpPath = join11(
30894
- tmpdir(),
31421
+ const tmpPath = join13(
31422
+ tmpdir3(),
30895
31423
  `antigravity-cache-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`
30896
31424
  );
30897
31425
  writeFileSync2(tmpPath, JSON.stringify(cacheData, null, 2), "utf-8");
@@ -31247,9 +31775,9 @@ function clearSignatureCache(sessionId) {
31247
31775
  // src/plugin/image-saver.ts
31248
31776
  import { chmodSync as chmodSync4, existsSync as existsSync8, mkdirSync as mkdirSync5, writeFileSync as writeFileSync3 } from "node:fs";
31249
31777
  import { homedir as homedir7 } from "node:os";
31250
- import { join as join12 } from "node:path";
31778
+ import { join as join14 } from "node:path";
31251
31779
  function getImageOutputDir(outputDir) {
31252
- const resolved = outputDir ?? join12(homedir7(), ".opencode", "generated-images");
31780
+ const resolved = outputDir ?? join14(homedir7(), ".opencode", "generated-images");
31253
31781
  if (!existsSync8(resolved)) {
31254
31782
  mkdirSync5(resolved, { recursive: true, mode: 448 });
31255
31783
  }
@@ -31272,7 +31800,7 @@ function generateImageFilename(mimeType) {
31272
31800
  function saveImageToDisk(base64Data, mimeType, outputDir) {
31273
31801
  try {
31274
31802
  const resolvedOutputDir = getImageOutputDir(outputDir);
31275
- const filePath = join12(resolvedOutputDir, generateImageFilename(mimeType));
31803
+ const filePath = join14(resolvedOutputDir, generateImageFilename(mimeType));
31276
31804
  writeFileSync3(filePath, Buffer.from(base64Data, "base64"), { mode: 384 });
31277
31805
  chmodSync4(filePath, 384);
31278
31806
  return filePath;
@@ -31707,11 +32235,11 @@ data: ${JSON.stringify(syntheticUsage)}
31707
32235
  // src/plugin/gemini-dump.ts
31708
32236
  import { createHash as createHash12 } from "node:crypto";
31709
32237
  import { appendFileSync as appendFileSync4, mkdirSync as mkdirSync6, writeFileSync as writeFileSync4 } from "node:fs";
31710
- import { tmpdir as tmpdir2 } from "node:os";
31711
- import { join as join13 } from "node:path";
32238
+ import { tmpdir as tmpdir4 } from "node:os";
32239
+ import { join as join15 } from "node:path";
31712
32240
  var DUMP_STATUS_TITLE = "## Gemini Dump Status";
31713
32241
  var DUMP_DIR_ENV = "OPENCODE_ANTIGRAVITY_GEMINI_DUMP_DIR";
31714
- var DEFAULT_DUMP_DIR = join13(tmpdir2(), "opencode-antigravity-gemini-dumps");
32242
+ var DEFAULT_DUMP_DIR = join15(tmpdir4(), "opencode-antigravity-gemini-dumps");
31715
32243
  var DUMP_DIR_MODE = 448;
31716
32244
  var DUMP_FILE_MODE = 384;
31717
32245
  var nextDumpId = 0;
@@ -31865,7 +32393,7 @@ function writeGeminiDump(input2) {
31865
32393
  nextDumpId += 1;
31866
32394
  const id = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-${String(nextDumpId).padStart(5, "0")}-${input2.streaming ? "stream" : "json"}`;
31867
32395
  const dumpDir = getGeminiDumpDirectory();
31868
- const prefix = join13(dumpDir, id);
32396
+ const prefix = join15(dumpDir, id);
31869
32397
  mkdirSync6(dumpDir, { recursive: true, mode: DUMP_DIR_MODE });
31870
32398
  const context = {
31871
32399
  id,
@@ -31949,21 +32477,21 @@ import {
31949
32477
  unlinkSync as unlinkSync4,
31950
32478
  writeFileSync as writeFileSync5
31951
32479
  } from "node:fs";
31952
- import { join as join15 } from "node:path";
32480
+ import { join as join17 } from "node:path";
31953
32481
 
31954
32482
  // src/plugin/recovery/constants.ts
31955
32483
  import { homedir as homedir8 } from "node:os";
31956
- import { join as join14 } from "node:path";
32484
+ import { join as join16 } from "node:path";
31957
32485
  function getXdgData() {
31958
32486
  const platform = process.platform;
31959
32487
  if (platform === "win32") {
31960
- return process.env.APPDATA || join14(homedir8(), "AppData", "Roaming");
32488
+ return process.env.APPDATA || join16(homedir8(), "AppData", "Roaming");
31961
32489
  }
31962
- return process.env.XDG_DATA_HOME || join14(homedir8(), ".local", "share");
32490
+ return process.env.XDG_DATA_HOME || join16(homedir8(), ".local", "share");
31963
32491
  }
31964
- var OPENCODE_STORAGE = join14(getXdgData(), "opencode", "storage");
31965
- var MESSAGE_STORAGE = join14(OPENCODE_STORAGE, "message");
31966
- var PART_STORAGE = join14(OPENCODE_STORAGE, "part");
32492
+ var OPENCODE_STORAGE = join16(getXdgData(), "opencode", "storage");
32493
+ var MESSAGE_STORAGE = join16(OPENCODE_STORAGE, "message");
32494
+ var PART_STORAGE = join16(OPENCODE_STORAGE, "part");
31967
32495
  var THINKING_TYPES = /* @__PURE__ */ new Set([
31968
32496
  "thinking",
31969
32497
  "redacted_thinking",
@@ -31973,13 +32501,13 @@ var THINKING_TYPES = /* @__PURE__ */ new Set([
31973
32501
  // src/plugin/recovery/storage.ts
31974
32502
  function getMessageDir(sessionID) {
31975
32503
  if (!existsSync9(MESSAGE_STORAGE)) return "";
31976
- const directPath = join15(MESSAGE_STORAGE, sessionID);
32504
+ const directPath = join17(MESSAGE_STORAGE, sessionID);
31977
32505
  if (existsSync9(directPath)) {
31978
32506
  return directPath;
31979
32507
  }
31980
32508
  try {
31981
32509
  for (const dir of readdirSync2(MESSAGE_STORAGE)) {
31982
- const sessionPath = join15(MESSAGE_STORAGE, dir, sessionID);
32510
+ const sessionPath = join17(MESSAGE_STORAGE, dir, sessionID);
31983
32511
  if (existsSync9(sessionPath)) {
31984
32512
  return sessionPath;
31985
32513
  }
@@ -31996,7 +32524,7 @@ function readMessages(sessionID) {
31996
32524
  for (const file of readdirSync2(messageDir)) {
31997
32525
  if (!file.endsWith(".json")) continue;
31998
32526
  try {
31999
- const content = readFileSync7(join15(messageDir, file), "utf-8");
32527
+ const content = readFileSync7(join17(messageDir, file), "utf-8");
32000
32528
  messages.push(JSON.parse(content));
32001
32529
  } catch {
32002
32530
  }
@@ -32012,14 +32540,14 @@ function readMessages(sessionID) {
32012
32540
  });
32013
32541
  }
32014
32542
  function readParts(messageID) {
32015
- const partDir = join15(PART_STORAGE, messageID);
32543
+ const partDir = join17(PART_STORAGE, messageID);
32016
32544
  if (!existsSync9(partDir)) return [];
32017
32545
  const parts = [];
32018
32546
  try {
32019
32547
  for (const file of readdirSync2(partDir)) {
32020
32548
  if (!file.endsWith(".json")) continue;
32021
32549
  try {
32022
- const content = readFileSync7(join15(partDir, file), "utf-8");
32550
+ const content = readFileSync7(join17(partDir, file), "utf-8");
32023
32551
  parts.push(JSON.parse(content));
32024
32552
  } catch {
32025
32553
  }
@@ -32061,7 +32589,7 @@ function findMessagesWithOrphanThinking(sessionID) {
32061
32589
  return result;
32062
32590
  }
32063
32591
  function prependThinkingPart(sessionID, messageID) {
32064
- const partDir = join15(PART_STORAGE, messageID);
32592
+ const partDir = join17(PART_STORAGE, messageID);
32065
32593
  try {
32066
32594
  if (!existsSync9(partDir)) {
32067
32595
  mkdirSync7(partDir, { recursive: true });
@@ -32076,7 +32604,7 @@ function prependThinkingPart(sessionID, messageID) {
32076
32604
  synthetic: true
32077
32605
  };
32078
32606
  writeFileSync5(
32079
- join15(partDir, `${partId}.json`),
32607
+ join17(partDir, `${partId}.json`),
32080
32608
  JSON.stringify(part, null, 2)
32081
32609
  );
32082
32610
  return true;
@@ -32085,14 +32613,14 @@ function prependThinkingPart(sessionID, messageID) {
32085
32613
  }
32086
32614
  }
32087
32615
  function stripThinkingParts(messageID) {
32088
- const partDir = join15(PART_STORAGE, messageID);
32616
+ const partDir = join17(PART_STORAGE, messageID);
32089
32617
  if (!existsSync9(partDir)) return false;
32090
32618
  let anyRemoved = false;
32091
32619
  try {
32092
32620
  for (const file of readdirSync2(partDir)) {
32093
32621
  if (!file.endsWith(".json")) continue;
32094
32622
  try {
32095
- const filePath = join15(partDir, file);
32623
+ const filePath = join17(partDir, file);
32096
32624
  const content = readFileSync7(filePath, "utf-8");
32097
32625
  const part = JSON.parse(content);
32098
32626
  if (THINKING_TYPES.has(part.type)) {
@@ -37960,6 +38488,7 @@ function createRequestExecutor(deps) {
37960
38488
  next = await deadline.wait(
37961
38489
  () => credentials.admit({ account, signal: abortSignal })
37962
38490
  );
38491
+ checkAborted();
37963
38492
  } catch {
37964
38493
  checkAborted();
37965
38494
  }
@@ -38814,8 +39343,8 @@ function extractRateLimitBodyInfo(body) {
38814
39343
  }
38815
39344
  }
38816
39345
  if (message) {
38817
- const afterMatch = message.match(/reset after\s+([0-9hms.]+)/i);
38818
- const rawDuration = afterMatch?.[1];
39346
+ const reset = message.match(/(?:reset after|resets? in)\s+([0-9hms.]+)/i);
39347
+ const rawDuration = reset?.[1];
38819
39348
  if (rawDuration) {
38820
39349
  const parsed = parseDurationToMs(rawDuration);
38821
39350
  if (parsed !== null) {
@@ -40106,7 +40635,7 @@ async function checkVaultQuota(input2) {
40106
40635
 
40107
40636
  // src/plugin/vault-custody.ts
40108
40637
  import { chmod as chmod3, mkdir as mkdir11, readFile as readFile9 } from "node:fs/promises";
40109
- import { dirname as dirname18, join as join16 } from "node:path";
40638
+ import { dirname as dirname18, join as join18 } from "node:path";
40110
40639
 
40111
40640
  // src/plugin/vault-insula-quota.ts
40112
40641
  var windows = [
@@ -40156,12 +40685,12 @@ var OPENCODE_VAULT_HOST = "opencode";
40156
40685
  var OPENCODE_VAULT_ENROLLMENT_NAME = getAntigravityVaultEnrollmentName(OPENCODE_VAULT_HOST);
40157
40686
  var OPENCODE_VAULT_DIR_NAME = "antigravity-auth-vault";
40158
40687
  function openCodeVaultPaths(accountFile) {
40159
- const dir = join16(dirname18(accountFile), OPENCODE_VAULT_DIR_NAME);
40688
+ const dir = join18(dirname18(accountFile), OPENCODE_VAULT_DIR_NAME);
40160
40689
  return {
40161
40690
  dir,
40162
- modeFile: join16(dir, "opencode-mode.json"),
40163
- rosterFile: join16(dir, "opencode-roster.json"),
40164
- stateFile: join16(dir, "opencode-state.json")
40691
+ modeFile: join18(dir, "opencode-mode.json"),
40692
+ rosterFile: join18(dir, "opencode-roster.json"),
40693
+ stateFile: join18(dir, "opencode-state.json")
40165
40694
  };
40166
40695
  }
40167
40696
  async function ensureVaultDir(dir) {
@@ -40509,6 +41038,9 @@ async function refusalOr(step) {
40509
41038
  }
40510
41039
  return "Done. Start a new request to use the change.";
40511
41040
  }
41041
+ function isUnsupportedEnrollment(status) {
41042
+ return status.state === "unavailable" && status.code === UNSUPPORTED_VAULT_CODE;
41043
+ }
40512
41044
  function describeEnrollment(status) {
40513
41045
  switch (status.state) {
40514
41046
  case "idle":
@@ -40522,7 +41054,7 @@ function describeEnrollment(status) {
40522
41054
  case "blocked":
40523
41055
  return `blocked (${status.code})`;
40524
41056
  case "unavailable":
40525
- return `vault unavailable (${status.code})`;
41057
+ return isUnsupportedEnrollment(status) ? "vault too old to connect plugins" : `vault unavailable (${status.code})`;
40526
41058
  case "busy":
40527
41059
  return "another setup step is running";
40528
41060
  }
@@ -40589,10 +41121,15 @@ function enrollmentGuidance(status) {
40589
41121
  return [
40590
41122
  "Resolve the enrollment problem with the vault operator, then request vault access again."
40591
41123
  ];
40592
- if (status.state === "unavailable")
41124
+ if (status.state === "unavailable") {
41125
+ if (isUnsupportedEnrollment(status))
41126
+ return [
41127
+ 'This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or keep using your local accounts.'
41128
+ ];
40593
41129
  return [
40594
41130
  "Check that the vault is running and its connection file is available, then request vault access again."
40595
41131
  ];
41132
+ }
40596
41133
  if (status.state === "busy")
40597
41134
  return [
40598
41135
  "Another enrollment operation is running. OpenCode will keep checking its outcome in the background."
@@ -44762,7 +45299,7 @@ function createGaAntigravityPlugin(overrides = {}) {
44762
45299
 
44763
45300
  // src/plugin/index.ts
44764
45301
  import { createHash as createHash20, randomUUID as randomUUID21 } from "node:crypto";
44765
- import { join as join31, resolve as resolve19 } from "node:path";
45302
+ import { join as join33, resolve as resolve19 } from "node:path";
44766
45303
 
44767
45304
  // src/cli.ts
44768
45305
  import { execFile } from "node:child_process";
@@ -44811,7 +45348,7 @@ async function performOAuthLogin(request, deps) {
44811
45348
 
44812
45349
  // src/setup.ts
44813
45350
  import { lstat as lstat5, readFile as readFile13 } from "node:fs/promises";
44814
- import { join as join22, resolve as resolve15 } from "node:path";
45351
+ import { join as join24, resolve as resolve15 } from "node:path";
44815
45352
 
44816
45353
  // src/common-auth-embedded/auth-menu/ansi.js
44817
45354
  var ANSI2 = {
@@ -45053,7 +45590,7 @@ async function select2(terminal, items, options) {
45053
45590
  import { createHash as createHash15, randomBytes as randomBytes6, randomUUID as randomUUID17 } from "node:crypto";
45054
45591
  import { constants as fsConstants2 } from "node:fs";
45055
45592
  import { chmod as chmod4, mkdir as mkdir13, open as open10, readFile as readFile11, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
45056
- import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute3, join as join18, resolve as resolve14 } from "node:path";
45593
+ import { basename as basename5, dirname as dirname20, extname as extname2, isAbsolute as isAbsolute3, join as join20, resolve as resolve14 } from "node:path";
45057
45594
  import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
45058
45595
 
45059
45596
  // src/common-auth-embedded/fs/lock-constants.js
@@ -45075,7 +45612,7 @@ var WRITER_LOCK_CONSTANTS2 = Object.freeze({
45075
45612
  // src/common-auth-embedded/fs/refresh-file-lock.js
45076
45613
  import { randomUUID as randomUUID16 } from "node:crypto";
45077
45614
  import { mkdir as mkdir12, open as open9, readFile as readFile10, rename as rename8, rm as rm5, stat as stat6 } from "node:fs/promises";
45078
- import { dirname as dirname19, join as join17 } from "node:path";
45615
+ import { dirname as dirname19, join as join19 } from "node:path";
45079
45616
 
45080
45617
  // src/common-auth-embedded/fs/with-lock.js
45081
45618
  function lockPathFor2(target, name) {
@@ -45110,7 +45647,7 @@ function acquireRefreshFileLock2(options) {
45110
45647
  }
45111
45648
  async function acquireRefreshFileLockWithClock2(options) {
45112
45649
  const lockPath = lockPathFor2(options.path, options.name);
45113
- const legacyOwnerPath = join17(lockPath, "owner.json");
45650
+ const legacyOwnerPath = join19(lockPath, "owner.json");
45114
45651
  const ownerId = randomUUID16();
45115
45652
  const now = options.now ?? Date.now;
45116
45653
  let renewTimer = null;
@@ -45153,7 +45690,7 @@ async function acquireRefreshFileLockWithClock2(options) {
45153
45690
  let terminalIOError;
45154
45691
  let renewalInFlight = null;
45155
45692
  const evictPath = `${lockPath}.evicting`;
45156
- const evictOwnerPath = join17(evictPath, "owner.json");
45693
+ const evictOwnerPath = join19(evictPath, "owner.json");
45157
45694
  const evictOwnerId = randomUUID16();
45158
45695
  const EVICT_TTL = 5e3;
45159
45696
  const MAX_STEAL_ATTEMPTS = 8;
@@ -45724,7 +46261,13 @@ var ENROLLMENT_SCHEMA2 = 1;
45724
46261
  var ENROLLMENT_FILE_MAX_BYTES2 = 16 * 1024;
45725
46262
  var ENROLLMENT_LOCK_TTL_MS2 = 3e4;
45726
46263
  var TOKEN_RE2 = /^[0-9a-f]{64}$/;
46264
+ var UNSUPPORTED_ENROLLMENT_CODE2 = "unknown_method";
45727
46265
  var TERMINAL_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
46266
+ // The daemon's answer to an operation it does not implement: a vault built
46267
+ // before the enrollment ceremony. It arrives as a transport Error frame with
46268
+ // no class, which claustrum-client before 0.13.0 labels transient/retry, but
46269
+ // asking again can never succeed.
46270
+ UNSUPPORTED_ENROLLMENT_CODE2,
45728
46271
  "invalid_params",
45729
46272
  "pending_exists",
45730
46273
  "not_found",
@@ -45754,7 +46297,7 @@ function getClaustrumEnrollmentPaths2(tokenPath) {
45754
46297
  const extension = extname2(tokenPath) || ".json";
45755
46298
  const stem = basename5(tokenPath, extname2(tokenPath));
45756
46299
  return {
45757
- statePath: join18(dirname20(tokenPath), `${stem}-state${extension}`),
46300
+ statePath: join20(dirname20(tokenPath), `${stem}-state${extension}`),
45758
46301
  tokenPath
45759
46302
  };
45760
46303
  }
@@ -45762,7 +46305,7 @@ function hostEnrollmentPaths2(input2) {
45762
46305
  const override = input2.override?.trim();
45763
46306
  if (override && !isAbsolute3(override) && !input2.cwd)
45764
46307
  throw new ClaustrumConsumerError2("invalid-state", "A relative Claustrum enrollment override needs a base directory");
45765
- const tokenPath = override ? isAbsolute3(override) ? override : resolve14(input2.cwd, override) : join18(input2.stateDir, `${input2.host}-enrollment.json`);
46308
+ const tokenPath = override ? isAbsolute3(override) ? override : resolve14(input2.cwd, override) : join20(input2.stateDir, `${input2.host}-enrollment.json`);
45766
46309
  return getClaustrumEnrollmentPaths2(tokenPath);
45767
46310
  }
45768
46311
  function isRecord10(value) {
@@ -45995,7 +46538,7 @@ async function writeStateAtomic2(path5, state, ancestorOptions = {}) {
45995
46538
  }
45996
46539
  if (windowsPrivateFiles2)
45997
46540
  return writePrivateAtomic2(path5, bytes);
45998
- const temporary = join18(parent, `.${basename5(path5)}.${process.pid}.${randomUUID17()}.tmp`);
46541
+ const temporary = join20(parent, `.${basename5(path5)}.${process.pid}.${randomUUID17()}.tmp`);
45999
46542
  let descriptor;
46000
46543
  let created = false;
46001
46544
  try {
@@ -46219,6 +46762,18 @@ var ClaustrumEnrollmentManager2 = class {
46219
46762
  retryCode: refusal3.code
46220
46763
  };
46221
46764
  }
46765
+ if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE2) {
46766
+ await lock.assertOwned();
46767
+ await unlink9(this.#paths.statePath).catch((cause) => {
46768
+ if (cause.code !== "ENOENT")
46769
+ throw cause;
46770
+ });
46771
+ return {
46772
+ state: "unavailable",
46773
+ proposedName: state.proposedName,
46774
+ code: refusal3.code
46775
+ };
46776
+ }
46222
46777
  return this.#block(state, refusal3.code);
46223
46778
  }
46224
46779
  }
@@ -46496,8 +47051,8 @@ function recordSetupEnrollment(failure2, enrollment) {
46496
47051
  // src/common-auth-embedded/setup/detect.js
46497
47052
  import { accessSync, constants as constants3, existsSync as existsSync11, readFileSync as readFileSync9, realpathSync as realpathSync2, statSync as statSync5 } from "node:fs";
46498
47053
  import { mkdtemp, rm as rm6 } from "node:fs/promises";
46499
- import { tmpdir as tmpdir3 } from "node:os";
46500
- import { join as join19 } from "node:path";
47054
+ import { tmpdir as tmpdir5 } from "node:os";
47055
+ import { join as join21 } from "node:path";
46501
47056
  import { parse } from "jsonc-parser";
46502
47057
 
46503
47058
  // src/common-auth-embedded/setup/paths.js
@@ -46668,7 +47223,7 @@ async function detectHosts(plugin2, io = {}) {
46668
47223
  return null;
46669
47224
  let root;
46670
47225
  try {
46671
- root = await mkdtemp(join19(tmpdir3(), "common-auth-setup-version-"));
47226
+ root = await mkdtemp(join21(tmpdir5(), "common-auth-setup-version-"));
46672
47227
  const probeEnv = {
46673
47228
  ...env3,
46674
47229
  HOME: root,
@@ -46737,6 +47292,8 @@ import { writeEnrollmentTokenFile as writeEnrollmentTokenFile3 } from "@cortexki
46737
47292
  var WINDOWS_CIM_TIMEOUT_MS = 45e3;
46738
47293
  var HOSTS = /* @__PURE__ */ new Set(["opencode", "litecode", "opencode2", "pi"]);
46739
47294
  var RUNTIMES = /* @__PURE__ */ new Set(["node", "bun"]);
47295
+ var WINDOWS_FENCE_FILTER = [...HOSTS, ...RUNTIMES].map((name) => `Name LIKE '${name}%'`).join(" OR ");
47296
+ 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 }`;
46740
47297
  var PI_SCRIPT_PATTERN = /(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;
46741
47298
  function commandArguments(command) {
46742
47299
  return [...command.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2] ?? "");
@@ -46876,6 +47433,29 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
46876
47433
  }
46877
47434
  };
46878
47435
  try {
47436
+ if (windows2 && options.hostImagesOnly) {
47437
+ const details = await inspect("CIM", "powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_FENCE_QUERY], WINDOWS_CIM_TIMEOUT_MS);
47438
+ if (details.exitCode !== 0)
47439
+ throw new ProcessInspectionError(inspection);
47440
+ const value = JSON.parse(details.stdout);
47441
+ if (!value || typeof value !== "object" || !("complete" in value) || value.complete !== true || !("processes" in value))
47442
+ throw new ProcessInspectionError(inspection);
47443
+ const listed = value.processes;
47444
+ const rows = listed === null ? [] : Array.isArray(listed) ? listed : [listed];
47445
+ const processes2 = [];
47446
+ for (const row of rows) {
47447
+ 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))
47448
+ throw new ProcessInspectionError(inspection);
47449
+ const pid = row.ProcessId;
47450
+ if (!/^(?:node|bun)\.exe$/i.test(row.Name))
47451
+ processes2.push({ pid, command: row.Name });
47452
+ else if (typeof row.CommandLine === "string")
47453
+ processes2.push({ pid, command: row.CommandLine });
47454
+ else if (pid !== selfPid)
47455
+ throw new ProcessInspectionError(inspection);
47456
+ }
47457
+ return processes2;
47458
+ }
46879
47459
  const result = await inspect(windows2 ? "tasklist" : "ps", windows2 ? "tasklist.exe" : "ps", windows2 ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
46880
47460
  if (result.exitCode !== 0)
46881
47461
  throw new ProcessInspectionError(inspection);
@@ -46945,7 +47525,11 @@ function createProcessFence(runner = defaultCommandRunner, options = {}) {
46945
47525
  const isHost = (entry) => entry.pid !== selfPid && hostName(entry.command) !== null;
46946
47526
  return {
46947
47527
  async listRunningHosts(env3) {
46948
- return (await listSetupProcesses(runner, { ...options, env: env3 })).filter(isHost);
47528
+ return (await listSetupProcesses(runner, {
47529
+ ...options,
47530
+ env: env3,
47531
+ hostImagesOnly: true
47532
+ })).filter(isHost);
46949
47533
  },
46950
47534
  async previewRunningHosts(env3) {
46951
47535
  const processes = await listSetupProcesses(runner, {
@@ -46969,8 +47553,27 @@ async function assertHostsStopped(fence, env3) {
46969
47553
 
46970
47554
  // src/common-auth-embedded/setup/enroll.js
46971
47555
  var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
47556
+ var UNSUPPORTED_VAULT_MESSAGE = 'This Claustrum vault is too old to connect plugins. Run ck upgrade to move to Claustrum v0.2.0 or newer (read "Upgrading from v0.1.3" in its release notes first), or run setup without --claustrum to use local accounts.';
47557
+ var ENROLLMENT_WAIT_MS = 3e5;
47558
+ var APPROVAL_POLL_MS = 1e3;
47559
+ var PROPOSE_BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
47560
+ function safeCode(code2) {
47561
+ return code2 && /^[a-z][a-z0-9_]{0,63}$/.test(code2) ? code2 : "unknown";
47562
+ }
46972
47563
  var HostNotEnrolledError = class extends Error {
47564
+ reason;
47565
+ lastErrorCode;
47566
+ constructor(message, details) {
47567
+ super(message);
47568
+ this.name = "HostNotEnrolledError";
47569
+ this.reason = details.reason;
47570
+ if (details.lastErrorCode !== void 0)
47571
+ this.lastErrorCode = safeCode(details.lastErrorCode);
47572
+ }
46973
47573
  };
47574
+ function approveCommand(requestId, name) {
47575
+ return `ck auth enroll approve --request-id ${requestId} --name ${name}`;
47576
+ }
46974
47577
  async function connectSetupHost(plugin2, host, io, terminal, fence) {
46975
47578
  const { name, paths: input2 } = plugin2.vault.hosts[host];
46976
47579
  const paths = hostEnrollmentPaths2(input2);
@@ -46979,54 +47582,94 @@ async function connectSetupHost(plugin2, host, io, terminal, fence) {
46979
47582
  connectionFile: plugin2.vault.connectionFile,
46980
47583
  handshakeTimeoutMs: 2e3
46981
47584
  }).catch(() => {
46982
- throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.");
47585
+ throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.", { reason: "connection-failed" });
46983
47586
  });
47587
+ const now = io.now ?? (() => performance.now());
47588
+ const wait2 = io.wait ?? delay;
46984
47589
  try {
46985
47590
  const manager = new ClaustrumEnrollmentManager2({
46986
47591
  proposedName: name,
46987
47592
  paths,
46988
- client: {
46989
- enrollPropose: async (input3) => {
46990
- await fence();
46991
- return client.enrollPropose(input3);
46992
- },
46993
- enrollPoll: async (input3) => {
46994
- await fence();
46995
- return client.enrollPoll(input3);
46996
- }
46997
- },
47593
+ // Each tick of the wait below checks the fence once, just before
47594
+ // reconcile proposes or polls. Checking again inside every vault call
47595
+ // doubled the process listings per tick, and on Windows each listing
47596
+ // starts PowerShell.
47597
+ client,
46998
47598
  writeTokenFile: async (path5, file) => {
46999
47599
  await fence();
47000
47600
  await writeEnrollmentTokenFile3(path5, file);
47001
47601
  }
47002
47602
  });
47603
+ printLine2(terminal, `Asking the vault to connect ${name}\u2026`);
47604
+ const deadline = now() + ENROLLMENT_WAIT_MS;
47003
47605
  let printedRequest;
47004
- for (let tick = 0; tick < 300; tick++) {
47606
+ let lastCode;
47607
+ let reportedCode;
47608
+ let failedProposals = 0;
47609
+ for (; ; ) {
47005
47610
  await fence();
47006
47611
  const status = await manager.reconcile();
47007
47612
  if (status.state === "approved") {
47008
47613
  printLine2(terminal, `Connected ${host} to Claustrum.`);
47009
47614
  return;
47010
47615
  }
47616
+ if (status.state === "unavailable" && status.code === UNSUPPORTED_ENROLLMENT_CODE2)
47617
+ throw new HostNotEnrolledError(UNSUPPORTED_VAULT_MESSAGE, {
47618
+ reason: "unsupported-vault",
47619
+ lastErrorCode: status.code
47620
+ });
47011
47621
  if (status.state !== "pending" && status.state !== "busy")
47012
- throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
47013
- if (status.state === "pending" && status.requestId && status.requestId !== printedRequest) {
47014
- if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
47015
- throw new HostNotEnrolledError("Invalid enrollment request id.");
47016
- printedRequest = status.requestId;
47017
- printLine2(terminal, "Waiting for approval. In another terminal, run:");
47018
- printLine2(terminal, ` ck auth enroll approve --request-id ${status.requestId} --name ${name}`);
47019
- printLine2(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
47020
- }
47021
- await (io.wait ?? delay)(1e3);
47022
- }
47023
- throw new HostNotEnrolledError("Claustrum approval is still pending; approve with ck and rerun setup.");
47622
+ throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.", {
47623
+ reason: "refused",
47624
+ ..."code" in status && { lastErrorCode: status.code }
47625
+ });
47626
+ let pause = APPROVAL_POLL_MS;
47627
+ if (status.state === "busy")
47628
+ lastCode = "busy";
47629
+ else if (status.retryCode)
47630
+ lastCode = status.retryCode;
47631
+ if (status.state === "pending" && status.requestId) {
47632
+ failedProposals = 0;
47633
+ if (status.requestId !== printedRequest) {
47634
+ if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
47635
+ throw new HostNotEnrolledError("Invalid enrollment request id.", {
47636
+ reason: "invalid-request"
47637
+ });
47638
+ printedRequest = status.requestId;
47639
+ printLine2(terminal, "Waiting for approval. In another terminal, run:");
47640
+ printLine2(terminal, ` ${approveCommand(status.requestId, name)}`);
47641
+ printLine2(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
47642
+ }
47643
+ } else if (status.state === "pending" && status.retryCode) {
47644
+ pause = PROPOSE_BACKOFF_MS[Math.min(failedProposals, PROPOSE_BACKOFF_MS.length - 1)] ?? APPROVAL_POLL_MS;
47645
+ failedProposals++;
47646
+ const code3 = safeCode(status.retryCode);
47647
+ if (code3 !== reportedCode) {
47648
+ reportedCode = code3;
47649
+ printLine2(terminal, `The vault has not created the request yet (${code3}); retrying.`);
47650
+ }
47651
+ }
47652
+ const remaining = deadline - now();
47653
+ if (remaining <= 0)
47654
+ break;
47655
+ await wait2(Math.min(pause, remaining));
47656
+ }
47657
+ if (printedRequest)
47658
+ throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
47659
+ reason: "approval-pending",
47660
+ ...lastCode !== void 0 && { lastErrorCode: lastCode }
47661
+ });
47662
+ const code2 = safeCode(lastCode);
47663
+ 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 });
47024
47664
  } catch (error) {
47025
- if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError)
47665
+ if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError || // Built above from fixed text and vetted values only.
47666
+ error instanceof HostNotEnrolledError)
47026
47667
  throw error;
47027
- if (error instanceof HostNotEnrolledError)
47028
- throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE);
47029
- throw new Error(ENROLLMENT_INCOMPLETE_MESSAGE);
47668
+ const code2 = error?.code;
47669
+ throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE, {
47670
+ reason: "incomplete",
47671
+ ...typeof code2 === "string" && { lastErrorCode: code2 }
47672
+ });
47030
47673
  } finally {
47031
47674
  client.close();
47032
47675
  }
@@ -47064,7 +47707,7 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
47064
47707
  // src/common-auth-embedded/setup/config-write.js
47065
47708
  import { randomUUID as randomUUID18 } from "node:crypto";
47066
47709
  import { mkdir as mkdir14, open as open11, rename as rename10, stat as stat9, unlink as unlink10 } from "node:fs/promises";
47067
- import { basename as basename6, dirname as dirname21, join as join20 } from "node:path";
47710
+ import { basename as basename6, dirname as dirname21, join as join22 } from "node:path";
47068
47711
  import { setTimeout as delay2 } from "node:timers/promises";
47069
47712
  async function writeHostConfigAtomic(file, content, options = {}) {
47070
47713
  const windows2 = (options.platform ?? process.platform) === "win32";
@@ -47079,7 +47722,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
47079
47722
  throw error;
47080
47723
  }
47081
47724
  }
47082
- const stage = join20(parent, `.${basename6(file)}.${(options.stageName ?? randomUUID18)()}.tmp`);
47725
+ const stage = join22(parent, `.${basename6(file)}.${(options.stageName ?? randomUUID18)()}.tmp`);
47083
47726
  let created = false;
47084
47727
  try {
47085
47728
  const handle = await open11(stage, "wx", mode ?? 438);
@@ -47446,11 +48089,11 @@ ${write.content}`);
47446
48089
  // src/plugin/vault-activation.ts
47447
48090
  import { readFile as readFile12 } from "node:fs/promises";
47448
48091
  import { homedir as homedir10 } from "node:os";
47449
- import { join as join21 } from "node:path";
48092
+ import { join as join23 } from "node:path";
47450
48093
  var V1_VAULT_ACTIVATION_LABEL = "Activate approved Antigravity vault";
47451
48094
  function nativeOpenCodeAuthPath(env3 = process.env, home = homedir10()) {
47452
- return join21(
47453
- env3.XDG_DATA_HOME || join21(home, ".local", "share"),
48095
+ return join23(
48096
+ env3.XDG_DATA_HOME || join23(home, ".local", "share"),
47454
48097
  "opencode",
47455
48098
  "auth.json"
47456
48099
  );
@@ -47498,7 +48141,7 @@ function createV1VaultActivationMethod(input2) {
47498
48141
  // src/setup.ts
47499
48142
  var PI_PLACEHOLDER_KEY = "antigravity-vault-custody";
47500
48143
  function nativeAuthPath(host, context) {
47501
- return host === "opencode" ? nativeOpenCodeAuthPath() : join22(context.piAgentDir, "auth.json");
48144
+ return host === "opencode" ? nativeOpenCodeAuthPath() : join24(context.piAgentDir, "auth.json");
47502
48145
  }
47503
48146
  function provider(host) {
47504
48147
  return host === "opencode" ? OPENCODE_VAULT_PROVIDER : ANTIGRAVITY_PROVIDER_ID;
@@ -47619,7 +48262,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
47619
48262
  const { openPiSlot: openPiSlot2 } = await loadCommonAuthPiSlot();
47620
48263
  if ((await openPiSlot2({
47621
48264
  authPath: nativeAuthPath(host, context),
47622
- stashPath: join22(piDir, "google-login-stash.json"),
48265
+ stashPath: join24(piDir, "google-login-stash.json"),
47623
48266
  provider: ANTIGRAVITY_PROVIDER_ID,
47624
48267
  placeholderKey: PI_PLACEHOLDER_KEY
47625
48268
  }).inspect()).slot === "placeholder")
@@ -47656,7 +48299,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
47656
48299
  const { openPiSlot: openPiSlot2 } = await loadCommonAuthPiSlot();
47657
48300
  const inspection = await openPiSlot2({
47658
48301
  authPath: nativeAuthPath("pi", context),
47659
- stashPath: join22(piDir, "google-login-stash.json"),
48302
+ stashPath: join24(piDir, "google-login-stash.json"),
47660
48303
  provider: ANTIGRAVITY_PROVIDER_ID,
47661
48304
  placeholderKey: PI_PLACEHOLDER_KEY
47662
48305
  }).inspect();
@@ -47775,7 +48418,7 @@ Setup has not completed the OpenCode 2 native Google connection.
47775
48418
  await assertSetupHostsStopped();
47776
48419
  await openPiSlot2({
47777
48420
  authPath: nativeAuthPath(host, context),
47778
- stashPath: join22(piDir, "google-login-stash.json"),
48421
+ stashPath: join24(piDir, "google-login-stash.json"),
47779
48422
  provider: ANTIGRAVITY_PROVIDER_ID,
47780
48423
  placeholderKey: PI_PLACEHOLDER_KEY
47781
48424
  }).enterVault();
@@ -48795,8 +49438,8 @@ function isTuiConnected(sessionId) {
48795
49438
 
48796
49439
  // src/rpc/rpc-dir.ts
48797
49440
  import { createHash as createHash16 } from "node:crypto";
48798
- import { homedir as homedir12, tmpdir as tmpdir4 } from "node:os";
48799
- import { isAbsolute as isAbsolute4, join as join26, resolve as resolve17 } from "node:path";
49441
+ import { homedir as homedir12, tmpdir as tmpdir6 } from "node:os";
49442
+ import { isAbsolute as isAbsolute4, join as join28, resolve as resolve17 } from "node:path";
48800
49443
  var RPC_DIR_ENV = "ANTIGRAVITY_AUTH_RPC_DIR";
48801
49444
  function getRpcDir(projectDirectory) {
48802
49445
  const override = process.env[RPC_DIR_ENV]?.trim();
@@ -48804,8 +49447,8 @@ function getRpcDir(projectDirectory) {
48804
49447
  return isAbsolute4(override) ? override : resolve17(projectDirectory, override);
48805
49448
  }
48806
49449
  const projectHash = createHash16("sha256").update(resolve17(projectDirectory)).digest("hex").slice(0, 16);
48807
- const stateHome = process.env.XDG_STATE_HOME ?? join26(homedir12(), ".local", "state");
48808
- return join26(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
49450
+ const stateHome = process.env.XDG_STATE_HOME ?? join28(homedir12(), ".local", "state");
49451
+ return join28(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
48809
49452
  }
48810
49453
 
48811
49454
  // src/common-auth-embedded/rpc/notifications.js
@@ -48816,7 +49459,7 @@ function isSessionId(value) {
48816
49459
  // src/common-auth-embedded/rpc/port-file.js
48817
49460
  import { createHash as createHash17, randomUUID as randomUUID19 } from "node:crypto";
48818
49461
  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";
48819
- import { join as join27, resolve as resolve18 } from "node:path";
49462
+ import { join as join29, resolve as resolve18 } from "node:path";
48820
49463
  function isProbeablePid(pid) {
48821
49464
  return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0;
48822
49465
  }
@@ -48847,7 +49490,7 @@ async function removeCorruptPortFile(portFile, log16) {
48847
49490
  }
48848
49491
  async function writePortFile(dir, entry, options = {}) {
48849
49492
  const writeOnce = async () => {
48850
- const target = join27(dir, `port-${entry.pid}.json`);
49493
+ const target = join29(dir, `port-${entry.pid}.json`);
48851
49494
  if (windowsPrivateFiles2) {
48852
49495
  await ensurePrivateDirectory3(dir, options.secureDir ?? false);
48853
49496
  await options.beforeWrite?.();
@@ -48908,7 +49551,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
48908
49551
  if (!projectDir.isDirectory() || !isManagedDir(projectDir.name)) {
48909
49552
  continue;
48910
49553
  }
48911
- const dir = join27(root, projectDir.name);
49554
+ const dir = join29(root, projectDir.name);
48912
49555
  let names;
48913
49556
  try {
48914
49557
  names = await readdir(dir);
@@ -48920,7 +49563,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
48920
49563
  for (const name of names) {
48921
49564
  if (!name.startsWith("port-") || !name.endsWith(".json"))
48922
49565
  continue;
48923
- const portFile = join27(dir, name);
49566
+ const portFile = join29(dir, name);
48924
49567
  let raw;
48925
49568
  try {
48926
49569
  raw = await readPrivateText2(portFile);
@@ -48957,7 +49600,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
48957
49600
  import { randomBytes as randomBytes7, timingSafeEqual } from "node:crypto";
48958
49601
  import { unlink as unlink12 } from "node:fs/promises";
48959
49602
  import { createServer as createServer3 } from "node:http";
48960
- import { join as join28 } from "node:path";
49603
+ import { join as join30 } from "node:path";
48961
49604
  var RpcRequestError = class extends Error {
48962
49605
  status;
48963
49606
  constructor(status, message) {
@@ -49209,7 +49852,7 @@ async function startRpcServer(options) {
49209
49852
  for (const socket of connections)
49210
49853
  socket.destroy();
49211
49854
  });
49212
- const portFile = join28(options.dir, `port-${process.pid}.json`);
49855
+ const portFile = join30(options.dir, `port-${process.pid}.json`);
49213
49856
  const current = await readPrivateText2(portFile).then((raw) => JSON.parse(raw)).catch((error) => {
49214
49857
  if (error instanceof PrivateFileError2 && error.code !== "ENOENT")
49215
49858
  throw error;
@@ -49512,7 +50155,7 @@ import { createInterface as createInterface2 } from "node:readline/promises";
49512
50155
  // src/plugin/config/updater.ts
49513
50156
  import { existsSync as existsSync14, mkdirSync as mkdirSync8, readFileSync as readFileSync12, writeFileSync as writeFileSync8 } from "node:fs";
49514
50157
  import { homedir as homedir13 } from "node:os";
49515
- import { dirname as dirname23, join as join29 } from "node:path";
50158
+ import { dirname as dirname23, join as join31 } from "node:path";
49516
50159
  var PLUGIN_NAME = "@cortexkit/opencode-antigravity-auth@latest";
49517
50160
  var SCHEMA_URL = "https://opencode.ai/config.json";
49518
50161
  var OPENCODE_JSON_FILENAME = "opencode.json";
@@ -49524,13 +50167,13 @@ function stripJsonCommentsAndTrailingCommas(json) {
49524
50167
  ).replace(/,(\s*[}\]])/g, "$1");
49525
50168
  }
49526
50169
  function getOpencodeConfigDir() {
49527
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join29(homedir13(), ".config");
49528
- return join29(xdgConfig2, "opencode");
50170
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join31(homedir13(), ".config");
50171
+ return join31(xdgConfig2, "opencode");
49529
50172
  }
49530
50173
  function getOpencodeConfigPath() {
49531
50174
  const configDir = getOpencodeConfigDir();
49532
- const jsoncPath = join29(configDir, OPENCODE_JSONC_FILENAME);
49533
- const jsonPath = join29(configDir, OPENCODE_JSON_FILENAME);
50175
+ const jsoncPath = join31(configDir, OPENCODE_JSONC_FILENAME);
50176
+ const jsonPath = join31(configDir, OPENCODE_JSON_FILENAME);
49534
50177
  if (existsSync14(jsoncPath)) {
49535
50178
  return jsoncPath;
49536
50179
  }
@@ -53118,15 +53761,15 @@ function projectCommandAccountRows(storage) {
53118
53761
 
53119
53762
  // src/plugin/dependencies.ts
53120
53763
  import { homedir as homedir14 } from "node:os";
53121
- import { join as join30 } from "node:path";
53764
+ import { join as join32 } from "node:path";
53122
53765
  function defaultFilesystemRoots() {
53123
- const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join30(homedir14(), ".config");
53124
- const xdgState2 = process.env.XDG_STATE_HOME ?? join30(homedir14(), ".local", "state");
53766
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join32(homedir14(), ".config");
53767
+ const xdgState2 = process.env.XDG_STATE_HOME ?? join32(homedir14(), ".local", "state");
53125
53768
  return {
53126
53769
  projectRoot: process.cwd(),
53127
- userConfigRoot: join30(xdgConfig2, "opencode"),
53128
- sidebarStateRoot: join30(xdgState2, "cortexkit", "antigravity-auth"),
53129
- rpcRoot: join30(xdgState2, "cortexkit", "antigravity-auth", "rpc")
53770
+ userConfigRoot: join32(xdgConfig2, "opencode"),
53771
+ sidebarStateRoot: join32(xdgState2, "cortexkit", "antigravity-auth"),
53772
+ rpcRoot: join32(xdgState2, "cortexkit", "antigravity-auth", "rpc")
53130
53773
  };
53131
53774
  }
53132
53775
  function resolvePluginDependencies(overrides = {}) {
@@ -53744,6 +54387,19 @@ function createGoogleSearchTool({
53744
54387
  // src/plugin/lifecycle.ts
53745
54388
  var NOOP_DRAIN = async () => {
53746
54389
  };
54390
+ async function collectCleanupFailure(cleanup2, failures) {
54391
+ try {
54392
+ await cleanup2();
54393
+ } catch (error) {
54394
+ failures.push(error);
54395
+ }
54396
+ }
54397
+ function reportCleanupFailures(failures) {
54398
+ if (failures.length === 1) throw failures[0];
54399
+ if (failures.length > 1) {
54400
+ throw new AggregateError(failures, "Plugin cleanup failed");
54401
+ }
54402
+ }
53747
54403
  function createPluginLifecycle(options) {
53748
54404
  let accountManager = null;
53749
54405
  let refreshQueue = null;
@@ -53755,19 +54411,19 @@ function createPluginLifecycle(options) {
53755
54411
  const consumers = [];
53756
54412
  const drainSidebarWrites2 = options.drainSidebarWrites ?? NOOP_DRAIN;
53757
54413
  const retire2 = (manager, queue2, requests) => {
53758
- const queueDrained = Promise.resolve(queue2?.dispose());
54414
+ const queueDrained = (async () => {
54415
+ await queue2?.dispose();
54416
+ })();
53759
54417
  const record3 = {
53760
54418
  requests,
53761
54419
  done: (async () => {
53762
- const drained = await Promise.allSettled([
53763
- queueDrained,
53764
- requests?.retire()
54420
+ const failures = [];
54421
+ await Promise.all([
54422
+ collectCleanupFailure(() => queueDrained, failures),
54423
+ collectCleanupFailure(() => requests?.retire(), failures)
53765
54424
  ]);
53766
- await manager.dispose();
53767
- const failed = drained.find(
53768
- (outcome) => outcome.status === "rejected"
53769
- );
53770
- if (failed) throw failed.reason;
54425
+ await collectCleanupFailure(() => manager.dispose(), failures);
54426
+ reportCleanupFailures(failures);
53771
54427
  })()
53772
54428
  };
53773
54429
  retiring.add(record3);
@@ -53777,8 +54433,6 @@ function createPluginLifecycle(options) {
53777
54433
  if (!requests) retiring.delete(record3);
53778
54434
  }
53779
54435
  );
53780
- void queueDrained.catch(() => {
53781
- });
53782
54436
  return { queueDrained, done: record3.done };
53783
54437
  };
53784
54438
  const disposeAccountRuntime = async () => {
@@ -53790,23 +54444,26 @@ function createPluginLifecycle(options) {
53790
54444
  accountRequests = null;
53791
54445
  const retired = [...retiring];
53792
54446
  retiring.clear();
54447
+ const failures = [];
53793
54448
  const aborted = Promise.all([
53794
- oldRequests?.dispose(),
53795
- ...retired.map((record3) => record3.requests?.dispose())
54449
+ collectCleanupFailure(() => oldRequests?.dispose(), failures),
54450
+ ...retired.map(
54451
+ (record3) => collectCleanupFailure(() => record3.requests?.dispose(), failures)
54452
+ )
53796
54453
  ]);
53797
- const liveQueueDrained = Promise.resolve(oldQueue?.dispose());
53798
- void liveQueueDrained.catch(() => {
53799
- });
53800
- await aborted;
53801
- const retirements = await Promise.allSettled(
53802
- retired.map((record3) => record3.done)
53803
- );
53804
- await liveQueueDrained;
53805
- await oldManager?.dispose();
53806
- const failed = retirements.find(
53807
- (outcome) => outcome.status === "rejected"
54454
+ const liveQueueDrained = collectCleanupFailure(
54455
+ () => oldQueue?.dispose(),
54456
+ failures
53808
54457
  );
53809
- if (failed) throw failed.reason;
54458
+ await Promise.all([
54459
+ aborted,
54460
+ liveQueueDrained,
54461
+ ...retired.map(
54462
+ (record3) => collectCleanupFailure(() => record3.done, failures)
54463
+ )
54464
+ ]);
54465
+ await collectCleanupFailure(() => oldManager?.dispose(), failures);
54466
+ reportCleanupFailures(failures);
53810
54467
  };
53811
54468
  const register = (disposable, phase = "consumer") => {
53812
54469
  if (closing) {
@@ -53861,19 +54518,27 @@ function createPluginLifecycle(options) {
53861
54518
  failDisposal = reject;
53862
54519
  });
53863
54520
  void (async () => {
53864
- await disposeAccountRuntime();
53865
- await options.shutdownDiskSignatureCache();
53866
- options.sessionRegistry.clear();
53867
- options.clearFetchState();
54521
+ const failures = [];
54522
+ await collectCleanupFailure(disposeAccountRuntime, failures);
54523
+ await collectCleanupFailure(
54524
+ () => options.shutdownDiskSignatureCache(),
54525
+ failures
54526
+ );
54527
+ await collectCleanupFailure(
54528
+ () => options.sessionRegistry.clear(),
54529
+ failures
54530
+ );
54531
+ await collectCleanupFailure(() => options.clearFetchState(), failures);
53868
54532
  for (const disposable of producers) {
53869
- await disposable.dispose();
54533
+ await collectCleanupFailure(() => disposable.dispose(), failures);
53870
54534
  }
53871
54535
  producers.length = 0;
53872
- await drainSidebarWrites2();
54536
+ await collectCleanupFailure(drainSidebarWrites2, failures);
53873
54537
  for (const disposable of consumers) {
53874
- await disposable.dispose();
54538
+ await collectCleanupFailure(() => disposable.dispose(), failures);
53875
54539
  }
53876
54540
  consumers.length = 0;
54541
+ reportCleanupFailures(failures);
53877
54542
  })().then(finishDisposal, failDisposal);
53878
54543
  }
53879
54544
  return disposal;
@@ -54202,7 +54867,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
54202
54867
  lifecycle.register(vaultQuotaPoller, "producer");
54203
54868
  }
54204
54869
  const operatorSettings = createOperatorSettingsController({
54205
- projectConfigPath: join31(directory, ".opencode", "antigravity.json"),
54870
+ projectConfigPath: join33(directory, ".opencode", "antigravity.json"),
54206
54871
  // getUserConfigPath() already returns the full file path including
54207
54872
  // 'antigravity.json' — do NOT join again or the path double-nests
54208
54873
  // into <dir>/antigravity.json/antigravity.json.