@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/index.js CHANGED
@@ -764,7 +764,8 @@ var init_identity = __esm({
764
764
  // ../core/dist/common-auth-embedded/fs/private-files.js
765
765
  import { randomUUID as randomUUID7 } from "node:crypto";
766
766
  import { lstat as lstat2, readFile as readFile4, rename as rename3, unlink as unlink5 } from "node:fs/promises";
767
- import { dirname as dirname5, resolve as resolve2 } from "node:path";
767
+ import { tmpdir } from "node:os";
768
+ import { dirname as dirname5, join as join4, resolve as resolve2 } from "node:path";
768
769
  function ioCode(detail) {
769
770
  if (detail?.reason === "io-error") {
770
771
  if (detail.win32Code === 2 || detail.win32Code === 3)
@@ -774,8 +775,31 @@ function ioCode(detail) {
774
775
  }
775
776
  return detail?.code ?? "ERR_PRIVATE_FILE";
776
777
  }
778
+ function privateFilesUnavailable(cause) {
779
+ return Object.assign(new Error("Windows private-files native addon is unavailable", { cause }), {
780
+ code: "ERR_PRIVATE_FILES_UNAVAILABLE",
781
+ reason: PRIVATE_FILES_UNAVAILABLE_REASON
782
+ });
783
+ }
784
+ function isUnavailable(api, error) {
785
+ return error instanceof api.PrivateFilesUnavailableError || error?.code === "ERR_PRIVATE_FILES_UNAVAILABLE";
786
+ }
787
+ async function assertNativeAddonLoads(api) {
788
+ try {
789
+ await api.verifyPrivatePath(join4(tmpdir(), `.common-auth-private-files-probe-${randomUUID7()}`), "file");
790
+ } catch (error) {
791
+ if (isUnavailable(api, error))
792
+ throw privateFilesUnavailable(error);
793
+ }
794
+ }
777
795
  function loadBackend() {
778
- backend ??= import("@cortexkit/private-files");
796
+ backend ??= import("@cortexkit/private-files").then(async (api) => {
797
+ if (windowsPrivateFiles)
798
+ await assertNativeAddonLoads(api);
799
+ return api;
800
+ }, (cause) => {
801
+ throw windowsPrivateFiles ? privateFilesUnavailable(cause) : cause;
802
+ });
779
803
  return backend;
780
804
  }
781
805
  async function privateOperation(path5, stage, operation) {
@@ -1001,12 +1025,13 @@ async function writePrivateAtomic(path5, bytes, options = {}) {
1001
1025
  });
1002
1026
  }
1003
1027
  }
1004
- var windowsPrivateFiles, migrationNotices, backend, PrivateFileError, safeParentOptionsForTest;
1028
+ var windowsPrivateFiles, migrationNotices, backend, PRIVATE_FILES_UNAVAILABLE_REASON, PrivateFileError, safeParentOptionsForTest;
1005
1029
  var init_private_files = __esm({
1006
1030
  "../core/dist/common-auth-embedded/fs/private-files.js"() {
1007
1031
  "use strict";
1008
1032
  windowsPrivateFiles = process.platform === "win32";
1009
1033
  migrationNotices = /* @__PURE__ */ new Set();
1034
+ PRIVATE_FILES_UNAVAILABLE_REASON = "native-addon-unavailable";
1010
1035
  PrivateFileError = class extends Error {
1011
1036
  path;
1012
1037
  stage;
@@ -1021,7 +1046,7 @@ var init_private_files = __esm({
1021
1046
  orphanPath;
1022
1047
  constructor(path5, stage, cause) {
1023
1048
  const detail = cause;
1024
- super(`Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`, { cause });
1049
+ super(detail?.code === "ERR_PRIVATE_FILES_UNAVAILABLE" ? `Private file refused at ${stage}: ${path5} (${PRIVATE_FILES_UNAVAILABLE_REASON}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.` : `Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
1025
1050
  this.path = path5;
1026
1051
  this.stage = stage;
1027
1052
  this.name = "PrivateFileError";
@@ -1132,7 +1157,7 @@ var init_atomic_write = __esm({
1132
1157
  // ../core/dist/common-auth-embedded/fs/refresh-file-lock.js
1133
1158
  import { randomUUID as randomUUID9 } from "node:crypto";
1134
1159
  import { mkdir as mkdir7, open as open4, readFile as readFile5, rename as rename5, rm as rm4, stat as stat3 } from "node:fs/promises";
1135
- import { dirname as dirname7, join as join4 } from "node:path";
1160
+ import { dirname as dirname7, join as join5 } from "node:path";
1136
1161
  async function createExclusiveText(path5, text2) {
1137
1162
  const handle = await open4(path5, "wx", 384);
1138
1163
  try {
@@ -1150,7 +1175,7 @@ function acquireRefreshFileLock(options) {
1150
1175
  }
1151
1176
  async function acquireRefreshFileLockWithClock(options) {
1152
1177
  const lockPath = lockPathFor(options.path, options.name);
1153
- const legacyOwnerPath = join4(lockPath, "owner.json");
1178
+ const legacyOwnerPath = join5(lockPath, "owner.json");
1154
1179
  const ownerId = randomUUID9();
1155
1180
  const now = options.now ?? Date.now;
1156
1181
  let renewTimer = null;
@@ -1193,7 +1218,7 @@ async function acquireRefreshFileLockWithClock(options) {
1193
1218
  let terminalIOError;
1194
1219
  let renewalInFlight = null;
1195
1220
  const evictPath = `${lockPath}.evicting`;
1196
- const evictOwnerPath = join4(evictPath, "owner.json");
1221
+ const evictOwnerPath = join5(evictPath, "owner.json");
1197
1222
  const evictOwnerId = randomUUID9();
1198
1223
  const EVICT_TTL = 5e3;
1199
1224
  const MAX_STEAL_ATTEMPTS = 8;
@@ -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();
@@ -5443,580 +6181,157 @@ function selectStickyCandidate(input2) {
5443
6181
  const leftScore = ((input2.pendingBytes.get(left.candidate.accountId) ?? 0) + input2.requestBytes) / Math.max(left.weight, MIN_WEIGHT);
5444
6182
  const rightScore = ((input2.pendingBytes.get(right.candidate.accountId) ?? 0) + input2.requestBytes) / Math.max(right.weight, MIN_WEIGHT);
5445
6183
  return leftScore - rightScore || left.candidate.configuredOrder - right.candidate.configuredOrder || compareAccountIds(left.candidate.accountId, right.candidate.accountId);
5446
- });
5447
- 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 {
6184
+ });
6185
+ const selected = weighted[0];
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
  }
@@ -11992,7 +12453,7 @@ var init_pi_slot = __esm({
11992
12453
 
11993
12454
  // src/plugin/index.ts
11994
12455
  import { createHash as createHash20, randomUUID as randomUUID20 } from "node:crypto";
11995
- import { join as join31, resolve as resolve19 } from "node:path";
12456
+ import { join as join33, resolve as resolve19 } from "node:path";
11996
12457
 
11997
12458
  // ../core/dist/abort-forwarding.js
11998
12459
  function forwardAbort(source, target) {
@@ -22493,15 +22954,15 @@ async function redactCredentialResponse(response, credentials, bufferedBody, pro
22493
22954
 
22494
22955
  // ../core/dist/pi-paths.js
22495
22956
  import { homedir } from "node:os";
22496
- import { dirname as dirname11, join as join6 } from "node:path";
22957
+ import { dirname as dirname11, join as join7 } from "node:path";
22497
22958
  function getPiConfigDir() {
22498
- return process.env.PI_AGENT_DIR?.trim() || join6(homedir(), ".pi", "agent");
22959
+ return process.env.PI_AGENT_DIR?.trim() || join7(homedir(), ".pi", "agent");
22499
22960
  }
22500
22961
  function getPiAntigravityAuthFile() {
22501
- return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join6(getPiConfigDir(), "antigravity-accounts.json");
22962
+ return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join7(getPiConfigDir(), "antigravity-accounts.json");
22502
22963
  }
22503
22964
  function getPiAntigravityVaultDir() {
22504
- return join6(dirname11(getPiAntigravityAuthFile()), "antigravity-auth-vault");
22965
+ return join7(dirname11(getPiAntigravityAuthFile()), "antigravity-auth-vault");
22505
22966
  }
22506
22967
 
22507
22968
  // ../core/dist/pre-response-deadline.js
@@ -23237,11 +23698,16 @@ function mostConstrainedWindow(windows2) {
23237
23698
  };
23238
23699
  }
23239
23700
  function poolForBucketId(bucketId) {
23240
- if (bucketId.startsWith("gemini-"))
23241
- return "gemini";
23242
- if (bucketId.startsWith("3p-"))
23243
- return "non-gemini";
23244
- return null;
23701
+ switch (bucketId) {
23702
+ case "gemini-5h":
23703
+ case "gemini-weekly":
23704
+ return "gemini";
23705
+ case "3p-5h":
23706
+ case "3p-weekly":
23707
+ return "non-gemini";
23708
+ default:
23709
+ return null;
23710
+ }
23245
23711
  }
23246
23712
  function parseDescriptionModelCount(description) {
23247
23713
  const prefixMatch = description.match(/^[^:]+:\s*/);
@@ -23262,31 +23728,60 @@ function windowDurationMs(window) {
23262
23728
  }
23263
23729
  }
23264
23730
  function aggregateQuotaSummary(response) {
23265
- const groups = {};
23266
- let totalCount = 0;
23731
+ const windowsByPool = {
23732
+ gemini: /* @__PURE__ */ new Map(),
23733
+ "non-gemini": /* @__PURE__ */ new Map()
23734
+ };
23735
+ const modelCounts = {
23736
+ gemini: 0,
23737
+ "non-gemini": 0
23738
+ };
23739
+ const seenBucketIds = /* @__PURE__ */ new Set();
23740
+ const duplicateBucketIds = /* @__PURE__ */ new Set();
23267
23741
  for (const group of response.groups) {
23268
- const windows2 = [];
23742
+ const contributingPools = /* @__PURE__ */ new Set();
23269
23743
  for (const bucket of group.buckets) {
23270
- const pool2 = poolForBucketId(bucket.bucketId);
23271
- if (!pool2)
23744
+ if (bucket.disabled === true)
23745
+ continue;
23746
+ const pool = poolForBucketId(bucket.bucketId);
23747
+ if (!pool)
23272
23748
  continue;
23273
- windows2.push({
23749
+ contributingPools.add(pool);
23750
+ const window = {
23274
23751
  window: bucket.window,
23275
23752
  remainingFraction: normalizeRemainingFraction(bucket.remainingFraction),
23276
23753
  resetTime: bucket.resetTime
23277
- });
23754
+ };
23755
+ const previous = windowsByPool[pool].get(bucket.bucketId);
23756
+ if (seenBucketIds.has(bucket.bucketId)) {
23757
+ duplicateBucketIds.add(bucket.bucketId);
23758
+ } else {
23759
+ seenBucketIds.add(bucket.bucketId);
23760
+ }
23761
+ if (!previous || window.remainingFraction < previous.remainingFraction) {
23762
+ windowsByPool[pool].set(bucket.bucketId, window);
23763
+ }
23278
23764
  }
23765
+ const modelCount = group.description ? parseDescriptionModelCount(group.description) : 0;
23766
+ for (const pool of contributingPools)
23767
+ modelCounts[pool] += modelCount;
23768
+ }
23769
+ if (duplicateBucketIds.size > 0) {
23770
+ log4.debug("duplicate quota summary bucket ids", {
23771
+ bucketIds: [...duplicateBucketIds].sort()
23772
+ });
23773
+ }
23774
+ const groups = {};
23775
+ let totalCount = 0;
23776
+ for (const pool of ["gemini", "non-gemini"]) {
23777
+ const windows2 = [...windowsByPool[pool].values()];
23279
23778
  if (windows2.length === 0)
23280
23779
  continue;
23281
23780
  windows2.sort((a, b) => windowDurationMs(a.window) - windowDurationMs(b.window));
23282
23781
  const constrained = mostConstrainedWindow(windows2);
23283
- const recognizedBucket = group.buckets.find((bucket) => poolForBucketId(bucket.bucketId));
23284
- if (!recognizedBucket)
23285
- continue;
23286
- const pool = poolForBucketId(recognizedBucket.bucketId);
23287
- if (!pool || !constrained)
23782
+ if (!constrained)
23288
23783
  continue;
23289
- const modelCount = group.description ? parseDescriptionModelCount(group.description) : 0;
23784
+ const modelCount = modelCounts[pool];
23290
23785
  groups[pool] = {
23291
23786
  remainingFraction: constrained.remainingFraction,
23292
23787
  resetTime: constrained.resetTime,
@@ -23649,6 +24144,7 @@ function toGeminiSchema(schema, options = {}) {
23649
24144
  }
23650
24145
  const numericConstraintHints = [];
23651
24146
  const inputSchema = mergeSchemaAllOf(schema, numericConstraintHints);
24147
+ const schemaType = typeof inputSchema.type === "string" ? inputSchema.type.toUpperCase() : void 0;
23652
24148
  let result = {};
23653
24149
  const propertyNames = /* @__PURE__ */ new Set();
23654
24150
  if (inputSchema.properties && typeof inputSchema.properties === "object") {
@@ -23657,6 +24153,12 @@ function toGeminiSchema(schema, options = {}) {
23657
24153
  }
23658
24154
  }
23659
24155
  for (const [key, value] of Object.entries(inputSchema)) {
24156
+ if (schemaType !== void 0) {
24157
+ if (key === "items" && schemaType !== "ARRAY")
24158
+ continue;
24159
+ if (schemaType !== "OBJECT" && ["properties", "required", "propertyOrdering"].includes(key))
24160
+ continue;
24161
+ }
23660
24162
  if (options.claudeValidated) {
23661
24163
  if (key === "title")
23662
24164
  continue;
@@ -24976,6 +25478,7 @@ function createAntigravityVaultAccountSource(options) {
24976
25478
  }
24977
25479
 
24978
25480
  // ../core/dist/vault-enrollment-authority.js
25481
+ var UNSUPPORTED_VAULT_CODE = "unknown_method";
24979
25482
  var VAULT_ACCOUNT_REMEDY = "Vault account access is unavailable. Connect accounts in the vault, or disconnect the vault to use local accounts.";
24980
25483
  async function enrollmentAuthority2(paths, proposedName, reader) {
24981
25484
  try {
@@ -25133,7 +25636,7 @@ import {
25133
25636
  writeFileSync
25134
25637
  } from "node:fs";
25135
25638
  import { homedir as homedir3 } from "node:os";
25136
- import { dirname as dirname14, join as join8, resolve as resolve11 } from "node:path";
25639
+ import { dirname as dirname14, join as join10, resolve as resolve11 } from "node:path";
25137
25640
 
25138
25641
  // src/common-auth-embedded/logger/engine.js
25139
25642
  import { appendFileSync as appendFileSync2, chmodSync as chmodSync2, existsSync as existsSync2, renameSync as renameSync2, statSync as statSync3 } from "node:fs";
@@ -25143,7 +25646,8 @@ import { dirname as dirname13, resolve as resolve10 } from "node:path";
25143
25646
  // src/common-auth-embedded/fs/private-files.js
25144
25647
  import { randomUUID as randomUUID13 } from "node:crypto";
25145
25648
  import { lstat as lstat4, readFile as readFile8, rename as rename7, unlink as unlink8 } from "node:fs/promises";
25146
- import { dirname as dirname12, resolve as resolve9 } from "node:path";
25649
+ import { tmpdir as tmpdir2 } from "node:os";
25650
+ import { dirname as dirname12, join as join8, resolve as resolve9 } from "node:path";
25147
25651
  var windowsPrivateFiles2 = process.platform === "win32";
25148
25652
  var migrationNotices2 = /* @__PURE__ */ new Set();
25149
25653
  function ioCode2(detail) {
@@ -25156,8 +25660,32 @@ function ioCode2(detail) {
25156
25660
  return detail?.code ?? "ERR_PRIVATE_FILE";
25157
25661
  }
25158
25662
  var backend2;
25663
+ var PRIVATE_FILES_UNAVAILABLE_REASON2 = "native-addon-unavailable";
25664
+ function privateFilesUnavailable2(cause) {
25665
+ return Object.assign(new Error("Windows private-files native addon is unavailable", { cause }), {
25666
+ code: "ERR_PRIVATE_FILES_UNAVAILABLE",
25667
+ reason: PRIVATE_FILES_UNAVAILABLE_REASON2
25668
+ });
25669
+ }
25670
+ function isUnavailable2(api, error) {
25671
+ return error instanceof api.PrivateFilesUnavailableError || error?.code === "ERR_PRIVATE_FILES_UNAVAILABLE";
25672
+ }
25673
+ async function assertNativeAddonLoads2(api) {
25674
+ try {
25675
+ await api.verifyPrivatePath(join8(tmpdir2(), `.common-auth-private-files-probe-${randomUUID13()}`), "file");
25676
+ } catch (error) {
25677
+ if (isUnavailable2(api, error))
25678
+ throw privateFilesUnavailable2(error);
25679
+ }
25680
+ }
25159
25681
  function loadBackend2() {
25160
- backend2 ??= import("@cortexkit/private-files");
25682
+ backend2 ??= import("@cortexkit/private-files").then(async (api) => {
25683
+ if (windowsPrivateFiles2)
25684
+ await assertNativeAddonLoads2(api);
25685
+ return api;
25686
+ }, (cause) => {
25687
+ throw windowsPrivateFiles2 ? privateFilesUnavailable2(cause) : cause;
25688
+ });
25161
25689
  return backend2;
25162
25690
  }
25163
25691
  var PrivateFileError2 = class extends Error {
@@ -25174,7 +25702,7 @@ var PrivateFileError2 = class extends Error {
25174
25702
  orphanPath;
25175
25703
  constructor(path5, stage, cause) {
25176
25704
  const detail = cause;
25177
- super(`Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`, { cause });
25705
+ super(detail?.code === "ERR_PRIVATE_FILES_UNAVAILABLE" ? `Private file refused at ${stage}: ${path5} (${PRIVATE_FILES_UNAVAILABLE_REASON2}). The Windows native addon of @cortexkit/private-files could not be loaded, so owner-only access cannot be enforced and nothing was read or written. Reinstall the plugin so the private-files Windows prebuild for this architecture is present; Windows has no safe fallback to permission bits.` : `Private file refused at ${stage}: ${path5} (${detail?.reason ?? detail?.code ?? "io-error"}). Keep this file in a folder that only you, the system or administrators can change, such as a folder in your home directory. If other users could read the file before, sign in again to replace the credentials it held. On Windows the file must also be on a local drive that keeps Windows file permissions, such as NTFS.`, { cause });
25178
25706
  this.path = path5;
25179
25707
  this.stage = stage;
25180
25708
  this.name = "PrivateFileError";
@@ -25790,7 +26318,7 @@ import {
25790
26318
  unlinkSync
25791
26319
  } from "node:fs";
25792
26320
  import { homedir as homedir2 } from "node:os";
25793
- import { join as join7 } from "node:path";
26321
+ import { join as join9 } from "node:path";
25794
26322
  import { env } from "node:process";
25795
26323
 
25796
26324
  // src/plugin/logging-utils.ts
@@ -25922,16 +26450,16 @@ var liveLogFilePaths = /* @__PURE__ */ new Set();
25922
26450
  function getConfigDir() {
25923
26451
  const platform = process.platform;
25924
26452
  if (platform === "win32") {
25925
- return join7(
25926
- env.APPDATA || join7(homedir2(), "AppData", "Roaming"),
26453
+ return join9(
26454
+ env.APPDATA || join9(homedir2(), "AppData", "Roaming"),
25927
26455
  "opencode"
25928
26456
  );
25929
26457
  }
25930
- const xdgConfig2 = env.XDG_CONFIG_HOME || join7(homedir2(), ".config");
25931
- return join7(xdgConfig2, "opencode");
26458
+ const xdgConfig2 = env.XDG_CONFIG_HOME || join9(homedir2(), ".config");
26459
+ return join9(xdgConfig2, "opencode");
25932
26460
  }
25933
26461
  function getLogsDir(customLogDir) {
25934
- const logsDir = customLogDir || join7(getConfigDir(), "antigravity-logs");
26462
+ const logsDir = customLogDir || join9(getConfigDir(), "antigravity-logs");
25935
26463
  try {
25936
26464
  mkdirSync(logsDir, { recursive: true, mode: 448 });
25937
26465
  } catch {
@@ -25942,9 +26470,9 @@ function createLogFilePath(customLogDir) {
25942
26470
  const logsDir = getLogsDir(customLogDir);
25943
26471
  cleanupOldLogs(logsDir, 25);
25944
26472
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
25945
- let candidate = join7(logsDir, `antigravity-debug-${timestamp}.log`);
26473
+ let candidate = join9(logsDir, `antigravity-debug-${timestamp}.log`);
25946
26474
  for (let suffix = 2; liveLogFilePaths.has(candidate); suffix++) {
25947
- candidate = join7(logsDir, `antigravity-debug-${timestamp}-${suffix}.log`);
26475
+ candidate = join9(logsDir, `antigravity-debug-${timestamp}-${suffix}.log`);
25948
26476
  }
25949
26477
  return candidate;
25950
26478
  }
@@ -25952,7 +26480,7 @@ function cleanupOldLogs(logsDir, maxFiles) {
25952
26480
  try {
25953
26481
  const files = readdirSync(logsDir).filter(
25954
26482
  (file) => file.startsWith("antigravity-debug-") && file.endsWith(".log")
25955
- ).map((file) => join7(logsDir, file));
26483
+ ).map((file) => join9(logsDir, file));
25956
26484
  if (files.length <= maxFiles) {
25957
26485
  return;
25958
26486
  }
@@ -26531,7 +27059,7 @@ var GITIGNORE_ENTRIES = [
26531
27059
  "antigravity-logs/"
26532
27060
  ];
26533
27061
  async function ensureGitignore(configDir) {
26534
- const gitignorePath = join8(configDir, ".gitignore");
27062
+ const gitignorePath = join10(configDir, ".gitignore");
26535
27063
  try {
26536
27064
  let content;
26537
27065
  let existingLines = [];
@@ -26577,7 +27105,7 @@ async function ensureGitignore(configDir) {
26577
27105
  }
26578
27106
  }
26579
27107
  function ensureGitignoreSync(configDir) {
26580
- const gitignorePath = join8(configDir, ".gitignore");
27108
+ const gitignorePath = join10(configDir, ".gitignore");
26581
27109
  try {
26582
27110
  let content;
26583
27111
  let existingLines = [];
@@ -26616,8 +27144,8 @@ function ensureGitignoreSync(configDir) {
26616
27144
  }
26617
27145
  }
26618
27146
  function getLegacyWindowsConfigDir() {
26619
- return join8(
26620
- process.env.APPDATA || join8(homedir3(), "AppData", "Roaming"),
27147
+ return join10(
27148
+ process.env.APPDATA || join10(homedir3(), "AppData", "Roaming"),
26621
27149
  "opencode"
26622
27150
  );
26623
27151
  }
@@ -26625,15 +27153,15 @@ function getConfigDir2() {
26625
27153
  if (process.env.OPENCODE_CONFIG_DIR) {
26626
27154
  return process.env.OPENCODE_CONFIG_DIR;
26627
27155
  }
26628
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join8(homedir3(), ".config");
26629
- return join8(xdgConfig2, "opencode");
27156
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join10(homedir3(), ".config");
27157
+ return join10(xdgConfig2, "opencode");
26630
27158
  }
26631
27159
  function migrateLegacyWindowsConfig() {
26632
27160
  if (process.platform !== "win32") {
26633
27161
  return false;
26634
27162
  }
26635
- const newPath = join8(getConfigDir2(), "antigravity-accounts.json");
26636
- const legacyPath = join8(
27163
+ const newPath = join10(getConfigDir2(), "antigravity-accounts.json");
27164
+ const legacyPath = join10(
26637
27165
  getLegacyWindowsConfigDir(),
26638
27166
  "antigravity-accounts.json"
26639
27167
  );
@@ -26668,11 +27196,11 @@ function migrateLegacyWindowsConfig() {
26668
27196
  }
26669
27197
  }
26670
27198
  function getStoragePathWithMigration() {
26671
- const newPath = join8(getConfigDir2(), "antigravity-accounts.json");
27199
+ const newPath = join10(getConfigDir2(), "antigravity-accounts.json");
26672
27200
  if (process.platform === "win32") {
26673
27201
  migrateLegacyWindowsConfig();
26674
27202
  if (!existsSync3(newPath)) {
26675
- const legacyPath = join8(
27203
+ const legacyPath = join10(
26676
27204
  getLegacyWindowsConfigDir(),
26677
27205
  "antigravity-accounts.json"
26678
27206
  );
@@ -27008,7 +27536,7 @@ async function replacePoolLogins(repository, results, options = {}) {
27008
27536
  // src/sidebar-state.ts
27009
27537
  import { chmodSync as chmodSync3, mkdirSync as mkdirSync3, readFileSync as readFileSync2 } from "node:fs";
27010
27538
  import { homedir as homedir4 } from "node:os";
27011
- import { dirname as dirname15, join as join9 } from "node:path";
27539
+ import { dirname as dirname15, join as join11 } from "node:path";
27012
27540
 
27013
27541
  // ../../node_modules/.bun/xdg-basedir@5.1.0/node_modules/xdg-basedir/index.js
27014
27542
  import os from "os";
@@ -27067,8 +27595,8 @@ async function emitMergeStep(step) {
27067
27595
  function getSidebarStateFile() {
27068
27596
  const override = process.env[SIDEBAR_STATE_ENV];
27069
27597
  if (override && override.trim().length > 0) return override;
27070
- const base = xdgState ?? join9(homedir4(), ".local", "state");
27071
- return join9(base, SIDEBAR_STATE_DIR, SIDEBAR_STATE_FILENAME);
27598
+ const base = xdgState ?? join11(homedir4(), ".local", "state");
27599
+ return join11(base, SIDEBAR_STATE_DIR, SIDEBAR_STATE_FILENAME);
27072
27600
  }
27073
27601
  function readSidebarState(path5 = getSidebarStateFile()) {
27074
27602
  let raw;
@@ -29082,7 +29610,7 @@ async function startOAuthListener({
29082
29610
 
29083
29611
  // src/setup.ts
29084
29612
  import { lstat as lstat5, readFile as readFile13 } from "node:fs/promises";
29085
- import { join as join16, resolve as resolve13 } from "node:path";
29613
+ import { join as join18, resolve as resolve13 } from "node:path";
29086
29614
 
29087
29615
  // src/auth-method-labels.ts
29088
29616
  var OPENCODE2_POOL_AUTH_LABEL = "Google (antigravity-auth pool, browser)";
@@ -29328,7 +29856,7 @@ async function select2(terminal, items, options) {
29328
29856
  import { createHash as createHash10, randomBytes as randomBytes5, randomUUID as randomUUID16 } from "node:crypto";
29329
29857
  import { constants as fsConstants2 } from "node:fs";
29330
29858
  import { chmod as chmod3, mkdir as mkdir12, open as open10, readFile as readFile10, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
29331
- import { basename as basename4, dirname as dirname17, extname as extname2, isAbsolute as isAbsolute3, join as join11, resolve as resolve12 } from "node:path";
29859
+ import { basename as basename4, dirname as dirname17, extname as extname2, isAbsolute as isAbsolute3, join as join13, resolve as resolve12 } from "node:path";
29332
29860
  import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
29333
29861
 
29334
29862
  // src/common-auth-embedded/fs/lock-constants.js
@@ -29350,7 +29878,7 @@ var WRITER_LOCK_CONSTANTS2 = Object.freeze({
29350
29878
  // src/common-auth-embedded/fs/refresh-file-lock.js
29351
29879
  import { randomUUID as randomUUID15 } from "node:crypto";
29352
29880
  import { mkdir as mkdir11, open as open9, readFile as readFile9, rename as rename8, rm as rm5, stat as stat6 } from "node:fs/promises";
29353
- import { dirname as dirname16, join as join10 } from "node:path";
29881
+ import { dirname as dirname16, join as join12 } from "node:path";
29354
29882
 
29355
29883
  // src/common-auth-embedded/fs/with-lock.js
29356
29884
  function lockPathFor2(target, name) {
@@ -29385,7 +29913,7 @@ function acquireRefreshFileLock2(options) {
29385
29913
  }
29386
29914
  async function acquireRefreshFileLockWithClock2(options) {
29387
29915
  const lockPath = lockPathFor2(options.path, options.name);
29388
- const legacyOwnerPath = join10(lockPath, "owner.json");
29916
+ const legacyOwnerPath = join12(lockPath, "owner.json");
29389
29917
  const ownerId = randomUUID15();
29390
29918
  const now = options.now ?? Date.now;
29391
29919
  let renewTimer = null;
@@ -29428,7 +29956,7 @@ async function acquireRefreshFileLockWithClock2(options) {
29428
29956
  let terminalIOError;
29429
29957
  let renewalInFlight = null;
29430
29958
  const evictPath = `${lockPath}.evicting`;
29431
- const evictOwnerPath = join10(evictPath, "owner.json");
29959
+ const evictOwnerPath = join12(evictPath, "owner.json");
29432
29960
  const evictOwnerId = randomUUID15();
29433
29961
  const EVICT_TTL = 5e3;
29434
29962
  const MAX_STEAL_ATTEMPTS = 8;
@@ -29999,7 +30527,13 @@ var ENROLLMENT_SCHEMA2 = 1;
29999
30527
  var ENROLLMENT_FILE_MAX_BYTES2 = 16 * 1024;
30000
30528
  var ENROLLMENT_LOCK_TTL_MS2 = 3e4;
30001
30529
  var TOKEN_RE2 = /^[0-9a-f]{64}$/;
30530
+ var UNSUPPORTED_ENROLLMENT_CODE2 = "unknown_method";
30002
30531
  var TERMINAL_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
30532
+ // The daemon's answer to an operation it does not implement: a vault built
30533
+ // before the enrollment ceremony. It arrives as a transport Error frame with
30534
+ // no class, which claustrum-client before 0.13.0 labels transient/retry, but
30535
+ // asking again can never succeed.
30536
+ UNSUPPORTED_ENROLLMENT_CODE2,
30003
30537
  "invalid_params",
30004
30538
  "pending_exists",
30005
30539
  "not_found",
@@ -30029,7 +30563,7 @@ function getClaustrumEnrollmentPaths2(tokenPath) {
30029
30563
  const extension = extname2(tokenPath) || ".json";
30030
30564
  const stem = basename4(tokenPath, extname2(tokenPath));
30031
30565
  return {
30032
- statePath: join11(dirname17(tokenPath), `${stem}-state${extension}`),
30566
+ statePath: join13(dirname17(tokenPath), `${stem}-state${extension}`),
30033
30567
  tokenPath
30034
30568
  };
30035
30569
  }
@@ -30037,7 +30571,7 @@ function hostEnrollmentPaths2(input2) {
30037
30571
  const override = input2.override?.trim();
30038
30572
  if (override && !isAbsolute3(override) && !input2.cwd)
30039
30573
  throw new ClaustrumConsumerError2("invalid-state", "A relative Claustrum enrollment override needs a base directory");
30040
- const tokenPath = override ? isAbsolute3(override) ? override : resolve12(input2.cwd, override) : join11(input2.stateDir, `${input2.host}-enrollment.json`);
30574
+ const tokenPath = override ? isAbsolute3(override) ? override : resolve12(input2.cwd, override) : join13(input2.stateDir, `${input2.host}-enrollment.json`);
30041
30575
  return getClaustrumEnrollmentPaths2(tokenPath);
30042
30576
  }
30043
30577
  function isRecord10(value) {
@@ -30270,7 +30804,7 @@ async function writeStateAtomic2(path5, state, ancestorOptions = {}) {
30270
30804
  }
30271
30805
  if (windowsPrivateFiles2)
30272
30806
  return writePrivateAtomic2(path5, bytes);
30273
- const temporary = join11(parent, `.${basename4(path5)}.${process.pid}.${randomUUID16()}.tmp`);
30807
+ const temporary = join13(parent, `.${basename4(path5)}.${process.pid}.${randomUUID16()}.tmp`);
30274
30808
  let descriptor;
30275
30809
  let created = false;
30276
30810
  try {
@@ -30494,6 +31028,18 @@ var ClaustrumEnrollmentManager2 = class {
30494
31028
  retryCode: refusal3.code
30495
31029
  };
30496
31030
  }
31031
+ if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE2) {
31032
+ await lock.assertOwned();
31033
+ await unlink9(this.#paths.statePath).catch((cause) => {
31034
+ if (cause.code !== "ENOENT")
31035
+ throw cause;
31036
+ });
31037
+ return {
31038
+ state: "unavailable",
31039
+ proposedName: state.proposedName,
31040
+ code: refusal3.code
31041
+ };
31042
+ }
30497
31043
  return this.#block(state, refusal3.code);
30498
31044
  }
30499
31045
  }
@@ -30771,8 +31317,8 @@ function recordSetupEnrollment(failure2, enrollment) {
30771
31317
  // src/common-auth-embedded/setup/detect.js
30772
31318
  import { accessSync, constants as constants3, existsSync as existsSync5, readFileSync as readFileSync4, realpathSync, statSync as statSync5 } from "node:fs";
30773
31319
  import { mkdtemp, rm as rm6 } from "node:fs/promises";
30774
- import { tmpdir } from "node:os";
30775
- import { join as join12 } from "node:path";
31320
+ import { tmpdir as tmpdir3 } from "node:os";
31321
+ import { join as join14 } from "node:path";
30776
31322
  import { parse } from "jsonc-parser";
30777
31323
 
30778
31324
  // src/common-auth-embedded/setup/paths.js
@@ -30943,7 +31489,7 @@ async function detectHosts(plugin, io = {}) {
30943
31489
  return null;
30944
31490
  let root;
30945
31491
  try {
30946
- root = await mkdtemp(join12(tmpdir(), "common-auth-setup-version-"));
31492
+ root = await mkdtemp(join14(tmpdir3(), "common-auth-setup-version-"));
30947
31493
  const probeEnv = {
30948
31494
  ...env3,
30949
31495
  HOME: root,
@@ -31012,6 +31558,8 @@ import { writeEnrollmentTokenFile as writeEnrollmentTokenFile3 } from "@cortexki
31012
31558
  var WINDOWS_CIM_TIMEOUT_MS = 45e3;
31013
31559
  var HOSTS = /* @__PURE__ */ new Set(["opencode", "litecode", "opencode2", "pi"]);
31014
31560
  var RUNTIMES = /* @__PURE__ */ new Set(["node", "bun"]);
31561
+ var WINDOWS_FENCE_FILTER = [...HOSTS, ...RUNTIMES].map((name) => `Name LIKE '${name}%'`).join(" OR ");
31562
+ var WINDOWS_FENCE_QUERY = `$ErrorActionPreference = 'Stop'; $rows = @(Get-CimInstance Win32_Process -Filter "${WINDOWS_FENCE_FILTER}" | Select-Object Name,ProcessId,CommandLine); ConvertTo-Json -Compress -Depth 3 -InputObject @{ complete = $true; processes = $rows }`;
31015
31563
  var PI_SCRIPT_PATTERN = /(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;
31016
31564
  function commandArguments(command) {
31017
31565
  return [...command.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2] ?? "");
@@ -31151,6 +31699,29 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
31151
31699
  }
31152
31700
  };
31153
31701
  try {
31702
+ if (windows2 && options.hostImagesOnly) {
31703
+ const details = await inspect("CIM", "powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_FENCE_QUERY], WINDOWS_CIM_TIMEOUT_MS);
31704
+ if (details.exitCode !== 0)
31705
+ throw new ProcessInspectionError(inspection);
31706
+ const value = JSON.parse(details.stdout);
31707
+ if (!value || typeof value !== "object" || !("complete" in value) || value.complete !== true || !("processes" in value))
31708
+ throw new ProcessInspectionError(inspection);
31709
+ const listed = value.processes;
31710
+ const rows = listed === null ? [] : Array.isArray(listed) ? listed : [listed];
31711
+ const processes2 = [];
31712
+ for (const row of rows) {
31713
+ 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))
31714
+ throw new ProcessInspectionError(inspection);
31715
+ const pid = row.ProcessId;
31716
+ if (!/^(?:node|bun)\.exe$/i.test(row.Name))
31717
+ processes2.push({ pid, command: row.Name });
31718
+ else if (typeof row.CommandLine === "string")
31719
+ processes2.push({ pid, command: row.CommandLine });
31720
+ else if (pid !== selfPid)
31721
+ throw new ProcessInspectionError(inspection);
31722
+ }
31723
+ return processes2;
31724
+ }
31154
31725
  const result = await inspect(windows2 ? "tasklist" : "ps", windows2 ? "tasklist.exe" : "ps", windows2 ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
31155
31726
  if (result.exitCode !== 0)
31156
31727
  throw new ProcessInspectionError(inspection);
@@ -31220,7 +31791,11 @@ function createProcessFence(runner = defaultCommandRunner, options = {}) {
31220
31791
  const isHost = (entry) => entry.pid !== selfPid && hostName(entry.command) !== null;
31221
31792
  return {
31222
31793
  async listRunningHosts(env3) {
31223
- return (await listSetupProcesses(runner, { ...options, env: env3 })).filter(isHost);
31794
+ return (await listSetupProcesses(runner, {
31795
+ ...options,
31796
+ env: env3,
31797
+ hostImagesOnly: true
31798
+ })).filter(isHost);
31224
31799
  },
31225
31800
  async previewRunningHosts(env3) {
31226
31801
  const processes = await listSetupProcesses(runner, {
@@ -31244,8 +31819,27 @@ async function assertHostsStopped(fence, env3) {
31244
31819
 
31245
31820
  // src/common-auth-embedded/setup/enroll.js
31246
31821
  var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
31822
+ 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.';
31823
+ var ENROLLMENT_WAIT_MS = 3e5;
31824
+ var APPROVAL_POLL_MS = 1e3;
31825
+ var PROPOSE_BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
31826
+ function safeCode(code2) {
31827
+ return code2 && /^[a-z][a-z0-9_]{0,63}$/.test(code2) ? code2 : "unknown";
31828
+ }
31247
31829
  var HostNotEnrolledError = class extends Error {
31830
+ reason;
31831
+ lastErrorCode;
31832
+ constructor(message, details) {
31833
+ super(message);
31834
+ this.name = "HostNotEnrolledError";
31835
+ this.reason = details.reason;
31836
+ if (details.lastErrorCode !== void 0)
31837
+ this.lastErrorCode = safeCode(details.lastErrorCode);
31838
+ }
31248
31839
  };
31840
+ function approveCommand(requestId, name) {
31841
+ return `ck auth enroll approve --request-id ${requestId} --name ${name}`;
31842
+ }
31249
31843
  async function connectSetupHost(plugin, host, io, terminal, fence) {
31250
31844
  const { name, paths: input2 } = plugin.vault.hosts[host];
31251
31845
  const paths = hostEnrollmentPaths2(input2);
@@ -31254,54 +31848,94 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
31254
31848
  connectionFile: plugin.vault.connectionFile,
31255
31849
  handshakeTimeoutMs: 2e3
31256
31850
  }).catch(() => {
31257
- throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.");
31851
+ throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.", { reason: "connection-failed" });
31258
31852
  });
31853
+ const now = io.now ?? (() => performance.now());
31854
+ const wait2 = io.wait ?? delay;
31259
31855
  try {
31260
31856
  const manager = new ClaustrumEnrollmentManager2({
31261
31857
  proposedName: name,
31262
31858
  paths,
31263
- client: {
31264
- enrollPropose: async (input3) => {
31265
- await fence();
31266
- return client.enrollPropose(input3);
31267
- },
31268
- enrollPoll: async (input3) => {
31269
- await fence();
31270
- return client.enrollPoll(input3);
31271
- }
31272
- },
31859
+ // Each tick of the wait below checks the fence once, just before
31860
+ // reconcile proposes or polls. Checking again inside every vault call
31861
+ // doubled the process listings per tick, and on Windows each listing
31862
+ // starts PowerShell.
31863
+ client,
31273
31864
  writeTokenFile: async (path5, file) => {
31274
31865
  await fence();
31275
31866
  await writeEnrollmentTokenFile3(path5, file);
31276
31867
  }
31277
31868
  });
31869
+ printLine2(terminal, `Asking the vault to connect ${name}\u2026`);
31870
+ const deadline = now() + ENROLLMENT_WAIT_MS;
31278
31871
  let printedRequest;
31279
- for (let tick = 0; tick < 300; tick++) {
31872
+ let lastCode;
31873
+ let reportedCode;
31874
+ let failedProposals = 0;
31875
+ for (; ; ) {
31280
31876
  await fence();
31281
31877
  const status = await manager.reconcile();
31282
31878
  if (status.state === "approved") {
31283
31879
  printLine2(terminal, `Connected ${host} to Claustrum.`);
31284
31880
  return;
31285
31881
  }
31882
+ if (status.state === "unavailable" && status.code === UNSUPPORTED_ENROLLMENT_CODE2)
31883
+ throw new HostNotEnrolledError(UNSUPPORTED_VAULT_MESSAGE, {
31884
+ reason: "unsupported-vault",
31885
+ lastErrorCode: status.code
31886
+ });
31286
31887
  if (status.state !== "pending" && status.state !== "busy")
31287
- throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
31288
- if (status.state === "pending" && status.requestId && status.requestId !== printedRequest) {
31289
- if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
31290
- throw new HostNotEnrolledError("Invalid enrollment request id.");
31291
- printedRequest = status.requestId;
31292
- printLine2(terminal, "Waiting for approval. In another terminal, run:");
31293
- printLine2(terminal, ` ck auth enroll approve --request-id ${status.requestId} --name ${name}`);
31294
- printLine2(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
31295
- }
31296
- await (io.wait ?? delay)(1e3);
31297
- }
31298
- throw new HostNotEnrolledError("Claustrum approval is still pending; approve with ck and rerun setup.");
31888
+ throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.", {
31889
+ reason: "refused",
31890
+ ..."code" in status && { lastErrorCode: status.code }
31891
+ });
31892
+ let pause = APPROVAL_POLL_MS;
31893
+ if (status.state === "busy")
31894
+ lastCode = "busy";
31895
+ else if (status.retryCode)
31896
+ lastCode = status.retryCode;
31897
+ if (status.state === "pending" && status.requestId) {
31898
+ failedProposals = 0;
31899
+ if (status.requestId !== printedRequest) {
31900
+ if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
31901
+ throw new HostNotEnrolledError("Invalid enrollment request id.", {
31902
+ reason: "invalid-request"
31903
+ });
31904
+ printedRequest = status.requestId;
31905
+ printLine2(terminal, "Waiting for approval. In another terminal, run:");
31906
+ printLine2(terminal, ` ${approveCommand(status.requestId, name)}`);
31907
+ printLine2(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
31908
+ }
31909
+ } else if (status.state === "pending" && status.retryCode) {
31910
+ pause = PROPOSE_BACKOFF_MS[Math.min(failedProposals, PROPOSE_BACKOFF_MS.length - 1)] ?? APPROVAL_POLL_MS;
31911
+ failedProposals++;
31912
+ const code3 = safeCode(status.retryCode);
31913
+ if (code3 !== reportedCode) {
31914
+ reportedCode = code3;
31915
+ printLine2(terminal, `The vault has not created the request yet (${code3}); retrying.`);
31916
+ }
31917
+ }
31918
+ const remaining = deadline - now();
31919
+ if (remaining <= 0)
31920
+ break;
31921
+ await wait2(Math.min(pause, remaining));
31922
+ }
31923
+ if (printedRequest)
31924
+ throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
31925
+ reason: "approval-pending",
31926
+ ...lastCode !== void 0 && { lastErrorCode: lastCode }
31927
+ });
31928
+ const code2 = safeCode(lastCode);
31929
+ throw new HostNotEnrolledError(`The vault never created the enrollment request (last error: ${code2}). Check that ck is running, then rerun setup.`, { reason: "request-not-created", lastErrorCode: code2 });
31299
31930
  } catch (error) {
31300
- if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError)
31931
+ if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError || // Built above from fixed text and vetted values only.
31932
+ error instanceof HostNotEnrolledError)
31301
31933
  throw error;
31302
- if (error instanceof HostNotEnrolledError)
31303
- throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE);
31304
- throw new Error(ENROLLMENT_INCOMPLETE_MESSAGE);
31934
+ const code2 = error?.code;
31935
+ throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE, {
31936
+ reason: "incomplete",
31937
+ ...typeof code2 === "string" && { lastErrorCode: code2 }
31938
+ });
31305
31939
  } finally {
31306
31940
  client.close();
31307
31941
  }
@@ -31339,7 +31973,7 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
31339
31973
  // src/common-auth-embedded/setup/config-write.js
31340
31974
  import { randomUUID as randomUUID17 } from "node:crypto";
31341
31975
  import { mkdir as mkdir13, open as open11, rename as rename10, stat as stat9, unlink as unlink10 } from "node:fs/promises";
31342
- import { basename as basename5, dirname as dirname18, join as join13 } from "node:path";
31976
+ import { basename as basename5, dirname as dirname18, join as join15 } from "node:path";
31343
31977
  import { setTimeout as delay2 } from "node:timers/promises";
31344
31978
  async function writeHostConfigAtomic(file, content, options = {}) {
31345
31979
  const windows2 = (options.platform ?? process.platform) === "win32";
@@ -31354,7 +31988,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
31354
31988
  throw error;
31355
31989
  }
31356
31990
  }
31357
- const stage = join13(parent, `.${basename5(file)}.${(options.stageName ?? randomUUID17)()}.tmp`);
31991
+ const stage = join15(parent, `.${basename5(file)}.${(options.stageName ?? randomUUID17)()}.tmp`);
31358
31992
  let created = false;
31359
31993
  try {
31360
31994
  const handle = await open11(stage, "wx", mode ?? 438);
@@ -31721,11 +32355,11 @@ ${write.content}`);
31721
32355
  // src/plugin/vault-activation.ts
31722
32356
  import { readFile as readFile11 } from "node:fs/promises";
31723
32357
  import { homedir as homedir6 } from "node:os";
31724
- import { join as join14 } from "node:path";
32358
+ import { join as join16 } from "node:path";
31725
32359
  var V1_VAULT_ACTIVATION_LABEL = "Activate approved Antigravity vault";
31726
32360
  function nativeOpenCodeAuthPath(env3 = process.env, home = homedir6()) {
31727
- return join14(
31728
- env3.XDG_DATA_HOME || join14(home, ".local", "share"),
32361
+ return join16(
32362
+ env3.XDG_DATA_HOME || join16(home, ".local", "share"),
31729
32363
  "opencode",
31730
32364
  "auth.json"
31731
32365
  );
@@ -31772,7 +32406,7 @@ function createV1VaultActivationMethod(input2) {
31772
32406
 
31773
32407
  // src/plugin/vault-custody.ts
31774
32408
  import { chmod as chmod4, mkdir as mkdir14, readFile as readFile12 } from "node:fs/promises";
31775
- import { dirname as dirname19, join as join15 } from "node:path";
32409
+ import { dirname as dirname19, join as join17 } from "node:path";
31776
32410
 
31777
32411
  // src/plugin/shared/vault-request-credentials.ts
31778
32412
  function vaultAccountRows(routes) {
@@ -32233,12 +32867,12 @@ var OPENCODE_VAULT_HOST = "opencode";
32233
32867
  var OPENCODE_VAULT_ENROLLMENT_NAME = getAntigravityVaultEnrollmentName(OPENCODE_VAULT_HOST);
32234
32868
  var OPENCODE_VAULT_DIR_NAME = "antigravity-auth-vault";
32235
32869
  function openCodeVaultPaths(accountFile) {
32236
- const dir = join15(dirname19(accountFile), OPENCODE_VAULT_DIR_NAME);
32870
+ const dir = join17(dirname19(accountFile), OPENCODE_VAULT_DIR_NAME);
32237
32871
  return {
32238
32872
  dir,
32239
- modeFile: join15(dir, "opencode-mode.json"),
32240
- rosterFile: join15(dir, "opencode-roster.json"),
32241
- stateFile: join15(dir, "opencode-state.json")
32873
+ modeFile: join17(dir, "opencode-mode.json"),
32874
+ rosterFile: join17(dir, "opencode-roster.json"),
32875
+ stateFile: join17(dir, "opencode-state.json")
32242
32876
  };
32243
32877
  }
32244
32878
  async function ensureVaultDir(dir) {
@@ -32586,6 +33220,9 @@ async function refusalOr(step) {
32586
33220
  }
32587
33221
  return "Done. Start a new request to use the change.";
32588
33222
  }
33223
+ function isUnsupportedEnrollment(status) {
33224
+ return status.state === "unavailable" && status.code === UNSUPPORTED_VAULT_CODE;
33225
+ }
32589
33226
  function describeEnrollment(status) {
32590
33227
  switch (status.state) {
32591
33228
  case "idle":
@@ -32599,7 +33236,7 @@ function describeEnrollment(status) {
32599
33236
  case "blocked":
32600
33237
  return `blocked (${status.code})`;
32601
33238
  case "unavailable":
32602
- return `vault unavailable (${status.code})`;
33239
+ return isUnsupportedEnrollment(status) ? "vault too old to connect plugins" : `vault unavailable (${status.code})`;
32603
33240
  case "busy":
32604
33241
  return "another setup step is running";
32605
33242
  }
@@ -32666,10 +33303,15 @@ function enrollmentGuidance(status) {
32666
33303
  return [
32667
33304
  "Resolve the enrollment problem with the vault operator, then request vault access again."
32668
33305
  ];
32669
- if (status.state === "unavailable")
33306
+ if (status.state === "unavailable") {
33307
+ if (isUnsupportedEnrollment(status))
33308
+ return [
33309
+ '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.'
33310
+ ];
32670
33311
  return [
32671
33312
  "Check that the vault is running and its connection file is available, then request vault access again."
32672
33313
  ];
33314
+ }
32673
33315
  if (status.state === "busy")
32674
33316
  return [
32675
33317
  "Another enrollment operation is running. OpenCode will keep checking its outcome in the background."
@@ -32702,7 +33344,7 @@ function statusLines(status) {
32702
33344
  // src/setup.ts
32703
33345
  var PI_PLACEHOLDER_KEY = "antigravity-vault-custody";
32704
33346
  function nativeAuthPath(host, context) {
32705
- return host === "opencode" ? nativeOpenCodeAuthPath() : join16(context.piAgentDir, "auth.json");
33347
+ return host === "opencode" ? nativeOpenCodeAuthPath() : join18(context.piAgentDir, "auth.json");
32706
33348
  }
32707
33349
  function provider(host) {
32708
33350
  return host === "opencode" ? OPENCODE_VAULT_PROVIDER : ANTIGRAVITY_PROVIDER_ID;
@@ -32823,7 +33465,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
32823
33465
  const { openPiSlot: openPiSlot2 } = await loadCommonAuthPiSlot();
32824
33466
  if ((await openPiSlot2({
32825
33467
  authPath: nativeAuthPath(host, context),
32826
- stashPath: join16(piDir, "google-login-stash.json"),
33468
+ stashPath: join18(piDir, "google-login-stash.json"),
32827
33469
  provider: ANTIGRAVITY_PROVIDER_ID,
32828
33470
  placeholderKey: PI_PLACEHOLDER_KEY
32829
33471
  }).inspect()).slot === "placeholder")
@@ -32860,7 +33502,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
32860
33502
  const { openPiSlot: openPiSlot2 } = await loadCommonAuthPiSlot();
32861
33503
  const inspection = await openPiSlot2({
32862
33504
  authPath: nativeAuthPath("pi", context),
32863
- stashPath: join16(piDir, "google-login-stash.json"),
33505
+ stashPath: join18(piDir, "google-login-stash.json"),
32864
33506
  provider: ANTIGRAVITY_PROVIDER_ID,
32865
33507
  placeholderKey: PI_PLACEHOLDER_KEY
32866
33508
  }).inspect();
@@ -32979,7 +33621,7 @@ Setup has not completed the OpenCode 2 native Google connection.
32979
33621
  await assertSetupHostsStopped();
32980
33622
  await openPiSlot2({
32981
33623
  authPath: nativeAuthPath(host, context),
32982
- stashPath: join16(piDir, "google-login-stash.json"),
33624
+ stashPath: join18(piDir, "google-login-stash.json"),
32983
33625
  provider: ANTIGRAVITY_PROVIDER_ID,
32984
33626
  placeholderKey: PI_PLACEHOLDER_KEY
32985
33627
  }).enterVault();
@@ -33999,8 +34641,8 @@ function isTuiConnected(sessionId) {
33999
34641
 
34000
34642
  // src/rpc/rpc-dir.ts
34001
34643
  import { createHash as createHash11 } from "node:crypto";
34002
- import { homedir as homedir8, tmpdir as tmpdir2 } from "node:os";
34003
- import { isAbsolute as isAbsolute4, join as join20, resolve as resolve15 } from "node:path";
34644
+ import { homedir as homedir8, tmpdir as tmpdir4 } from "node:os";
34645
+ import { isAbsolute as isAbsolute4, join as join22, resolve as resolve15 } from "node:path";
34004
34646
  var RPC_DIR_ENV = "ANTIGRAVITY_AUTH_RPC_DIR";
34005
34647
  function getRpcDir(projectDirectory) {
34006
34648
  const override = process.env[RPC_DIR_ENV]?.trim();
@@ -34008,8 +34650,8 @@ function getRpcDir(projectDirectory) {
34008
34650
  return isAbsolute4(override) ? override : resolve15(projectDirectory, override);
34009
34651
  }
34010
34652
  const projectHash = createHash11("sha256").update(resolve15(projectDirectory)).digest("hex").slice(0, 16);
34011
- const stateHome = process.env.XDG_STATE_HOME ?? join20(homedir8(), ".local", "state");
34012
- return join20(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
34653
+ const stateHome = process.env.XDG_STATE_HOME ?? join22(homedir8(), ".local", "state");
34654
+ return join22(stateHome, "cortexkit", "antigravity-auth", "rpc", projectHash);
34013
34655
  }
34014
34656
 
34015
34657
  // src/common-auth-embedded/rpc/notifications.js
@@ -34020,7 +34662,7 @@ function isSessionId(value) {
34020
34662
  // src/common-auth-embedded/rpc/port-file.js
34021
34663
  import { createHash as createHash12, randomUUID as randomUUID18 } from "node:crypto";
34022
34664
  import { chmod as chmod5, mkdir as mkdir15, open as open12, readdir, rename as rename11, rmdir as rmdir2, stat as stat10, unlink as unlink11 } from "node:fs/promises";
34023
- import { join as join21, resolve as resolve16 } from "node:path";
34665
+ import { join as join23, resolve as resolve16 } from "node:path";
34024
34666
  function isProbeablePid(pid) {
34025
34667
  return typeof pid === "number" && Number.isSafeInteger(pid) && pid > 0;
34026
34668
  }
@@ -34051,7 +34693,7 @@ async function removeCorruptPortFile(portFile, log16) {
34051
34693
  }
34052
34694
  async function writePortFile(dir, entry, options = {}) {
34053
34695
  const writeOnce = async () => {
34054
- const target = join21(dir, `port-${entry.pid}.json`);
34696
+ const target = join23(dir, `port-${entry.pid}.json`);
34055
34697
  if (windowsPrivateFiles2) {
34056
34698
  await ensurePrivateDirectory3(dir, options.secureDir ?? false);
34057
34699
  await options.beforeWrite?.();
@@ -34112,7 +34754,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
34112
34754
  if (!projectDir.isDirectory() || !isManagedDir(projectDir.name)) {
34113
34755
  continue;
34114
34756
  }
34115
- const dir = join21(root, projectDir.name);
34757
+ const dir = join23(root, projectDir.name);
34116
34758
  let names;
34117
34759
  try {
34118
34760
  names = await readdir(dir);
@@ -34124,7 +34766,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
34124
34766
  for (const name of names) {
34125
34767
  if (!name.startsWith("port-") || !name.endsWith(".json"))
34126
34768
  continue;
34127
- const portFile = join21(dir, name);
34769
+ const portFile = join23(dir, name);
34128
34770
  let raw;
34129
34771
  try {
34130
34772
  raw = await readPrivateText2(portFile);
@@ -34161,7 +34803,7 @@ async function sweepRpcState(root, activeDir, isManagedDir, log16) {
34161
34803
  import { randomBytes as randomBytes6, timingSafeEqual } from "node:crypto";
34162
34804
  import { unlink as unlink12 } from "node:fs/promises";
34163
34805
  import { createServer as createServer2 } from "node:http";
34164
- import { join as join22 } from "node:path";
34806
+ import { join as join24 } from "node:path";
34165
34807
  var RpcRequestError = class extends Error {
34166
34808
  status;
34167
34809
  constructor(status, message) {
@@ -34413,7 +35055,7 @@ async function startRpcServer(options) {
34413
35055
  for (const socket of connections)
34414
35056
  socket.destroy();
34415
35057
  });
34416
- const portFile = join22(options.dir, `port-${process.pid}.json`);
35058
+ const portFile = join24(options.dir, `port-${process.pid}.json`);
34417
35059
  const current = await readPrivateText2(portFile).then((raw) => JSON.parse(raw)).catch((error) => {
34418
35060
  if (error instanceof PrivateFileError2 && error.code !== "ENOENT")
34419
35061
  throw error;
@@ -35475,7 +36117,7 @@ import { createInterface as createInterface2 } from "node:readline/promises";
35475
36117
  // src/plugin/config/updater.ts
35476
36118
  import { existsSync as existsSync8, mkdirSync as mkdirSync4, readFileSync as readFileSync7, writeFileSync as writeFileSync4 } from "node:fs";
35477
36119
  import { homedir as homedir9 } from "node:os";
35478
- import { dirname as dirname21, join as join23 } from "node:path";
36120
+ import { dirname as dirname21, join as join25 } from "node:path";
35479
36121
  var PLUGIN_NAME = "@cortexkit/opencode-antigravity-auth@latest";
35480
36122
  var SCHEMA_URL = "https://opencode.ai/config.json";
35481
36123
  var OPENCODE_JSON_FILENAME = "opencode.json";
@@ -35487,13 +36129,13 @@ function stripJsonCommentsAndTrailingCommas(json) {
35487
36129
  ).replace(/,(\s*[}\]])/g, "$1");
35488
36130
  }
35489
36131
  function getOpencodeConfigDir() {
35490
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join23(homedir9(), ".config");
35491
- return join23(xdgConfig2, "opencode");
36132
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join25(homedir9(), ".config");
36133
+ return join25(xdgConfig2, "opencode");
35492
36134
  }
35493
36135
  function getOpencodeConfigPath() {
35494
36136
  const configDir = getOpencodeConfigDir();
35495
- const jsoncPath = join23(configDir, OPENCODE_JSONC_FILENAME);
35496
- const jsonPath = join23(configDir, OPENCODE_JSON_FILENAME);
36137
+ const jsoncPath = join25(configDir, OPENCODE_JSONC_FILENAME);
36138
+ const jsonPath = join25(configDir, OPENCODE_JSON_FILENAME);
35497
36139
  if (existsSync8(jsoncPath)) {
35498
36140
  return jsoncPath;
35499
36141
  }
@@ -38214,21 +38856,21 @@ import {
38214
38856
  unlinkSync as unlinkSync3,
38215
38857
  writeFileSync as writeFileSync5
38216
38858
  } from "node:fs";
38217
- import { homedir as homedir10, tmpdir as tmpdir3 } from "node:os";
38218
- import { dirname as dirname22, join as join24 } from "node:path";
38859
+ import { homedir as homedir10, tmpdir as tmpdir5 } from "node:os";
38860
+ import { dirname as dirname22, join as join26 } from "node:path";
38219
38861
  function getConfigDir3() {
38220
38862
  const platform = process.platform;
38221
38863
  if (platform === "win32") {
38222
- return join24(
38223
- process.env.APPDATA || join24(homedir10(), "AppData", "Roaming"),
38864
+ return join26(
38865
+ process.env.APPDATA || join26(homedir10(), "AppData", "Roaming"),
38224
38866
  "opencode"
38225
38867
  );
38226
38868
  }
38227
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join24(homedir10(), ".config");
38228
- return join24(xdgConfig2, "opencode");
38869
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join26(homedir10(), ".config");
38870
+ return join26(xdgConfig2, "opencode");
38229
38871
  }
38230
38872
  function getSignatureCacheFilePath() {
38231
- return join24(getConfigDir3(), "antigravity-signature-cache.json");
38873
+ return join26(getConfigDir3(), "antigravity-signature-cache.json");
38232
38874
  }
38233
38875
  var SignatureCache = class {
38234
38876
  // In-memory cache: key -> entry with signature and optional thinking text
@@ -38511,8 +39153,8 @@ var SignatureCache = class {
38511
39153
  last_write: now
38512
39154
  }
38513
39155
  };
38514
- const tmpPath = join24(
38515
- tmpdir3(),
39156
+ const tmpPath = join26(
39157
+ tmpdir5(),
38516
39158
  `antigravity-cache-${Date.now()}-${Math.random().toString(36).slice(2)}.tmp`
38517
39159
  );
38518
39160
  writeFileSync5(tmpPath, JSON.stringify(cacheData, null, 2), "utf-8");
@@ -38579,7 +39221,7 @@ var SignatureCache = class {
38579
39221
  // src/plugin/config/loader.ts
38580
39222
  import { existsSync as existsSync10, readFileSync as readFileSync10, realpathSync as realpathSync3 } from "node:fs";
38581
39223
  import { homedir as homedir11 } from "node:os";
38582
- import { basename as basename6, dirname as dirname23, join as join25, resolve as resolve17 } from "node:path";
39224
+ import { basename as basename6, dirname as dirname23, join as join27, resolve as resolve17 } from "node:path";
38583
39225
 
38584
39226
  // src/plugin/config/schema.ts
38585
39227
  import { z } from "zod";
@@ -39074,14 +39716,14 @@ function getConfigDir4() {
39074
39716
  if (process.env.OPENCODE_CONFIG_DIR) {
39075
39717
  return process.env.OPENCODE_CONFIG_DIR;
39076
39718
  }
39077
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join25(homedir11(), ".config");
39078
- return join25(xdgConfig2, "opencode");
39719
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join27(homedir11(), ".config");
39720
+ return join27(xdgConfig2, "opencode");
39079
39721
  }
39080
39722
  function getUserConfigPath() {
39081
- return join25(getConfigDir4(), "antigravity.json");
39723
+ return join27(getConfigDir4(), "antigravity.json");
39082
39724
  }
39083
39725
  function getProjectConfigPath(directory) {
39084
- return join25(directory, ".opencode", "antigravity.json");
39726
+ return join27(directory, ".opencode", "antigravity.json");
39085
39727
  }
39086
39728
  function loadConfigFile(path5, log16) {
39087
39729
  try {
@@ -39142,7 +39784,7 @@ function canonicalizeOwnedPath(path5) {
39142
39784
  let current = absolute;
39143
39785
  for (; ; ) {
39144
39786
  try {
39145
- return join25(realpathSync3(current), ...missing.reverse());
39787
+ return join27(realpathSync3(current), ...missing.reverse());
39146
39788
  } catch {
39147
39789
  const parent = dirname23(current);
39148
39790
  if (parent === current) return absolute;
@@ -39448,9 +40090,9 @@ function clearSignatureCache(sessionId) {
39448
40090
  // src/plugin/image-saver.ts
39449
40091
  import { chmodSync as chmodSync4, existsSync as existsSync11, mkdirSync as mkdirSync6, writeFileSync as writeFileSync6 } from "node:fs";
39450
40092
  import { homedir as homedir12 } from "node:os";
39451
- import { join as join26 } from "node:path";
40093
+ import { join as join28 } from "node:path";
39452
40094
  function getImageOutputDir(outputDir) {
39453
- const resolved = outputDir ?? join26(homedir12(), ".opencode", "generated-images");
40095
+ const resolved = outputDir ?? join28(homedir12(), ".opencode", "generated-images");
39454
40096
  if (!existsSync11(resolved)) {
39455
40097
  mkdirSync6(resolved, { recursive: true, mode: 448 });
39456
40098
  }
@@ -39473,7 +40115,7 @@ function generateImageFilename(mimeType) {
39473
40115
  function saveImageToDisk(base64Data, mimeType, outputDir) {
39474
40116
  try {
39475
40117
  const resolvedOutputDir = getImageOutputDir(outputDir);
39476
- const filePath = join26(resolvedOutputDir, generateImageFilename(mimeType));
40118
+ const filePath = join28(resolvedOutputDir, generateImageFilename(mimeType));
39477
40119
  writeFileSync6(filePath, Buffer.from(base64Data, "base64"), { mode: 384 });
39478
40120
  chmodSync4(filePath, 384);
39479
40121
  return filePath;
@@ -39908,11 +40550,11 @@ data: ${JSON.stringify(syntheticUsage)}
39908
40550
  // src/plugin/gemini-dump.ts
39909
40551
  import { createHash as createHash14 } from "node:crypto";
39910
40552
  import { appendFileSync as appendFileSync4, mkdirSync as mkdirSync7, writeFileSync as writeFileSync7 } from "node:fs";
39911
- import { tmpdir as tmpdir4 } from "node:os";
39912
- import { join as join27 } from "node:path";
40553
+ import { tmpdir as tmpdir6 } from "node:os";
40554
+ import { join as join29 } from "node:path";
39913
40555
  var DUMP_STATUS_TITLE = "## Gemini Dump Status";
39914
40556
  var DUMP_DIR_ENV = "OPENCODE_ANTIGRAVITY_GEMINI_DUMP_DIR";
39915
- var DEFAULT_DUMP_DIR = join27(tmpdir4(), "opencode-antigravity-gemini-dumps");
40557
+ var DEFAULT_DUMP_DIR = join29(tmpdir6(), "opencode-antigravity-gemini-dumps");
39916
40558
  var DUMP_DIR_MODE = 448;
39917
40559
  var DUMP_FILE_MODE = 384;
39918
40560
  var nextDumpId = 0;
@@ -40066,7 +40708,7 @@ function writeGeminiDump(input2) {
40066
40708
  nextDumpId += 1;
40067
40709
  const id = `${(/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-")}-${String(nextDumpId).padStart(5, "0")}-${input2.streaming ? "stream" : "json"}`;
40068
40710
  const dumpDir = getGeminiDumpDirectory();
40069
- const prefix = join27(dumpDir, id);
40711
+ const prefix = join29(dumpDir, id);
40070
40712
  mkdirSync7(dumpDir, { recursive: true, mode: DUMP_DIR_MODE });
40071
40713
  const context = {
40072
40714
  id,
@@ -40150,21 +40792,21 @@ import {
40150
40792
  unlinkSync as unlinkSync4,
40151
40793
  writeFileSync as writeFileSync8
40152
40794
  } from "node:fs";
40153
- import { join as join29 } from "node:path";
40795
+ import { join as join31 } from "node:path";
40154
40796
 
40155
40797
  // src/plugin/recovery/constants.ts
40156
40798
  import { homedir as homedir13 } from "node:os";
40157
- import { join as join28 } from "node:path";
40799
+ import { join as join30 } from "node:path";
40158
40800
  function getXdgData() {
40159
40801
  const platform = process.platform;
40160
40802
  if (platform === "win32") {
40161
- return process.env.APPDATA || join28(homedir13(), "AppData", "Roaming");
40803
+ return process.env.APPDATA || join30(homedir13(), "AppData", "Roaming");
40162
40804
  }
40163
- return process.env.XDG_DATA_HOME || join28(homedir13(), ".local", "share");
40805
+ return process.env.XDG_DATA_HOME || join30(homedir13(), ".local", "share");
40164
40806
  }
40165
- var OPENCODE_STORAGE = join28(getXdgData(), "opencode", "storage");
40166
- var MESSAGE_STORAGE = join28(OPENCODE_STORAGE, "message");
40167
- var PART_STORAGE = join28(OPENCODE_STORAGE, "part");
40807
+ var OPENCODE_STORAGE = join30(getXdgData(), "opencode", "storage");
40808
+ var MESSAGE_STORAGE = join30(OPENCODE_STORAGE, "message");
40809
+ var PART_STORAGE = join30(OPENCODE_STORAGE, "part");
40168
40810
  var THINKING_TYPES = /* @__PURE__ */ new Set([
40169
40811
  "thinking",
40170
40812
  "redacted_thinking",
@@ -40174,13 +40816,13 @@ var THINKING_TYPES = /* @__PURE__ */ new Set([
40174
40816
  // src/plugin/recovery/storage.ts
40175
40817
  function getMessageDir(sessionID) {
40176
40818
  if (!existsSync12(MESSAGE_STORAGE)) return "";
40177
- const directPath = join29(MESSAGE_STORAGE, sessionID);
40819
+ const directPath = join31(MESSAGE_STORAGE, sessionID);
40178
40820
  if (existsSync12(directPath)) {
40179
40821
  return directPath;
40180
40822
  }
40181
40823
  try {
40182
40824
  for (const dir of readdirSync2(MESSAGE_STORAGE)) {
40183
- const sessionPath = join29(MESSAGE_STORAGE, dir, sessionID);
40825
+ const sessionPath = join31(MESSAGE_STORAGE, dir, sessionID);
40184
40826
  if (existsSync12(sessionPath)) {
40185
40827
  return sessionPath;
40186
40828
  }
@@ -40197,7 +40839,7 @@ function readMessages(sessionID) {
40197
40839
  for (const file of readdirSync2(messageDir)) {
40198
40840
  if (!file.endsWith(".json")) continue;
40199
40841
  try {
40200
- const content = readFileSync11(join29(messageDir, file), "utf-8");
40842
+ const content = readFileSync11(join31(messageDir, file), "utf-8");
40201
40843
  messages.push(JSON.parse(content));
40202
40844
  } catch {
40203
40845
  }
@@ -40213,14 +40855,14 @@ function readMessages(sessionID) {
40213
40855
  });
40214
40856
  }
40215
40857
  function readParts(messageID) {
40216
- const partDir = join29(PART_STORAGE, messageID);
40858
+ const partDir = join31(PART_STORAGE, messageID);
40217
40859
  if (!existsSync12(partDir)) return [];
40218
40860
  const parts = [];
40219
40861
  try {
40220
40862
  for (const file of readdirSync2(partDir)) {
40221
40863
  if (!file.endsWith(".json")) continue;
40222
40864
  try {
40223
- const content = readFileSync11(join29(partDir, file), "utf-8");
40865
+ const content = readFileSync11(join31(partDir, file), "utf-8");
40224
40866
  parts.push(JSON.parse(content));
40225
40867
  } catch {
40226
40868
  }
@@ -40262,7 +40904,7 @@ function findMessagesWithOrphanThinking(sessionID) {
40262
40904
  return result;
40263
40905
  }
40264
40906
  function prependThinkingPart(sessionID, messageID) {
40265
- const partDir = join29(PART_STORAGE, messageID);
40907
+ const partDir = join31(PART_STORAGE, messageID);
40266
40908
  try {
40267
40909
  if (!existsSync12(partDir)) {
40268
40910
  mkdirSync8(partDir, { recursive: true });
@@ -40277,7 +40919,7 @@ function prependThinkingPart(sessionID, messageID) {
40277
40919
  synthetic: true
40278
40920
  };
40279
40921
  writeFileSync8(
40280
- join29(partDir, `${partId}.json`),
40922
+ join31(partDir, `${partId}.json`),
40281
40923
  JSON.stringify(part, null, 2)
40282
40924
  );
40283
40925
  return true;
@@ -40286,14 +40928,14 @@ function prependThinkingPart(sessionID, messageID) {
40286
40928
  }
40287
40929
  }
40288
40930
  function stripThinkingParts(messageID) {
40289
- const partDir = join29(PART_STORAGE, messageID);
40931
+ const partDir = join31(PART_STORAGE, messageID);
40290
40932
  if (!existsSync12(partDir)) return false;
40291
40933
  let anyRemoved = false;
40292
40934
  try {
40293
40935
  for (const file of readdirSync2(partDir)) {
40294
40936
  if (!file.endsWith(".json")) continue;
40295
40937
  try {
40296
- const filePath = join29(partDir, file);
40938
+ const filePath = join31(partDir, file);
40297
40939
  const content = readFileSync11(filePath, "utf-8");
40298
40940
  const part = JSON.parse(content);
40299
40941
  if (THINKING_TYPES.has(part.type)) {
@@ -45944,15 +46586,15 @@ function projectCommandAccountRows(storage) {
45944
46586
 
45945
46587
  // src/plugin/dependencies.ts
45946
46588
  import { homedir as homedir14 } from "node:os";
45947
- import { join as join30 } from "node:path";
46589
+ import { join as join32 } from "node:path";
45948
46590
  function defaultFilesystemRoots() {
45949
- const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join30(homedir14(), ".config");
45950
- const xdgState2 = process.env.XDG_STATE_HOME ?? join30(homedir14(), ".local", "state");
46591
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME ?? join32(homedir14(), ".config");
46592
+ const xdgState2 = process.env.XDG_STATE_HOME ?? join32(homedir14(), ".local", "state");
45951
46593
  return {
45952
46594
  projectRoot: process.cwd(),
45953
- userConfigRoot: join30(xdgConfig2, "opencode"),
45954
- sidebarStateRoot: join30(xdgState2, "cortexkit", "antigravity-auth"),
45955
- rpcRoot: join30(xdgState2, "cortexkit", "antigravity-auth", "rpc")
46595
+ userConfigRoot: join32(xdgConfig2, "opencode"),
46596
+ sidebarStateRoot: join32(xdgState2, "cortexkit", "antigravity-auth"),
46597
+ rpcRoot: join32(xdgState2, "cortexkit", "antigravity-auth", "rpc")
45956
46598
  };
45957
46599
  }
45958
46600
  function resolvePluginDependencies(overrides = {}) {
@@ -47704,6 +48346,7 @@ function createRequestExecutor(deps) {
47704
48346
  next = await deadline.wait(
47705
48347
  () => credentials.admit({ account, signal: abortSignal })
47706
48348
  );
48349
+ checkAborted();
47707
48350
  } catch {
47708
48351
  checkAborted();
47709
48352
  }
@@ -48558,8 +49201,8 @@ function extractRateLimitBodyInfo(body) {
48558
49201
  }
48559
49202
  }
48560
49203
  if (message) {
48561
- const afterMatch = message.match(/reset after\s+([0-9hms.]+)/i);
48562
- const rawDuration = afterMatch?.[1];
49204
+ const reset = message.match(/(?:reset after|resets? in)\s+([0-9hms.]+)/i);
49205
+ const rawDuration = reset?.[1];
48563
49206
  if (rawDuration) {
48564
49207
  const parsed = parseDurationToMs(rawDuration);
48565
49208
  if (parsed !== null) {
@@ -49088,6 +49731,19 @@ function createGoogleSearchTool({
49088
49731
  // src/plugin/lifecycle.ts
49089
49732
  var NOOP_DRAIN = async () => {
49090
49733
  };
49734
+ async function collectCleanupFailure(cleanup2, failures) {
49735
+ try {
49736
+ await cleanup2();
49737
+ } catch (error) {
49738
+ failures.push(error);
49739
+ }
49740
+ }
49741
+ function reportCleanupFailures(failures) {
49742
+ if (failures.length === 1) throw failures[0];
49743
+ if (failures.length > 1) {
49744
+ throw new AggregateError(failures, "Plugin cleanup failed");
49745
+ }
49746
+ }
49091
49747
  function createPluginLifecycle(options) {
49092
49748
  let accountManager = null;
49093
49749
  let refreshQueue = null;
@@ -49099,19 +49755,19 @@ function createPluginLifecycle(options) {
49099
49755
  const consumers = [];
49100
49756
  const drainSidebarWrites2 = options.drainSidebarWrites ?? NOOP_DRAIN;
49101
49757
  const retire2 = (manager, queue2, requests) => {
49102
- const queueDrained = Promise.resolve(queue2?.dispose());
49758
+ const queueDrained = (async () => {
49759
+ await queue2?.dispose();
49760
+ })();
49103
49761
  const record3 = {
49104
49762
  requests,
49105
49763
  done: (async () => {
49106
- const drained = await Promise.allSettled([
49107
- queueDrained,
49108
- requests?.retire()
49764
+ const failures = [];
49765
+ await Promise.all([
49766
+ collectCleanupFailure(() => queueDrained, failures),
49767
+ collectCleanupFailure(() => requests?.retire(), failures)
49109
49768
  ]);
49110
- await manager.dispose();
49111
- const failed = drained.find(
49112
- (outcome) => outcome.status === "rejected"
49113
- );
49114
- if (failed) throw failed.reason;
49769
+ await collectCleanupFailure(() => manager.dispose(), failures);
49770
+ reportCleanupFailures(failures);
49115
49771
  })()
49116
49772
  };
49117
49773
  retiring.add(record3);
@@ -49121,8 +49777,6 @@ function createPluginLifecycle(options) {
49121
49777
  if (!requests) retiring.delete(record3);
49122
49778
  }
49123
49779
  );
49124
- void queueDrained.catch(() => {
49125
- });
49126
49780
  return { queueDrained, done: record3.done };
49127
49781
  };
49128
49782
  const disposeAccountRuntime = async () => {
@@ -49134,23 +49788,26 @@ function createPluginLifecycle(options) {
49134
49788
  accountRequests = null;
49135
49789
  const retired = [...retiring];
49136
49790
  retiring.clear();
49791
+ const failures = [];
49137
49792
  const aborted = Promise.all([
49138
- oldRequests?.dispose(),
49139
- ...retired.map((record3) => record3.requests?.dispose())
49793
+ collectCleanupFailure(() => oldRequests?.dispose(), failures),
49794
+ ...retired.map(
49795
+ (record3) => collectCleanupFailure(() => record3.requests?.dispose(), failures)
49796
+ )
49140
49797
  ]);
49141
- const liveQueueDrained = Promise.resolve(oldQueue?.dispose());
49142
- void liveQueueDrained.catch(() => {
49143
- });
49144
- await aborted;
49145
- const retirements = await Promise.allSettled(
49146
- retired.map((record3) => record3.done)
49147
- );
49148
- await liveQueueDrained;
49149
- await oldManager?.dispose();
49150
- const failed = retirements.find(
49151
- (outcome) => outcome.status === "rejected"
49798
+ const liveQueueDrained = collectCleanupFailure(
49799
+ () => oldQueue?.dispose(),
49800
+ failures
49152
49801
  );
49153
- if (failed) throw failed.reason;
49802
+ await Promise.all([
49803
+ aborted,
49804
+ liveQueueDrained,
49805
+ ...retired.map(
49806
+ (record3) => collectCleanupFailure(() => record3.done, failures)
49807
+ )
49808
+ ]);
49809
+ await collectCleanupFailure(() => oldManager?.dispose(), failures);
49810
+ reportCleanupFailures(failures);
49154
49811
  };
49155
49812
  const register = (disposable, phase = "consumer") => {
49156
49813
  if (closing) {
@@ -49205,19 +49862,27 @@ function createPluginLifecycle(options) {
49205
49862
  failDisposal = reject;
49206
49863
  });
49207
49864
  void (async () => {
49208
- await disposeAccountRuntime();
49209
- await options.shutdownDiskSignatureCache();
49210
- options.sessionRegistry.clear();
49211
- options.clearFetchState();
49865
+ const failures = [];
49866
+ await collectCleanupFailure(disposeAccountRuntime, failures);
49867
+ await collectCleanupFailure(
49868
+ () => options.shutdownDiskSignatureCache(),
49869
+ failures
49870
+ );
49871
+ await collectCleanupFailure(
49872
+ () => options.sessionRegistry.clear(),
49873
+ failures
49874
+ );
49875
+ await collectCleanupFailure(() => options.clearFetchState(), failures);
49212
49876
  for (const disposable of producers) {
49213
- await disposable.dispose();
49877
+ await collectCleanupFailure(() => disposable.dispose(), failures);
49214
49878
  }
49215
49879
  producers.length = 0;
49216
- await drainSidebarWrites2();
49880
+ await collectCleanupFailure(drainSidebarWrites2, failures);
49217
49881
  for (const disposable of consumers) {
49218
- await disposable.dispose();
49882
+ await collectCleanupFailure(() => disposable.dispose(), failures);
49219
49883
  }
49220
49884
  consumers.length = 0;
49885
+ reportCleanupFailures(failures);
49221
49886
  })().then(finishDisposal, failDisposal);
49222
49887
  }
49223
49888
  return disposal;
@@ -49595,7 +50260,7 @@ var createAntigravityPlugin = (providerId, options = {}) => async (input2) => {
49595
50260
  lifecycle.register(vaultQuotaPoller, "producer");
49596
50261
  }
49597
50262
  const operatorSettings = createOperatorSettingsController({
49598
- projectConfigPath: join31(directory, ".opencode", "antigravity.json"),
50263
+ projectConfigPath: join33(directory, ".opencode", "antigravity.json"),
49599
50264
  // getUserConfigPath() already returns the full file path including
49600
50265
  // 'antigravity.json' — do NOT join again or the path double-nests
49601
50266
  // into <dir>/antigravity.json/antigravity.json.