@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/cli.js CHANGED
@@ -765,7 +765,8 @@ var init_identity = __esm({
765
765
  // ../core/dist/common-auth-embedded/fs/private-files.js
766
766
  import { randomUUID as randomUUID5 } from "node:crypto";
767
767
  import { lstat as lstat2, readFile as readFile4, rename as rename3, unlink as unlink5 } from "node:fs/promises";
768
- import { dirname as dirname5, resolve as resolve2 } from "node:path";
768
+ import { tmpdir } from "node:os";
769
+ import { dirname as dirname5, join as join4, resolve as resolve2 } from "node:path";
769
770
  function ioCode(detail) {
770
771
  if (detail?.reason === "io-error") {
771
772
  if (detail.win32Code === 2 || detail.win32Code === 3)
@@ -775,8 +776,31 @@ function ioCode(detail) {
775
776
  }
776
777
  return detail?.code ?? "ERR_PRIVATE_FILE";
777
778
  }
779
+ function privateFilesUnavailable(cause) {
780
+ return Object.assign(new Error("Windows private-files native addon is unavailable", { cause }), {
781
+ code: "ERR_PRIVATE_FILES_UNAVAILABLE",
782
+ reason: PRIVATE_FILES_UNAVAILABLE_REASON
783
+ });
784
+ }
785
+ function isUnavailable(api, error) {
786
+ return error instanceof api.PrivateFilesUnavailableError || error?.code === "ERR_PRIVATE_FILES_UNAVAILABLE";
787
+ }
788
+ async function assertNativeAddonLoads(api) {
789
+ try {
790
+ await api.verifyPrivatePath(join4(tmpdir(), `.common-auth-private-files-probe-${randomUUID5()}`), "file");
791
+ } catch (error) {
792
+ if (isUnavailable(api, error))
793
+ throw privateFilesUnavailable(error);
794
+ }
795
+ }
778
796
  function loadBackend() {
779
- backend ??= import("@cortexkit/private-files");
797
+ backend ??= import("@cortexkit/private-files").then(async (api) => {
798
+ if (windowsPrivateFiles)
799
+ await assertNativeAddonLoads(api);
800
+ return api;
801
+ }, (cause) => {
802
+ throw windowsPrivateFiles ? privateFilesUnavailable(cause) : cause;
803
+ });
780
804
  return backend;
781
805
  }
782
806
  async function privateOperation(path2, stage, operation) {
@@ -1002,12 +1026,13 @@ async function writePrivateAtomic(path2, bytes, options = {}) {
1002
1026
  });
1003
1027
  }
1004
1028
  }
1005
- var windowsPrivateFiles, migrationNotices, backend, PrivateFileError, safeParentOptionsForTest;
1029
+ var windowsPrivateFiles, migrationNotices, backend, PRIVATE_FILES_UNAVAILABLE_REASON, PrivateFileError, safeParentOptionsForTest;
1006
1030
  var init_private_files = __esm({
1007
1031
  "../core/dist/common-auth-embedded/fs/private-files.js"() {
1008
1032
  "use strict";
1009
1033
  windowsPrivateFiles = process.platform === "win32";
1010
1034
  migrationNotices = /* @__PURE__ */ new Set();
1035
+ PRIVATE_FILES_UNAVAILABLE_REASON = "native-addon-unavailable";
1011
1036
  PrivateFileError = class extends Error {
1012
1037
  path;
1013
1038
  stage;
@@ -1022,7 +1047,7 @@ var init_private_files = __esm({
1022
1047
  orphanPath;
1023
1048
  constructor(path2, stage, cause) {
1024
1049
  const detail = cause;
1025
- super(`Private file refused at ${stage}: ${path2} (${detail?.reason ?? detail?.code ?? "io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`, { cause });
1050
+ super(detail?.code === "ERR_PRIVATE_FILES_UNAVAILABLE" ? `Private file refused at ${stage}: ${path2} (${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}: ${path2} (${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 });
1026
1051
  this.path = path2;
1027
1052
  this.stage = stage;
1028
1053
  this.name = "PrivateFileError";
@@ -1133,7 +1158,7 @@ var init_atomic_write = __esm({
1133
1158
  // ../core/dist/common-auth-embedded/fs/refresh-file-lock.js
1134
1159
  import { randomUUID as randomUUID7 } from "node:crypto";
1135
1160
  import { mkdir as mkdir7, open as open4, readFile as readFile5, rename as rename5, rm as rm4, stat as stat3 } from "node:fs/promises";
1136
- import { dirname as dirname7, join as join4 } from "node:path";
1161
+ import { dirname as dirname7, join as join5 } from "node:path";
1137
1162
  async function createExclusiveText(path2, text2) {
1138
1163
  const handle = await open4(path2, "wx", 384);
1139
1164
  try {
@@ -1151,7 +1176,7 @@ function acquireRefreshFileLock(options) {
1151
1176
  }
1152
1177
  async function acquireRefreshFileLockWithClock(options) {
1153
1178
  const lockPath = lockPathFor(options.path, options.name);
1154
- const legacyOwnerPath = join4(lockPath, "owner.json");
1179
+ const legacyOwnerPath = join5(lockPath, "owner.json");
1155
1180
  const ownerId = randomUUID7();
1156
1181
  const now = options.now ?? Date.now;
1157
1182
  let renewTimer = null;
@@ -1194,7 +1219,7 @@ async function acquireRefreshFileLockWithClock(options) {
1194
1219
  let terminalIOError;
1195
1220
  let renewalInFlight = null;
1196
1221
  const evictPath = `${lockPath}.evicting`;
1197
- const evictOwnerPath = join4(evictPath, "owner.json");
1222
+ const evictOwnerPath = join5(evictPath, "owner.json");
1198
1223
  const evictOwnerId = randomUUID7();
1199
1224
  const EVICT_TTL = 5e3;
1200
1225
  const MAX_STEAL_ATTEMPTS = 8;
@@ -3172,13 +3197,40 @@ var init_runtime = __esm({
3172
3197
  });
3173
3198
 
3174
3199
  // ../core/dist/common-auth-embedded/store/attribution.js
3200
+ function assertQuotaEpoch(id, attribution) {
3201
+ if (!isCredentialEpoch(attribution?.credentialEpoch))
3202
+ throw refusal2("pull", id, "invalid-input", "the credential epoch the reading was issued for must be a positive safe integer");
3203
+ }
3204
+ function assertQuotaRow(id, attribution, row) {
3205
+ if (!row)
3206
+ throw unknownRow("pull", id);
3207
+ if (row.invalid)
3208
+ throw refusal2("pull", id, "invalid-row", `row ${id} is invalid`);
3209
+ if (!row.credential)
3210
+ throw refusal2("pull", id, "no-credential", `row ${id} holds no credential`);
3211
+ requireBound("pull", row);
3212
+ if (row.torn || !row.hasEntry || row.credentialEpoch !== attribution.credentialEpoch || row.identity !== attribution.identity)
3213
+ throw new PoolOperationError({
3214
+ operation: "pull",
3215
+ rowId: id,
3216
+ phase: "pull",
3217
+ retryable: true,
3218
+ kind: "attribution",
3219
+ message: `quota for ${id} was issued for a credential the row no longer holds`
3220
+ });
3221
+ }
3222
+ function mergedQuota(ctx, id, stored, observation) {
3223
+ const merged = ctx.codec.merge(stored, observation);
3224
+ if (!ctx.codec.validate(merged))
3225
+ throw refusal2("pull", id, "invalid-quota", "the quota codec rejected the merged map");
3226
+ return merged;
3227
+ }
3175
3228
  async function recordQuota(rt, id, attribution, observation) {
3176
3229
  const { ctx } = rt;
3177
3230
  const locks = new LockStack(ctx.lockDefaults, ctx.lockEnv);
3178
3231
  const progress = { writes: 0 };
3179
3232
  try {
3180
- if (!isCredentialEpoch(attribution?.credentialEpoch))
3181
- throw refusal2("pull", id, "invalid-input", "the credential epoch the reading was issued for must be a positive safe integer");
3233
+ assertQuotaEpoch(id, attribution);
3182
3234
  await withTransaction(
3183
3235
  ctx,
3184
3236
  locks,
@@ -3187,26 +3239,11 @@ async function recordQuota(rt, id, attribution, observation) {
3187
3239
  async (tx) => {
3188
3240
  tx.assertNotStaged(id);
3189
3241
  const row = tx.row(id);
3190
- if (!row)
3191
- throw unknownRow("pull", id);
3192
- if (row.invalid)
3193
- throw refusal2("pull", id, "invalid-row", `row ${id} is invalid`);
3194
- if (!row.credential)
3195
- throw refusal2("pull", id, "no-credential", `row ${id} holds no credential`);
3196
- requireBound("pull", row);
3242
+ assertQuotaRow(id, attribution, row);
3197
3243
  const entry = tx.entry(id);
3198
- if (row.torn || !entry || entry.credentialEpoch !== attribution.credentialEpoch || row.identity !== attribution.identity)
3199
- throw new PoolOperationError({
3200
- operation: "pull",
3201
- rowId: id,
3202
- phase: "pull",
3203
- retryable: true,
3204
- kind: "attribution",
3205
- message: `quota for ${id} was issued for a credential the row no longer holds`
3206
- });
3207
- const merged = ctx.codec.merge(entry.quota, observation);
3208
- if (!ctx.codec.validate(merged))
3209
- throw refusal2("pull", id, "invalid-quota", "the quota codec rejected the merged map");
3244
+ if (!entry)
3245
+ throw unknownRow("pull", id);
3246
+ const merged = mergedQuota(ctx, id, entry.quota, observation);
3210
3247
  tx.setEntry(id, { ...entry, quota: merged, needsFirstReading: false });
3211
3248
  await tx.commitConfig();
3212
3249
  },
@@ -4616,7 +4653,8 @@ var init_pull = __esm({
4616
4653
  cause
4617
4654
  });
4618
4655
  }
4619
- await recordQuota(rt, id, {
4656
+ const publish = rt.publishQuota ?? ((rowId2, attribution, value) => recordQuota(rt, rowId2, attribution, value));
4657
+ await publish(id, {
4620
4658
  credentialEpoch: request.credentialEpoch,
4621
4659
  ...request.identity !== void 0 ? { identity: request.identity } : {}
4622
4660
  }, observation);
@@ -4646,1378 +4684,1655 @@ var init_pull = __esm({
4646
4684
  }
4647
4685
  });
4648
4686
 
4649
- // ../core/dist/common-auth-embedded/store/refresh.js
4650
- import { randomUUID as randomUUID9 } from "node:crypto";
4651
- function requireRefreshable(id, row) {
4652
- assertNotReserved("refresh", id, row?.staged);
4653
- if (!row)
4654
- throw refusal2("refresh", id, "unknown-row", `no row ${id} in the pool`);
4655
- if (row.invalid)
4656
- throw refusal2("refresh", id, "invalid-row", `row ${id} is invalid`);
4657
- if (row.type !== "oauth" || row.credential?.type !== "oauth")
4658
- throw refusal2("refresh", id, "no-credential", `row ${id} holds no OAuth credential`);
4659
- if (!row.enabled)
4660
- throw refusal2("refresh", id, "row-disabled", `row ${id} is disabled`);
4661
- return row;
4662
- }
4663
- function stampAhead(id) {
4664
- return refusal2("refresh", id, "refresh-stamp-ahead", `row ${id}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`, true);
4665
- }
4666
- async function refreshRow(rt, id, provider2, options = {}) {
4667
- assertNotInsideHook("refresh");
4668
- const { ctx } = rt;
4669
- return runOperation(ctx, "refresh", id, options.onFailure, async (locks, progress) => {
4670
- const { row: seen } = await readRow(rt, "refresh", id);
4671
- requireRefreshable(id, seen);
4672
- const early = await options.refuse?.(seen);
4673
- if (early !== void 0)
4674
- return { status: "refused", rowId: id, reason: early };
4675
- let key = rowLockKey(seen);
4676
- let captured;
4677
- for (let attempt = 0; ; attempt++) {
4678
- await locks.acquire(rowLockSpec(rt, { id, identity: key === id ? void 0 : key }));
4679
- await locks.acquire(options.providerLock ?? rt.providerLock);
4680
- for (const extra of options.extraLocks ?? [])
4681
- await locks.acquire(extra);
4682
- const captureProgress = { writes: 0 };
4683
- const read = await withTransaction(ctx, locks, captureProgress, { operation: "refresh", rowId: id }, async (tx) => {
4684
- let row = requireRefreshable(id, tx.row(id));
4685
- requireBound("refresh", row);
4686
- if (!row.hasEntry) {
4687
- tx.setEntry(id, { credentialEpoch: 1, needsFirstReading: true });
4688
- await tx.commitConfig();
4689
- row = requireRefreshable(id, tx.row(id));
4690
- }
4691
- if (rowLockKey(row) !== key)
4692
- return { keyNow: rowLockKey(row) };
4693
- const reason = await options.refuse?.(row);
4694
- if (reason !== void 0)
4695
- return { refused: reason };
4696
- return {
4697
- row,
4698
- credential: row.credential,
4699
- credentialEpoch: row.credentialEpoch,
4700
- identity: row.identity
4701
- };
4702
- });
4703
- if ("refused" in read)
4704
- return { status: "refused", rowId: id, reason: read.refused };
4705
- if ("keyNow" in read) {
4706
- await locks.releaseAll();
4707
- if (attempt >= 1)
4708
- throw refusal2("refresh", id, "row-key-changed", `row ${id}'s wire identity changed twice while its lock was held`, true);
4709
- key = read.keyNow;
4710
- continue;
4711
- }
4712
- captured = read;
4713
- break;
4714
- }
4715
- if (rotationStampUntrusted(captured.credential.lastRefreshedAt, ctx.now()))
4716
- throw stampAhead(id);
4717
- await ctx.hold?.("refresh-before-provider", id);
4718
- await locks.assertAll();
4719
- let result;
4720
- try {
4721
- result = await provider2(captured.credential, captured.row);
4722
- } catch (cause) {
4723
- throw new PoolOperationError({
4724
- operation: "refresh",
4725
- rowId: id,
4726
- phase: "before-first-write",
4727
- retryable: true,
4728
- kind: "provider",
4729
- message: "the provider refresh failed",
4730
- cause
4731
- });
4732
- }
4733
- if (typeof result?.refresh !== "string" || !result.refresh.trim())
4734
- throw refusal2("refresh", id, "provider", "the provider returned no refresh token", true);
4735
- const incoming = result.providerState === void 0 ? void 0 : acceptProviderState(ctx.providerState, "refresh", id, result.providerState, "the provider state the provider returned");
4736
- const commit = await withTransaction(ctx, locks, progress, { operation: "refresh", rowId: id }, async (tx) => {
4737
- const current = tx.row(id);
4738
- const entry = tx.entry(id);
4739
- if (!current || current.invalid || !entry || entry.credentialEpoch !== captured.credentialEpoch || current.identity !== captured.identity)
4740
- throw new PoolOperationError({
4741
- operation: "refresh",
4742
- rowId: id,
4743
- phase: "before-first-write",
4744
- retryable: true,
4745
- kind: "attribution",
4746
- message: `row ${id} changed credential while its refresh was in flight; the rotation is discarded`
4747
- });
4748
- requireBound("refresh", current);
4749
- const reason = await options.refuse?.(current);
4750
- if (reason !== void 0)
4751
- return { refused: reason };
4752
- const now = ctx.now();
4753
- const prior = current.credential?.type === "oauth" ? current.credential.lastRefreshedAt : void 0;
4754
- if (rotationStampUntrusted(prior, now))
4755
- throw stampAhead(id);
4756
- const credential = {
4757
- type: "oauth",
4758
- access: result.access,
4759
- refresh: result.refresh,
4760
- expires: result.expires
4761
- };
4762
- const contradiction = current.identity !== void 0 && result.identity !== void 0 && current.identity !== result.identity ? {
4763
- expectedIdentity: current.identity,
4764
- returnedIdentity: result.identity
4765
- } : void 0;
4766
- const transition = contradiction ? {
4767
- mark: randomUUID9(),
4768
- enabled: false,
4769
- reason: `${IDENTITY_CONTRADICTED_REASON_PREFIX}${JSON.stringify(contradiction)}`
4770
- } : void 0;
4771
- const learnt = current.identity === void 0 && result.identity ? result.identity : void 0;
4772
- const stored = await rotateIn(rt, tx, id, credential, {
4773
- stamp: rotationStamp(prior, now),
4774
- // Write state first with the disable marker, then config below.
4775
- // Once the successor is durable, recovery projects the disable even
4776
- // if config has not landed. A crash before the first rename still
4777
- // loses an in-memory provider reply, as in any ordinary refresh.
4778
- transition,
4779
- identity: learnt,
4780
- ...incoming !== void 0 ? {
4781
- providerState: mergedProviderState(ctx.providerState, "refresh", id, current.providerState, incoming)
4782
- } : {}
4783
- });
4784
- if (transition !== void 0) {
4785
- applyTransition(tx, id, transition);
4786
- await tx.commitConfig();
4787
- }
4788
- let identity = current.identity;
4789
- if (learnt !== void 0) {
4790
- recordIdentityIn(tx, id, learnt);
4791
- identity = learnt;
4792
- await tx.commitConfig();
4793
- }
4794
- return { stored, identity, contradiction, refused: void 0 };
4795
- });
4796
- if (commit.refused !== void 0)
4797
- return { status: "refused", rowId: id, reason: commit.refused };
4798
- if (commit.contradiction !== void 0)
4799
- return {
4800
- status: "identity-contradicted",
4801
- rowId: id,
4802
- ...commit.contradiction,
4803
- credential: commit.stored
4804
- };
4805
- if (options.onPersisted) {
4806
- try {
4807
- const persisted = options.onPersisted;
4808
- await runInsideHook("refresh", () => persisted(id, commit.stored));
4809
- } catch (cause) {
4810
- throw new PoolOperationError({
4811
- operation: "refresh",
4812
- rowId: id,
4813
- phase: "after-first-write",
4814
- retryable: false,
4815
- kind: "after-persist-hook",
4816
- committed: commit.stored,
4817
- message: "the after-persist hook threw; the rotation stays committed",
4818
- cause
4819
- });
4820
- }
4687
+ // ../core/dist/common-auth-embedded/logger/capture-sink.js
4688
+ function createCaptureSink() {
4689
+ const records = [];
4690
+ const sink = (record3) => {
4691
+ records.push(record3);
4692
+ };
4693
+ return {
4694
+ records,
4695
+ sink,
4696
+ clear: () => {
4697
+ records.length = 0;
4821
4698
  }
4822
- return {
4823
- status: "rotated",
4824
- rowId: id,
4825
- credential: commit.stored,
4826
- ...commit.identity !== void 0 ? { identity: commit.identity } : {}
4827
- };
4828
- });
4699
+ };
4829
4700
  }
4830
- var init_refresh = __esm({
4831
- "../core/dist/common-auth-embedded/store/refresh.js"() {
4701
+ var init_capture_sink = __esm({
4702
+ "../core/dist/common-auth-embedded/logger/capture-sink.js"() {
4832
4703
  "use strict";
4833
- init_errors();
4834
- init_hooks();
4835
- init_identity();
4836
- init_mutate();
4837
- init_provider_state();
4838
- init_reserved();
4839
- init_rows();
4840
- init_runtime();
4841
- init_schema();
4842
- init_torn();
4843
4704
  }
4844
4705
  });
4845
4706
 
4846
- // ../core/dist/common-auth-embedded/store/settings.js
4847
- import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
4848
- function settingsOf2(config) {
4849
- const settings = {};
4850
- for (const [key, value] of Object.entries(config))
4851
- if (!POOL_OWNED_KEYS.includes(key))
4852
- defineKey(settings, key, value);
4853
- return settings;
4854
- }
4855
- function defineKey(target, key, value) {
4856
- Object.defineProperty(target, key, {
4857
- value,
4858
- enumerable: true,
4859
- writable: true,
4860
- configurable: true
4861
- });
4707
+ // ../core/dist/common-auth-embedded/logger/redact.js
4708
+ function isError(value) {
4709
+ return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
4862
4710
  }
4863
- function composeConfig(config, next) {
4864
- const out = {};
4865
- for (const [key, value] of Object.entries(config)) {
4866
- if (POOL_OWNED_KEYS.includes(key))
4867
- defineKey(out, key, value);
4868
- else if (Object.hasOwn(next, key))
4869
- defineKey(out, key, next[key]);
4870
- }
4871
- for (const [key, value] of Object.entries(next))
4872
- if (!Object.hasOwn(config, key))
4873
- defineKey(out, key, value);
4874
- return out;
4875
- }
4876
- function settingsRefusal(message) {
4877
- return new PoolOperationError({
4878
- operation: "updateSettings",
4879
- phase: "before-first-write",
4880
- retryable: false,
4881
- kind: "invalid-input",
4882
- message
4883
- });
4884
- }
4885
- async function readPoolSettings(rt) {
4886
- const result = await readPool(rt.ctx);
4887
- if (result.status === "error")
4888
- return result;
4889
- return { status: result.status, settings: settingsOf2(result.config) };
4890
- }
4891
- async function updatePoolSettings(rt, mutator, options = {}) {
4892
- assertNotInsideHook("updateSettings");
4893
- const { ctx } = rt;
4894
- const onFailure = options.onFailure;
4895
- return runOperation(ctx, "updateSettings", void 0, onFailure && ((_rowId, error) => onFailure(error)), async (locks, progress) => {
4896
- for (const extra of options.extraLocks ?? [])
4897
- await locks.acquire(extra);
4898
- const mark = locks.held.length;
4711
+ function createRedactor(options = {}) {
4712
+ const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
4713
+ function isSecretKey(key) {
4714
+ const normalized = key.toLowerCase().replace(/[-_]/g, "");
4715
+ return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
4716
+ }
4717
+ function errorEntries(error) {
4718
+ const fields2 = error;
4719
+ const entries = [
4720
+ ["name", error.name],
4721
+ ["message", error.message],
4722
+ ["stack", error.stack]
4723
+ ];
4724
+ for (const key of ["code", "status", "cause"])
4725
+ if (fields2[key] !== void 0)
4726
+ entries.push([key, fields2[key]]);
4727
+ const listed = new Set(entries.map(([key]) => key));
4728
+ for (const entry of Object.entries(error))
4729
+ if (!listed.has(entry[0]))
4730
+ entries.push(entry);
4731
+ return entries;
4732
+ }
4733
+ function walk(value, keys, seen, errorDepth = 0) {
4734
+ if (typeof value === "string") {
4735
+ return patterns.reduce((text2, pattern) => text2.replace(pattern, MASK), value);
4736
+ }
4737
+ if (!value || typeof value !== "object")
4738
+ return value;
4739
+ if (seen.has(value))
4740
+ return "[Circular]";
4741
+ seen.add(value);
4899
4742
  try {
4900
- for (const spec of ctx.storeLocks)
4901
- await locks.acquire(spec);
4902
- const result = await readPool(ctx);
4903
- if (result.status !== "ready")
4904
- throw notReadyError(result, "updateSettings", void 0);
4905
- const current = settingsOf2(result.config);
4906
- const draft = structuredClone(current);
4907
- const returned = await runInsideHook("updateSettings", () => mutator(draft));
4908
- const next = returned === void 0 ? draft : returned;
4909
- if (!isRecord4(next))
4910
- throw settingsRefusal("the settings mutator must produce an object");
4911
- const owned = POOL_OWNED_KEYS.filter((key) => Object.hasOwn(next, key));
4912
- if (owned.length > 0)
4913
- throw settingsRefusal(`settings cannot set the pool-owned key(s) ${owned.join(", ")}`);
4914
- if (isDeepStrictEqual3(next, current))
4915
- return { settings: current, outcome: "unchanged" };
4916
- const config = composeConfig(result.config, next);
4917
- const info = { operation: "updateSettings", rowId: void 0 };
4918
- await writeJsonAtomic2(ctx.configPath, config, {
4919
- beforeRename: async () => {
4920
- await ctx.onStep?.("before-config-write", info);
4921
- await locks.assertAll();
4922
- }
4923
- });
4924
- progress.writes++;
4925
- await ctx.onStep?.("after-config-write", info);
4926
- return { settings: settingsOf2(config), outcome: "updated" };
4743
+ if (Array.isArray(value))
4744
+ return value.map((item) => walk(item, keys, seen, errorDepth));
4745
+ const error = isError(value);
4746
+ if (error && errorDepth >= MAX_ERROR_DEPTH)
4747
+ return "[Truncated]";
4748
+ const childDepth = error ? errorDepth + 1 : errorDepth;
4749
+ return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
4750
+ key,
4751
+ keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
4752
+ ]));
4927
4753
  } finally {
4928
- await locks.releaseTo(mark);
4754
+ seen.delete(value);
4929
4755
  }
4930
- });
4756
+ }
4757
+ return {
4758
+ redact: (value) => walk(value, true, /* @__PURE__ */ new WeakSet()),
4759
+ // Schema keys describe arguments, not credentials; only their string values are scrubbed.
4760
+ redactStrings: (value) => walk(value, false, /* @__PURE__ */ new WeakSet())
4761
+ };
4931
4762
  }
4932
- var POOL_OWNED_KEYS;
4933
- var init_settings = __esm({
4934
- "../core/dist/common-auth-embedded/store/settings.js"() {
4763
+ var SECRET_KEY_EXACT, TOKEN_VALUE, MASK, MAX_ERROR_DEPTH, defaultRedactor, redact, redactStrings;
4764
+ var init_redact = __esm({
4765
+ "../core/dist/common-auth-embedded/logger/redact.js"() {
4935
4766
  "use strict";
4936
- init_atomic_write();
4937
- init_errors();
4938
- init_hooks();
4939
- init_mutate();
4940
- init_schema();
4941
- POOL_OWNED_KEYS = Object.freeze([
4942
- "version",
4943
- "accounts",
4944
- POOL_KEY
4945
- ]);
4767
+ SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
4768
+ TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
4769
+ MASK = "***REDACTED***";
4770
+ MAX_ERROR_DEPTH = 8;
4771
+ defaultRedactor = createRedactor();
4772
+ redact = defaultRedactor.redact;
4773
+ redactStrings = defaultRedactor.redactStrings;
4946
4774
  }
4947
4775
  });
4948
4776
 
4949
- // ../core/dist/common-auth-embedded/store/pool.js
4950
- function memoryFor(configPath) {
4951
- let memory = processMemory.get(configPath);
4952
- if (!memory) {
4953
- memory = { removedIds: /* @__PURE__ */ new Set(), firedAtLoad: /* @__PURE__ */ new Set() };
4954
- processMemory.set(configPath, memory);
4777
+ // ../core/dist/common-auth-embedded/logger/engine.js
4778
+ import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
4779
+ import { open as open5 } from "node:fs/promises";
4780
+ import { dirname as dirname8, resolve as resolve3 } from "node:path";
4781
+ function chmodPrivate(path2) {
4782
+ try {
4783
+ chmodSync(path2, 384);
4784
+ } catch {
4955
4785
  }
4956
- return memory;
4957
- }
4958
- function toLoad(result) {
4959
- if (result.status === "ready")
4960
- return {
4961
- status: "ready",
4962
- schemaVersion: POOL_SCHEMA_VERSION,
4963
- rows: result.rows
4964
- };
4965
- if (result.status === "pending-migration")
4966
- return {
4967
- status: "pending-migration",
4968
- roster: Array.isArray(result.config.accounts) ? result.config.accounts : []
4969
- };
4970
- return result;
4971
4786
  }
4972
- function openPoolStore(options) {
4973
- const memory = memoryFor(options.configPath);
4974
- const lockDefaults = {
4975
- ...POOL_LOCK_DEFAULTS,
4976
- ...options.lockOptions
4977
- };
4978
- const ctx = {
4979
- provider: options.provider,
4980
- configPath: options.configPath,
4981
- statePath: options.statePath,
4982
- codec: options.quota,
4983
- ...options.providerState ? { providerState: options.providerState } : {},
4984
- now: options.now ?? Date.now,
4985
- storeLocks: options.storeLocks ?? [
4986
- { name: "save", path: options.configPath },
4987
- { name: "save", path: options.statePath }
4988
- ],
4989
- lockDefaults,
4990
- lockEnv: {
4991
- ...options.onLockEvent ? { onLockEvent: options.onLockEvent } : {},
4992
- ...options.onLockStep ? { onLockStep: options.onLockStep } : {},
4993
- ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
4994
- },
4995
- removedIds: memory.removedIds,
4996
- requireCredentialStamps: options.requireCredentialStamps === true,
4997
- requireRemovedFingerprint: options.requireRemovedFingerprint === true,
4998
- ...options.logger ? { logger: options.logger } : {},
4999
- ...options.onStep ? { onStep: options.onStep } : {},
5000
- ...options.hold ? { hold: options.hold } : {}
5001
- };
5002
- const pulls = new PullScheduler(() => rt, options.pull, options.onPullFailure, memory.firedAtLoad, options.logger);
5003
- const rt = {
5004
- ctx,
5005
- providerLock: options.providerLock ?? {
5006
- name: `provider-${encodeURIComponent(options.provider)}`,
5007
- path: options.statePath
5008
- },
5009
- rowLockOptions: options.rowLockOptions ?? {},
5010
- firePull: (id, reason) => pulls.fire(id, reason)
5011
- };
5012
- return {
5013
- async load() {
5014
- const result = await readPool(ctx);
5015
- if (result.status === "ready") {
5016
- for (const row of result.rows)
5017
- if ((row.candidate || row.torn && row.enabled) && row.type === "oauth" && row.needsFirstReading)
5018
- pulls.fire(row.id, "load");
4787
+ function rotateIfNeeded(f) {
4788
+ try {
4789
+ if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
4790
+ return;
4791
+ for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
4792
+ if (existsSync(`${f}.${i}`)) {
4793
+ const rotated2 = `${f}.${i + 1}`;
4794
+ renameSync(`${f}.${i}`, rotated2);
4795
+ chmodPrivate(rotated2);
5019
4796
  }
5020
- return toLoad(result);
5021
- },
5022
- async read() {
5023
- return toLoad(await readPool(ctx));
5024
- },
5025
- async initialize(input = {}) {
5026
- return { status: await initializePool(ctx, input.dropKeys ?? []) };
5027
- },
5028
- add: (input, callOptions) => addRow(rt, input, callOptions),
5029
- publishRoster: (plan, callOptions) => publishRoster(rt, plan, callOptions),
5030
- publication: (operationId) => publication(rt, operationId),
5031
- replace: (id, credential, input, callOptions) => replaceRow(rt, id, credential, input, callOptions),
5032
- rotate: (id, credential, input, callOptions) => rotateRow(rt, id, credential, input, callOptions),
5033
- updateProviderState: (id, fence, mutator, callOptions) => updateProviderStateRow(rt, id, fence, mutator, callOptions),
5034
- disable: (id, reason, callOptions) => disableRow(rt, id, reason, callOptions),
5035
- enable: (id, callOptions) => enableRow(rt, id, callOptions),
5036
- remove: (id, callOptions) => removeRow(rt, id, callOptions),
5037
- reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
5038
- readSettings: () => readPoolSettings(rt),
5039
- updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
5040
- recordIdentity: (id, identity, attribution, callOptions) => recordRowIdentity(rt, id, identity, attribution, callOptions),
5041
- refresh: (id, provider2, callOptions) => refreshRow(rt, id, provider2, callOptions),
5042
- recordQuota: (id, attribution, observation) => recordQuota(rt, id, attribution, observation),
5043
- requestReading: (id) => pulls.fire(id, "admission"),
5044
- pullsSettled: () => pulls.settled()
5045
- };
4797
+ }
4798
+ const rotated = `${f}.1`;
4799
+ renameSync(f, rotated);
4800
+ chmodPrivate(rotated);
4801
+ } catch {
4802
+ }
5046
4803
  }
5047
- var processMemory;
5048
- var init_pool = __esm({
5049
- "../core/dist/common-auth-embedded/store/pool.js"() {
5050
- "use strict";
5051
- init_attribution();
5052
- init_mutate();
5053
- init_provider_state();
5054
- init_publication();
5055
- init_pull();
5056
- init_refresh();
5057
- init_refresh_lock();
5058
- init_rows();
5059
- init_schema();
5060
- init_settings();
5061
- processMemory = /* @__PURE__ */ new Map();
5062
- }
5063
- });
5064
-
5065
- // ../core/dist/common-auth-embedded/store/index.js
5066
- var store_exports = {};
5067
- __export(store_exports, {
5068
- DECLINE_TRANSITION: () => DECLINE_TRANSITION,
5069
- DUPLICATE_IDENTITY_REASON: () => DUPLICATE_IDENTITY_REASON,
5070
- LEGACY_STORE_VERSION: () => LEGACY_STORE_VERSION,
5071
- POOL_KEY: () => POOL_KEY,
5072
- POOL_LOCK_DEFAULTS: () => POOL_LOCK_DEFAULTS,
5073
- POOL_OWNED_KEYS: () => POOL_OWNED_KEYS,
5074
- POOL_ROWS_KEY: () => POOL_ROWS_KEY,
5075
- POOL_SCHEMA_VERSION: () => POOL_SCHEMA_VERSION,
5076
- PROVIDER_STATE_KEY: () => PROVIDER_STATE_KEY,
5077
- PoolOperationError: () => PoolOperationError,
5078
- PoolReentryError: () => PoolReentryError,
5079
- REFRESH_STAMP_TOLERANCE_MS: () => REFRESH_STAMP_TOLERANCE_MS,
5080
- countUnknownIdentityRows: () => countUnknownIdentityRows,
5081
- fingerprintOf: () => fingerprintOf,
5082
- openPoolStore: () => openPoolStore,
5083
- rowLockKey: () => rowLockKey
5084
- });
5085
- var init_store = __esm({
5086
- "../core/dist/common-auth-embedded/store/index.js"() {
5087
- "use strict";
5088
- init_errors();
5089
- init_identity();
5090
- init_pool();
5091
- init_provider_state();
5092
- init_refresh_lock();
5093
- init_schema();
5094
- init_settings();
4804
+ async function closeWindowsFile(sink) {
4805
+ const { file, handle } = sink;
4806
+ sink.file = void 0;
4807
+ sink.handle = void 0;
4808
+ if (file && handle)
4809
+ await privateOperation(file, "log-close", () => handle.close());
4810
+ }
4811
+ async function openWindowsFile(sink, file) {
4812
+ await ensurePrivateDirectory(dirname8(file));
4813
+ try {
4814
+ await verifyPrivate(file, "file", true);
4815
+ } catch (error) {
4816
+ if (error.code !== "ENOENT")
4817
+ throw error;
4818
+ try {
4819
+ await createPrivateBytes(file, "");
4820
+ } catch (creationError) {
4821
+ if (creationError.code !== "EEXIST")
4822
+ throw creationError;
4823
+ await verifyPrivate(file, "file", true);
4824
+ }
5095
4825
  }
5096
- });
5097
-
5098
- // ../core/dist/common-auth-embedded/fs/lock-constants.js
5099
- var WRITER_LOCK_CONSTANTS;
5100
- var init_lock_constants = __esm({
5101
- "../core/dist/common-auth-embedded/fs/lock-constants.js"() {
5102
- "use strict";
5103
- WRITER_LOCK_CONSTANTS = Object.freeze({
5104
- sidebar: Object.freeze({
5105
- name: "sidebar-write",
5106
- ttlMs: 1e4,
5107
- timeoutMs: 15e3,
5108
- renew: true
5109
- }),
5110
- preferences: Object.freeze({
5111
- name: "preferences",
5112
- ttlMs: 1e4,
5113
- timeoutMs: 2e3,
5114
- renew: true
5115
- })
4826
+ sink.handle = await privateOperation(file, "log-open", () => open5(file, "a"));
4827
+ sink.file = file;
4828
+ return sink.handle;
4829
+ }
4830
+ async function flushWindowsFile(sink, file, text2) {
4831
+ file = resolve3(file);
4832
+ try {
4833
+ if (sink.file !== file)
4834
+ await closeWindowsFile(sink);
4835
+ let handle = sink.handle ?? await openWindowsFile(sink, file);
4836
+ const info = await privateOperation(file, "log-stat", () => handle.stat());
4837
+ if (info.size >= MAX_BYTES) {
4838
+ await closeWindowsFile(sink);
4839
+ for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
4840
+ const source = i === 0 ? file : `${file}.${i}`;
4841
+ const target = `${file}.${i + 1}`;
4842
+ try {
4843
+ await verifyPrivate(source, "file", true);
4844
+ } catch (error) {
4845
+ if (error.code === "ENOENT")
4846
+ continue;
4847
+ throw error;
4848
+ }
4849
+ try {
4850
+ await verifyPrivate(target, "file", true);
4851
+ } catch (error) {
4852
+ if (error.code !== "ENOENT")
4853
+ throw error;
4854
+ }
4855
+ await replaceWindowsFile(source, target);
4856
+ await verifyPrivate(target, "file");
4857
+ }
4858
+ handle = await openWindowsFile(sink, file);
4859
+ }
4860
+ await privateOperation(file, "log-append", () => handle.appendFile(text2, "utf8"));
4861
+ } catch (error) {
4862
+ await closeWindowsFile(sink).catch(() => {
5116
4863
  });
4864
+ throw error;
5117
4865
  }
5118
- });
5119
-
5120
- // ../core/dist/common-auth-embedded/fs/index.js
5121
- var fs_exports = {};
5122
- __export(fs_exports, {
5123
- LockContentionError: () => LockContentionError,
5124
- LockOwnershipError: () => LockOwnershipError,
5125
- PrivateFileError: () => PrivateFileError,
5126
- WRITER_LOCK_CONSTANTS: () => WRITER_LOCK_CONSTANTS,
5127
- acquireRefreshFileLock: () => acquireRefreshFileLock,
5128
- isLostMarkerRaceError: () => isLostMarkerRaceError,
5129
- lockPathFor: () => lockPathFor,
5130
- withLock: () => withLock,
5131
- writeJsonAtomic: () => writeJsonAtomic2
5132
- });
5133
- var init_fs = __esm({
5134
- "../core/dist/common-auth-embedded/fs/index.js"() {
5135
- "use strict";
5136
- init_atomic_write();
5137
- init_lock_constants();
5138
- init_private_files();
5139
- init_refresh_file_lock();
5140
- init_with_lock();
4866
+ }
4867
+ function safeSerialize(data) {
4868
+ try {
4869
+ return ` ${JSON.stringify(data)}`;
4870
+ } catch {
4871
+ return " [unserializable]";
5141
4872
  }
5142
- });
5143
-
5144
- // ../core/dist/common-auth-embedded/routing/admission.js
5145
- function exclusionFor(id, inputs, now) {
5146
- const markedUntil = inputs.rateLimitMarks?.get(id);
5147
- if (markedUntil !== void 0 && now < markedUntil) {
5148
- return { id, reason: "rate-limited", until: markedUntil };
4873
+ }
4874
+ function createEngine(options) {
4875
+ let logFileSource;
4876
+ let initLevelSource;
4877
+ let runtimeLevel;
4878
+ let redactor = createRedactor();
4879
+ let captureSink;
4880
+ let buffer = [];
4881
+ let timer;
4882
+ let orderedSink = Promise.resolve();
4883
+ let sinkError;
4884
+ const windowsFile = {};
4885
+ function queueWindows(operation) {
4886
+ const next = orderedSink.then(operation);
4887
+ orderedSink = next.catch((error) => {
4888
+ sinkError = error;
4889
+ });
4890
+ return next;
5149
4891
  }
5150
- const backoffUntil = inputs.refreshBackoff?.get(id);
5151
- if (backoffUntil !== void 0 && now < backoffUntil) {
5152
- return { id, reason: "refresh-backoff", until: backoffUntil };
4892
+ function configure(next) {
4893
+ if (windowsPrivateFiles && next.file !== logFileSource)
4894
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
4895
+ });
4896
+ logFileSource = next.file;
4897
+ initLevelSource = next.level;
4898
+ redactor = createRedactor(next);
4899
+ captureSink = next.captureSink;
5153
4900
  }
5154
- return void 0;
5155
- }
5156
- function judgeStageOne(id, projection, requiredLabels, now) {
5157
- if (projection.limits.length === 0) {
5158
- return {
5159
- id,
5160
- stage: 1,
5161
- gate: 2,
5162
- reason: "needs-first-reading",
5163
- pullRequested: true
5164
- };
4901
+ function setLogLevel3(l) {
4902
+ if (l === void 0 || l in ORDER)
4903
+ runtimeLevel = l;
5165
4904
  }
5166
- for (const label of requiredLabels) {
5167
- if (!projection.limits.some((limit) => limit.label === label)) {
5168
- return {
5169
- id,
5170
- stage: 1,
5171
- gate: 3,
5172
- reason: "unknown-window",
5173
- window: { scope: projection.scope, label },
5174
- pullRequested: true
5175
- };
5176
- }
4905
+ function logFilePath() {
4906
+ if (logFileSource === void 0)
4907
+ return void 0;
4908
+ const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
4909
+ return resolved || void 0;
5177
4910
  }
5178
- const exhausted = projection.limits.filter(readsExhausted);
5179
- for (const limit of exhausted) {
5180
- if (futureResetAt(limit, now) === void 0) {
5181
- return {
5182
- id,
5183
- stage: 1,
5184
- gate: 4,
5185
- reason: "unknown-reset",
5186
- window: { scope: limit.scope, label: limit.label },
5187
- pullRequested: true
5188
- };
5189
- }
4911
+ function configuredLevel() {
4912
+ if (runtimeLevel)
4913
+ return runtimeLevel;
4914
+ const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
4915
+ if (floor && floor in ORDER)
4916
+ return floor;
4917
+ return "info";
5190
4918
  }
5191
- for (const limit of exhausted) {
5192
- const resetAtMs = futureResetAt(limit, now);
5193
- if (resetAtMs !== void 0 && typeof limit.resetsAt === "string") {
5194
- return {
5195
- id,
5196
- stage: 1,
5197
- gate: 5,
5198
- reason: "exhausted",
5199
- window: { scope: limit.scope, label: limit.label },
5200
- resetsAt: limit.resetsAt,
5201
- resetAtMs
5202
- };
4919
+ function flushLogs3(close = true) {
4920
+ if (timer) {
4921
+ clearTimeout(timer);
4922
+ timer = void 0;
5203
4923
  }
5204
- }
5205
- return void 0;
5206
- }
5207
- function admit(input) {
5208
- const scope = input.scope ?? ALL_SCOPE;
5209
- const requiredLabels = input.requiredLabels ?? DEFAULT_REQUIRED_LABELS;
5210
- const excluded = [];
5211
- const refused = [];
5212
- const survivors = [];
5213
- for (const row of input.rows) {
5214
- const exclusion = exclusionFor(row.id, input, input.now);
5215
- if (exclusion) {
5216
- excluded.push(exclusion);
5217
- continue;
4924
+ if (!buffer.length) {
4925
+ if (windowsPrivateFiles)
4926
+ return queueWindows(async () => {
4927
+ if (close)
4928
+ await closeWindowsFile(windowsFile);
4929
+ if (sinkError)
4930
+ throw sinkError;
4931
+ });
4932
+ return;
5218
4933
  }
5219
- if (row.kind === "api-key") {
5220
- survivors.push({ id: row.id, kind: row.kind });
5221
- continue;
4934
+ let file;
4935
+ try {
4936
+ file = logFilePath();
4937
+ } catch {
4938
+ buffer = [];
4939
+ if (windowsPrivateFiles && close)
4940
+ return queueWindows(() => closeWindowsFile(windowsFile));
4941
+ return;
5222
4942
  }
5223
- const projection = projectQuota(row.quota, scope);
5224
- const refusal3 = judgeStageOne(row.id, projection, requiredLabels, input.now);
5225
- if (refusal3) {
5226
- refused.push(refusal3);
5227
- continue;
4943
+ const text2 = buffer.join("");
4944
+ buffer = [];
4945
+ if (!file) {
4946
+ if (windowsPrivateFiles && close)
4947
+ return queueWindows(() => closeWindowsFile(windowsFile));
4948
+ return;
4949
+ }
4950
+ if (windowsPrivateFiles) {
4951
+ return queueWindows(async () => {
4952
+ try {
4953
+ await flushWindowsFile(windowsFile, file, text2);
4954
+ } finally {
4955
+ if (close)
4956
+ await closeWindowsFile(windowsFile);
4957
+ }
4958
+ });
4959
+ }
4960
+ try {
4961
+ rotateIfNeeded(file);
4962
+ if (existsSync(file))
4963
+ chmodPrivate(file);
4964
+ appendFileSync(file, text2, { encoding: "utf8", mode: 384 });
4965
+ } catch {
5228
4966
  }
5229
- survivors.push({ id: row.id, kind: row.kind, projection });
5230
4967
  }
5231
- const spent = new Map(survivors.flatMap((row) => {
5232
- const reset = budgetExhaustedResetAt(row.projection, input.now);
5233
- return reset ? [[row.id, reset]] : [];
5234
- }));
5235
- const lastPath = spent.size > 0 && spent.size === survivors.length;
5236
- const admitted = [];
5237
- for (const row of survivors) {
5238
- const reset = spent.get(row.id);
5239
- if (reset === void 0) {
5240
- admitted.push(row);
5241
- } else if (lastPath) {
5242
- admitted.push({ ...row, lastPath: true });
5243
- } else {
5244
- refused.push({ id: row.id, stage: 2, reason: "budget-spent", ...reset });
4968
+ function schedule2() {
4969
+ if (!timer)
4970
+ timer = setTimeout(() => {
4971
+ timer = void 0;
4972
+ const flushed = flushLogs3(false);
4973
+ if (flushed instanceof Promise)
4974
+ void flushed.catch(() => {
4975
+ });
4976
+ }, 500);
4977
+ }
4978
+ function emit(channel, level, message, data) {
4979
+ if (logFileSource === void 0 && captureSink === void 0)
4980
+ return;
4981
+ try {
4982
+ if (ORDER[level] > ORDER[configuredLevel()])
4983
+ return;
4984
+ const scrubbedMessage = redactor.redactStrings(message);
4985
+ let scrubbedData;
4986
+ try {
4987
+ scrubbedData = redactor.redact(data);
4988
+ } catch {
4989
+ scrubbedData = "[unserializable]";
4990
+ }
4991
+ const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${level.toUpperCase()} [${channel}] ${scrubbedMessage}` + (data === void 0 ? "" : safeSerialize(scrubbedData)) + "\n";
4992
+ try {
4993
+ captureSink?.({
4994
+ channel,
4995
+ level,
4996
+ message: scrubbedMessage,
4997
+ data: scrubbedData
4998
+ });
4999
+ } catch {
5000
+ }
5001
+ if (logFileSource === void 0)
5002
+ return;
5003
+ buffer.push(line);
5004
+ if (buffer.length >= 50) {
5005
+ const flushed = flushLogs3(false);
5006
+ if (flushed instanceof Promise)
5007
+ void flushed.catch(() => {
5008
+ });
5009
+ } else
5010
+ schedule2();
5011
+ } catch {
5245
5012
  }
5246
5013
  }
5247
- const order = new Map(input.rows.map((row, index) => [row.id, index]));
5248
- const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
5249
- refused.sort(byInput);
5250
- const pulls = refused.filter((refusal3) => "pullRequested" in refusal3).map((refusal3) => refusal3.id);
5251
- for (const id of pulls)
5252
- input.requestPull?.(id);
5253
- return { admitted, refused, excluded, pulls };
5254
- }
5255
- var init_admission = __esm({
5256
- "../core/dist/common-auth-embedded/routing/admission.js"() {
5257
- "use strict";
5258
- init_map();
5259
- init_projection();
5014
+ function createLogger5(channel) {
5015
+ return {
5016
+ error: (m, d) => emit(channel, "error", m, d),
5017
+ warn: (m, d) => emit(channel, "warn", m, d),
5018
+ info: (m, d) => emit(channel, "info", m, d),
5019
+ debug: (m, d) => emit(channel, "debug", m, d),
5020
+ trace: (m, d) => emit(channel, "trace", m, d)
5021
+ };
5260
5022
  }
5261
- });
5262
-
5263
- // ../core/dist/common-auth-embedded/routing/ordered.js
5264
- function resolveRoutingMode(value) {
5265
- switch (value) {
5266
- case "sticky-balanced":
5267
- return { mode: "sticky-balanced", placement: "roster" };
5268
- case "main-first":
5269
- return { mode: "ordered", placement: "main-first" };
5270
- case "fallback-first":
5271
- return { mode: "ordered", placement: "fallback-first" };
5272
- default:
5273
- return { mode: "ordered", placement: "roster" };
5023
+ function reset() {
5024
+ if (windowsPrivateFiles)
5025
+ void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
5026
+ });
5027
+ sinkError = void 0;
5028
+ buffer = [];
5029
+ if (timer) {
5030
+ clearTimeout(timer);
5031
+ timer = void 0;
5032
+ }
5033
+ logFileSource = void 0;
5034
+ initLevelSource = void 0;
5035
+ runtimeLevel = void 0;
5036
+ redactor = createRedactor();
5037
+ captureSink = void 0;
5274
5038
  }
5039
+ if (options)
5040
+ configure(options);
5041
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3, reset };
5275
5042
  }
5276
- function orderForPlacement(ids, placement, formerMainId = DEFAULT_FORMER_MAIN_ID) {
5277
- if (placement === "roster" || !ids.includes(formerMainId))
5278
- return [...ids];
5279
- const rest = ids.filter((id) => id !== formerMainId);
5280
- return placement === "main-first" ? [formerMainId, ...rest] : [...rest, formerMainId];
5043
+ function createLoggerInstance(options) {
5044
+ const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine(options);
5045
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
5281
5046
  }
5282
- function routeOrdered(input) {
5283
- const admission = admit(input);
5284
- const admitted = new Set(admission.admitted.map((row) => row.id));
5285
- const order = orderForPlacement(input.rows.map((row) => row.id), input.placement ?? "roster", input.formerMainId).filter((id) => admitted.has(id) && input.killswitch?.get(id) !== false);
5286
- return { order, admission };
5047
+ function initLogger(options) {
5048
+ defaultEngine.configure(options);
5049
+ const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = defaultEngine;
5050
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
5287
5051
  }
5288
- function nextOrderedAttempt(order, attempts2, retryStatuses) {
5289
- const last = attempts2.at(-1);
5290
- if (last !== void 0) {
5291
- if (last.status === void 0 || !retryStatuses.includes(last.status)) {
5292
- return void 0;
5293
- }
5294
- }
5295
- const tried = new Set(attempts2.map((attempt) => attempt.id));
5296
- return order.find((id) => !tried.has(id));
5052
+ function setLogLevel(l) {
5053
+ defaultEngine.setLogLevel(l);
5297
5054
  }
5298
- var DEFAULT_FORMER_MAIN_ID;
5299
- var init_ordered = __esm({
5300
- "../core/dist/common-auth-embedded/routing/ordered.js"() {
5055
+ function flushLogs() {
5056
+ return defaultEngine.flushLogs();
5057
+ }
5058
+ function createLogger2(channel) {
5059
+ return defaultEngine.createLogger(channel);
5060
+ }
5061
+ async function flushForTest() {
5062
+ return defaultEngine.flushLogs();
5063
+ }
5064
+ function resetLoggerForTest() {
5065
+ defaultEngine.reset();
5066
+ }
5067
+ var ORDER, MAX_BYTES, ROTATE_KEEP, defaultEngine;
5068
+ var init_engine = __esm({
5069
+ "../core/dist/common-auth-embedded/logger/engine.js"() {
5301
5070
  "use strict";
5302
- init_admission();
5303
- DEFAULT_FORMER_MAIN_ID = "main";
5071
+ init_private_files();
5072
+ init_redact();
5073
+ ORDER = {
5074
+ error: 0,
5075
+ warn: 1,
5076
+ info: 2,
5077
+ debug: 3,
5078
+ trace: 4
5079
+ };
5080
+ MAX_BYTES = 5 * 1024 * 1024;
5081
+ ROTATE_KEEP = 3;
5082
+ defaultEngine = createEngine();
5304
5083
  }
5305
5084
  });
5306
5085
 
5307
- // ../core/dist/common-auth-embedded/routing/pins.js
5308
- function isPinValid(pin, validIds, currentIdentity) {
5309
- if (!validIds.has(pin.accountId))
5310
- return false;
5311
- return !(typeof pin.wireIdentity === "string" && typeof currentIdentity === "string" && pin.wireIdentity !== currentIdentity);
5312
- }
5313
- function pendingBytesForPins(pins, quotaCheckedAtById, excludedSessionKey) {
5314
- const pending = /* @__PURE__ */ new Map();
5315
- for (const [sessionKey, pin] of pins) {
5316
- if (sessionKey === excludedSessionKey)
5317
- continue;
5318
- if (pin.quotaCheckedAt !== quotaCheckedAtById.get(pin.accountId))
5319
- continue;
5320
- pending.set(pin.accountId, (pending.get(pin.accountId) ?? 0) + (pin.inputBytes ?? 0));
5321
- }
5322
- return pending;
5323
- }
5324
- var init_pins = __esm({
5325
- "../core/dist/common-auth-embedded/routing/pins.js"() {
5086
+ // ../core/dist/common-auth-embedded/logger/index.js
5087
+ var logger_exports = {};
5088
+ __export(logger_exports, {
5089
+ createCaptureSink: () => createCaptureSink,
5090
+ createLogger: () => createLogger2,
5091
+ createLoggerInstance: () => createLoggerInstance,
5092
+ createRedactor: () => createRedactor,
5093
+ flushForTest: () => flushForTest,
5094
+ flushLogs: () => flushLogs,
5095
+ initLogger: () => initLogger,
5096
+ redact: () => redact,
5097
+ redactStrings: () => redactStrings,
5098
+ resetLoggerForTest: () => resetLoggerForTest,
5099
+ setLogLevel: () => setLogLevel
5100
+ });
5101
+ var init_logger = __esm({
5102
+ "../core/dist/common-auth-embedded/logger/index.js"() {
5326
5103
  "use strict";
5104
+ init_capture_sink();
5105
+ init_engine();
5106
+ init_redact();
5327
5107
  }
5328
5108
  });
5329
5109
 
5330
- // ../core/dist/common-auth-embedded/routing/sticky.js
5331
- function snapshotCheckedAt(quota, entryCheckedAt) {
5332
- for (const checkedAt of [quota?.checkedAt, entryCheckedAt]) {
5333
- if (typeof checkedAt === "number" && Number.isFinite(checkedAt)) {
5334
- return checkedAt;
5335
- }
5110
+ // ../core/dist/common-auth-embedded/store/quota-writer.js
5111
+ var COALESCE_MS, POOL_QUOTA_QUEUE_LIMIT, PoolQuotaWriter;
5112
+ var init_quota_writer = __esm({
5113
+ "../core/dist/common-auth-embedded/store/quota-writer.js"() {
5114
+ "use strict";
5115
+ init_logger();
5116
+ init_attribution();
5117
+ init_errors();
5118
+ init_mutate();
5119
+ init_refresh_lock();
5120
+ init_runtime();
5121
+ init_schema();
5122
+ COALESCE_MS = 100;
5123
+ POOL_QUOTA_QUEUE_LIMIT = 128;
5124
+ PoolQuotaWriter = class {
5125
+ rt;
5126
+ timeoutMs;
5127
+ pending = /* @__PURE__ */ new Map();
5128
+ warned = /* @__PURE__ */ new Set();
5129
+ wake = /* @__PURE__ */ new Set();
5130
+ logger;
5131
+ timer;
5132
+ running;
5133
+ closing;
5134
+ closed = false;
5135
+ stopped = false;
5136
+ failures = 0;
5137
+ constructor(rt, timeoutMs = 1e3) {
5138
+ this.rt = rt;
5139
+ this.timeoutMs = timeoutMs;
5140
+ this.logger = rt.ctx.logger ?? createLogger2("store");
5141
+ }
5142
+ async record(id, attribution, observation) {
5143
+ try {
5144
+ this.assertOpen(id);
5145
+ assertQuotaEpoch(id, attribution);
5146
+ const publication2 = structuredClone({
5147
+ id,
5148
+ attribution,
5149
+ observation
5150
+ });
5151
+ const { row, result } = await readRow(this.rt, "pull", id);
5152
+ assertQuotaRow(id, publication2.attribution, row);
5153
+ mergedQuota(this.rt.ctx, id, this.overlayRow({ ...row, quota: entryIn(result.config, id)?.quota }).quota, publication2.observation);
5154
+ await this.room(id);
5155
+ this.assertOpen(id);
5156
+ const queue = this.pending.get(id) ?? [];
5157
+ queue.push(publication2);
5158
+ this.pending.set(id, queue);
5159
+ if (queue.length >= POOL_QUOTA_QUEUE_LIMIT)
5160
+ this.flushNow();
5161
+ else
5162
+ this.schedule(COALESCE_MS);
5163
+ } catch (error) {
5164
+ throw toFailure(error, "pull", id, { writes: 0 });
5165
+ }
5166
+ }
5167
+ queued(id) {
5168
+ return this.pending.get(id)?.length ?? 0;
5169
+ }
5170
+ // Waits while the row's queue is full, flushing at once on every wake-up,
5171
+ // for at most the store's own lock acquisition budget.
5172
+ async room(id) {
5173
+ if (this.queued(id) < POOL_QUOTA_QUEUE_LIMIT)
5174
+ return;
5175
+ const { ctx } = this.rt;
5176
+ const budget = Math.max(0, ...ctx.storeLocks.map((spec) => spec.timeoutMs ?? ctx.lockDefaults.timeoutMs));
5177
+ const deadline = performance.now() + budget;
5178
+ while (this.queued(id) >= POOL_QUOTA_QUEUE_LIMIT) {
5179
+ this.assertOpen(id);
5180
+ this.flushNow();
5181
+ const left = deadline - performance.now();
5182
+ if (left <= 0)
5183
+ 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);
5184
+ await new Promise((resolve15) => {
5185
+ const done = () => {
5186
+ clearTimeout(timer);
5187
+ this.wake.delete(done);
5188
+ resolve15();
5189
+ };
5190
+ const timer = setTimeout(done, left);
5191
+ this.wake.add(done);
5192
+ });
5193
+ }
5194
+ }
5195
+ assertOpen(id) {
5196
+ if (this.closed)
5197
+ throw refusal2("pull", id, "invalid-input", "pool quota writer is closed");
5198
+ }
5199
+ // What read() and load() show: the stored map, then each queued reading of
5200
+ // the row still bound to it, in arrival order through the codec's merge.
5201
+ // A reading the codec now refuses is left out, as the flush drops it.
5202
+ overlayRow(row) {
5203
+ let next = row;
5204
+ for (const publication2 of this.pending.get(row.id) ?? []) {
5205
+ try {
5206
+ assertQuotaRow(row.id, publication2.attribution, row);
5207
+ next = {
5208
+ ...next,
5209
+ quota: mergedQuota(this.rt.ctx, row.id, next.quota, publication2.observation),
5210
+ needsFirstReading: false
5211
+ };
5212
+ } catch {
5213
+ }
5214
+ }
5215
+ return next;
5216
+ }
5217
+ overlay(rows) {
5218
+ return rows.map((row) => this.overlayRow(row));
5219
+ }
5220
+ schedule(delay3) {
5221
+ if (this.running || this.timer || !this.pending.size || this.stopped)
5222
+ return;
5223
+ this.timer = setTimeout(() => {
5224
+ this.timer = void 0;
5225
+ this.flush();
5226
+ }, delay3);
5227
+ if (!this.closed)
5228
+ this.timer.unref?.();
5229
+ }
5230
+ // Starts a flush now rather than at the coalescing timer or retry backoff;
5231
+ // a flush already running is left to finish.
5232
+ flushNow() {
5233
+ if (this.running)
5234
+ return;
5235
+ clearTimeout(this.timer);
5236
+ this.timer = void 0;
5237
+ this.flush();
5238
+ }
5239
+ flush() {
5240
+ if (this.running || this.stopped || !this.pending.size)
5241
+ return;
5242
+ const batch = [...this.pending.values()].flat();
5243
+ const ctx = {
5244
+ ...this.rt.ctx,
5245
+ storeLocks: this.rt.ctx.storeLocks.map((spec) => ({
5246
+ ...spec,
5247
+ timeoutMs: Math.min(spec.timeoutMs ?? this.rt.ctx.lockDefaults.timeoutMs, 100)
5248
+ }))
5249
+ };
5250
+ const locks = new LockStack(ctx.lockDefaults, ctx.lockEnv);
5251
+ this.running = (async () => {
5252
+ try {
5253
+ await withTransaction(ctx, locks, { writes: 0 }, { operation: "pull", rowId: void 0 }, async (tx) => {
5254
+ if (this.stopped)
5255
+ return;
5256
+ let changed = false;
5257
+ for (const publication2 of batch) {
5258
+ const { id, attribution, observation } = publication2;
5259
+ const witness = JSON.stringify([
5260
+ id,
5261
+ attribution.credentialEpoch,
5262
+ attribution.identity
5263
+ ]);
5264
+ try {
5265
+ tx.assertNotStaged(id);
5266
+ assertQuotaRow(id, attribution, tx.row(id));
5267
+ } catch (error) {
5268
+ if (!(error instanceof PoolOperationError))
5269
+ throw error;
5270
+ if (!this.warned.has(witness)) {
5271
+ this.warned.add(witness);
5272
+ this.warn("pool quota publication dropped; account binding changed", { id, kind: error.kind });
5273
+ }
5274
+ continue;
5275
+ }
5276
+ const entry = tx.entry(id);
5277
+ if (!entry)
5278
+ continue;
5279
+ let quota;
5280
+ try {
5281
+ quota = mergedQuota(ctx, id, entry.quota, observation);
5282
+ } catch (error) {
5283
+ const key = `codec:${witness}`;
5284
+ if (!this.warned.has(key)) {
5285
+ this.warned.add(key);
5286
+ this.warn("pool quota publication dropped; the quota codec refused it", {
5287
+ id,
5288
+ error: error instanceof Error ? error.message : String(error)
5289
+ });
5290
+ }
5291
+ continue;
5292
+ }
5293
+ tx.setEntry(id, { ...entry, quota, needsFirstReading: false });
5294
+ changed = true;
5295
+ }
5296
+ if (changed && !this.stopped)
5297
+ await tx.commitConfig();
5298
+ }, { completeTorn: false });
5299
+ const flushed = new Set(batch);
5300
+ for (const [id, queue] of this.pending) {
5301
+ const rest = queue.filter((publication2) => !flushed.has(publication2));
5302
+ if (rest.length)
5303
+ this.pending.set(id, rest);
5304
+ else
5305
+ this.pending.delete(id);
5306
+ }
5307
+ this.failures = 0;
5308
+ } catch (error) {
5309
+ if (!this.stopped && this.failures++ === 0)
5310
+ this.warn("pool quota publication delayed; retrying", {
5311
+ error: error instanceof Error ? error.message : String(error)
5312
+ });
5313
+ } finally {
5314
+ await locks.releaseAll();
5315
+ this.running = void 0;
5316
+ for (const wake of this.wake)
5317
+ wake();
5318
+ const delay3 = this.failures ? Math.min(5e3, 100 * 2 ** Math.min(this.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS;
5319
+ this.schedule(delay3);
5320
+ }
5321
+ })();
5322
+ }
5323
+ warn(message, data) {
5324
+ try {
5325
+ this.logger.warn(message, data);
5326
+ } catch {
5327
+ }
5328
+ }
5329
+ close() {
5330
+ if (this.closing)
5331
+ return this.closing;
5332
+ this.closed = true;
5333
+ this.closing = this.drain();
5334
+ return this.closing;
5335
+ }
5336
+ async drain() {
5337
+ clearTimeout(this.timer);
5338
+ this.timer = void 0;
5339
+ let deadline;
5340
+ let wake;
5341
+ const drained = new Promise((done) => {
5342
+ wake = () => {
5343
+ if (!this.pending.size)
5344
+ done();
5345
+ };
5346
+ this.wake.add(wake);
5347
+ wake();
5348
+ });
5349
+ try {
5350
+ this.flush();
5351
+ await Promise.race([
5352
+ drained,
5353
+ new Promise((done) => {
5354
+ deadline = setTimeout(done, Math.max(0, this.timeoutMs));
5355
+ })
5356
+ ]);
5357
+ } finally {
5358
+ this.stopped = true;
5359
+ clearTimeout(deadline);
5360
+ clearTimeout(this.timer);
5361
+ this.wake.delete(wake);
5362
+ if (this.pending.size)
5363
+ this.warn("pool quota drain timed out; pending readings left", {
5364
+ accounts: this.pending.size,
5365
+ readings: [...this.pending.values()].reduce((sum, queue) => sum + queue.length, 0)
5366
+ });
5367
+ this.pending.clear();
5368
+ for (const wake2 of this.wake)
5369
+ wake2();
5370
+ }
5371
+ }
5372
+ };
5336
5373
  }
5337
- return void 0;
5374
+ });
5375
+
5376
+ // ../core/dist/common-auth-embedded/store/refresh.js
5377
+ import { randomUUID as randomUUID9 } from "node:crypto";
5378
+ function requireRefreshable(id, row) {
5379
+ assertNotReserved("refresh", id, row?.staged);
5380
+ if (!row)
5381
+ throw refusal2("refresh", id, "unknown-row", `no row ${id} in the pool`);
5382
+ if (row.invalid)
5383
+ throw refusal2("refresh", id, "invalid-row", `row ${id} is invalid`);
5384
+ if (row.type !== "oauth" || row.credential?.type !== "oauth")
5385
+ throw refusal2("refresh", id, "no-credential", `row ${id} holds no OAuth credential`);
5386
+ if (!row.enabled)
5387
+ throw refusal2("refresh", id, "row-disabled", `row ${id} is disabled`);
5388
+ return row;
5338
5389
  }
5339
- function defaultStickyStatusClass(status) {
5340
- if (status === 401 || status === 403)
5341
- return "permanent";
5342
- if (status === void 0 || status === 0 || !Number.isFinite(status) || status >= 500 && status <= 599 || status === 429) {
5343
- return "transient";
5344
- }
5345
- return "healthy";
5390
+ function stampAhead(id) {
5391
+ return refusal2("refresh", id, "refresh-stamp-ahead", `row ${id}'s stored refresh stamp is ahead of the clock; a rotation now could not be stamped newer within the trust bound`, true);
5346
5392
  }
5347
- function windowReadings(quota) {
5348
- return quota.limits.filter((limit) => limit.kind === "reading").sort((left, right) => {
5349
- const leftKnown = left.windowMinutes !== void 0;
5350
- const rightKnown = right.windowMinutes !== void 0;
5351
- if (leftKnown !== rightKnown)
5352
- return leftKnown ? -1 : 1;
5353
- if (leftKnown && rightKnown) {
5354
- return (right.windowMinutes ?? 0) - (left.windowMinutes ?? 0);
5393
+ async function refreshRow(rt, id, provider2, options = {}) {
5394
+ assertNotInsideHook("refresh");
5395
+ const { ctx } = rt;
5396
+ return runOperation(ctx, "refresh", id, options.onFailure, async (locks, progress) => {
5397
+ const { row: seen } = await readRow(rt, "refresh", id);
5398
+ requireRefreshable(id, seen);
5399
+ const early = await options.refuse?.(seen);
5400
+ if (early !== void 0)
5401
+ return { status: "refused", rowId: id, reason: early };
5402
+ let key = rowLockKey(seen);
5403
+ let captured;
5404
+ for (let attempt = 0; ; attempt++) {
5405
+ await locks.acquire(rowLockSpec(rt, { id, identity: key === id ? void 0 : key }));
5406
+ await locks.acquire(options.providerLock ?? rt.providerLock);
5407
+ for (const extra of options.extraLocks ?? [])
5408
+ await locks.acquire(extra);
5409
+ const captureProgress = { writes: 0 };
5410
+ const read = await withTransaction(ctx, locks, captureProgress, { operation: "refresh", rowId: id }, async (tx) => {
5411
+ let row = requireRefreshable(id, tx.row(id));
5412
+ requireBound("refresh", row);
5413
+ if (!row.hasEntry) {
5414
+ tx.setEntry(id, { credentialEpoch: 1, needsFirstReading: true });
5415
+ await tx.commitConfig();
5416
+ row = requireRefreshable(id, tx.row(id));
5417
+ }
5418
+ if (rowLockKey(row) !== key)
5419
+ return { keyNow: rowLockKey(row) };
5420
+ const reason = await options.refuse?.(row);
5421
+ if (reason !== void 0)
5422
+ return { refused: reason };
5423
+ return {
5424
+ row,
5425
+ credential: row.credential,
5426
+ credentialEpoch: row.credentialEpoch,
5427
+ identity: row.identity
5428
+ };
5429
+ });
5430
+ if ("refused" in read)
5431
+ return { status: "refused", rowId: id, reason: read.refused };
5432
+ if ("keyNow" in read) {
5433
+ await locks.releaseAll();
5434
+ if (attempt >= 1)
5435
+ throw refusal2("refresh", id, "row-key-changed", `row ${id}'s wire identity changed twice while its lock was held`, true);
5436
+ key = read.keyNow;
5437
+ continue;
5438
+ }
5439
+ captured = read;
5440
+ break;
5355
5441
  }
5356
- return 0;
5357
- });
5358
- }
5359
- function decideStickyBreak(input) {
5360
- const statusClass = (input.classifyStatus ?? defaultStickyStatusClass)(input.status);
5361
- if (statusClass === "permanent") {
5362
- return { action: "migrate", reason: "permanent" };
5363
- }
5364
- if (!input.quota)
5365
- return { action: "retain", reason: "unknown" };
5366
- const checkedAt = snapshotCheckedAt(input.quota, input.quotaCheckedAt);
5367
- if (checkedAt === void 0 || !Number.isFinite(checkedAt) || input.now - checkedAt > QUOTA_STALENESS_MS) {
5368
- return { action: "retain", reason: "stale" };
5369
- }
5370
- if (input.killswitchPasses === false) {
5371
- return { action: "migrate", reason: "killswitch" };
5372
- }
5373
- for (const limit of windowReadings(input.quota)) {
5374
- const remaining = limit.remainingPercent;
5375
- if (typeof remaining === "number" && Number.isFinite(remaining) && remaining <= 0) {
5442
+ if (rotationStampUntrusted(captured.credential.lastRefreshedAt, ctx.now()))
5443
+ throw stampAhead(id);
5444
+ await ctx.hold?.("refresh-before-provider", id);
5445
+ await locks.assertAll();
5446
+ let result;
5447
+ try {
5448
+ result = await provider2(captured.credential, captured.row);
5449
+ } catch (cause) {
5450
+ throw new PoolOperationError({
5451
+ operation: "refresh",
5452
+ rowId: id,
5453
+ phase: "before-first-write",
5454
+ retryable: true,
5455
+ kind: "provider",
5456
+ message: "the provider refresh failed",
5457
+ cause
5458
+ });
5459
+ }
5460
+ if (typeof result?.refresh !== "string" || !result.refresh.trim())
5461
+ throw refusal2("refresh", id, "provider", "the provider returned no refresh token", true);
5462
+ const incoming = result.providerState === void 0 ? void 0 : acceptProviderState(ctx.providerState, "refresh", id, result.providerState, "the provider state the provider returned");
5463
+ const commit = await withTransaction(ctx, locks, progress, { operation: "refresh", rowId: id }, async (tx) => {
5464
+ const current = tx.row(id);
5465
+ const entry = tx.entry(id);
5466
+ if (!current || current.invalid || !entry || entry.credentialEpoch !== captured.credentialEpoch || current.identity !== captured.identity)
5467
+ throw new PoolOperationError({
5468
+ operation: "refresh",
5469
+ rowId: id,
5470
+ phase: "before-first-write",
5471
+ retryable: true,
5472
+ kind: "attribution",
5473
+ message: `row ${id} changed credential while its refresh was in flight; the rotation is discarded`
5474
+ });
5475
+ requireBound("refresh", current);
5476
+ const reason = await options.refuse?.(current);
5477
+ if (reason !== void 0)
5478
+ return { refused: reason };
5479
+ const now = ctx.now();
5480
+ const prior = current.credential?.type === "oauth" ? current.credential.lastRefreshedAt : void 0;
5481
+ if (rotationStampUntrusted(prior, now))
5482
+ throw stampAhead(id);
5483
+ const credential = {
5484
+ type: "oauth",
5485
+ access: result.access,
5486
+ refresh: result.refresh,
5487
+ expires: result.expires
5488
+ };
5489
+ const contradiction = current.identity !== void 0 && result.identity !== void 0 && current.identity !== result.identity ? {
5490
+ expectedIdentity: current.identity,
5491
+ returnedIdentity: result.identity
5492
+ } : void 0;
5493
+ const transition = contradiction ? {
5494
+ mark: randomUUID9(),
5495
+ enabled: false,
5496
+ reason: `${IDENTITY_CONTRADICTED_REASON_PREFIX}${JSON.stringify(contradiction)}`
5497
+ } : void 0;
5498
+ const learnt = current.identity === void 0 && result.identity ? result.identity : void 0;
5499
+ const stored = await rotateIn(rt, tx, id, credential, {
5500
+ stamp: rotationStamp(prior, now),
5501
+ // Write state first with the disable marker, then config below.
5502
+ // Once the successor is durable, recovery projects the disable even
5503
+ // if config has not landed. A crash before the first rename still
5504
+ // loses an in-memory provider reply, as in any ordinary refresh.
5505
+ transition,
5506
+ identity: learnt,
5507
+ ...incoming !== void 0 ? {
5508
+ providerState: mergedProviderState(ctx.providerState, "refresh", id, current.providerState, incoming)
5509
+ } : {}
5510
+ });
5511
+ if (transition !== void 0) {
5512
+ applyTransition(tx, id, transition);
5513
+ await tx.commitConfig();
5514
+ }
5515
+ let identity = current.identity;
5516
+ if (learnt !== void 0) {
5517
+ recordIdentityIn(tx, id, learnt);
5518
+ identity = learnt;
5519
+ await tx.commitConfig();
5520
+ }
5521
+ return { stored, identity, contradiction, refused: void 0 };
5522
+ });
5523
+ if (commit.refused !== void 0)
5524
+ return { status: "refused", rowId: id, reason: commit.refused };
5525
+ if (commit.contradiction !== void 0)
5376
5526
  return {
5377
- action: "migrate",
5378
- reason: "exhausted",
5379
- window: { scope: limit.scope, label: limit.label },
5380
- ...typeof limit.resetsAt === "string" ? { resetsAt: limit.resetsAt } : {}
5527
+ status: "identity-contradicted",
5528
+ rowId: id,
5529
+ ...commit.contradiction,
5530
+ credential: commit.stored
5381
5531
  };
5532
+ if (options.onPersisted) {
5533
+ try {
5534
+ const persisted = options.onPersisted;
5535
+ await runInsideHook("refresh", () => persisted(id, commit.stored));
5536
+ } catch (cause) {
5537
+ throw new PoolOperationError({
5538
+ operation: "refresh",
5539
+ rowId: id,
5540
+ phase: "after-first-write",
5541
+ retryable: false,
5542
+ kind: "after-persist-hook",
5543
+ committed: commit.stored,
5544
+ message: "the after-persist hook threw; the rotation stays committed",
5545
+ cause
5546
+ });
5547
+ }
5382
5548
  }
5383
- }
5384
- const budgetReset = budgetExhaustedResetAt(input.quota, input.now);
5385
- if (budgetReset) {
5386
5549
  return {
5387
- action: "migrate",
5388
- reason: "exhausted",
5389
- resetsAt: budgetReset.resetsAt
5550
+ status: "rotated",
5551
+ rowId: id,
5552
+ credential: commit.stored,
5553
+ ...commit.identity !== void 0 ? { identity: commit.identity } : {}
5390
5554
  };
5391
- }
5392
- return { action: "retain", reason: statusClass };
5555
+ });
5393
5556
  }
5394
- function sustainableWindowWeight(window, reservePercent, now) {
5395
- const spendable = Math.max(0, window.remainingPercent - reservePercent);
5396
- if (spendable <= 0)
5397
- return 0;
5398
- if (!window.resetsAt)
5399
- return spendable;
5400
- const resetMs = Date.parse(window.resetsAt);
5401
- if (!Number.isFinite(resetMs) || resetMs <= now)
5402
- return spendable;
5403
- const hours = Math.max((resetMs - now) / 36e5, MIN_RESET_HOURS);
5404
- return spendable / hours;
5557
+ var init_refresh = __esm({
5558
+ "../core/dist/common-auth-embedded/store/refresh.js"() {
5559
+ "use strict";
5560
+ init_errors();
5561
+ init_hooks();
5562
+ init_identity();
5563
+ init_mutate();
5564
+ init_provider_state();
5565
+ init_reserved();
5566
+ init_rows();
5567
+ init_runtime();
5568
+ init_schema();
5569
+ init_torn();
5570
+ }
5571
+ });
5572
+
5573
+ // ../core/dist/common-auth-embedded/store/settings.js
5574
+ import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
5575
+ function settingsOf2(config) {
5576
+ const settings = {};
5577
+ for (const [key, value] of Object.entries(config))
5578
+ if (!POOL_OWNED_KEYS.includes(key))
5579
+ defineKey(settings, key, value);
5580
+ return settings;
5405
5581
  }
5406
- function compareAccountIds(left, right) {
5407
- if (left < right)
5408
- return -1;
5409
- if (left > right)
5410
- return 1;
5411
- return 0;
5582
+ function defineKey(target, key, value) {
5583
+ Object.defineProperty(target, key, {
5584
+ value,
5585
+ enumerable: true,
5586
+ writable: true,
5587
+ configurable: true
5588
+ });
5412
5589
  }
5413
- function candidateWeight(candidate, now) {
5414
- if (!candidate.quota)
5415
- return void 0;
5416
- const quotaCheckedAt = snapshotCheckedAt(candidate.quota, candidate.quotaCheckedAt);
5417
- if (quotaCheckedAt === void 0 || now - quotaCheckedAt > QUOTA_STALENESS_MS) {
5418
- return void 0;
5419
- }
5420
- const weights = windowReadings(candidate.quota).map((limit) => sustainableWindowWeight({
5421
- remainingPercent: limit.remainingPercent ?? Number.NaN,
5422
- ...limit.resetsAt === void 0 ? {} : { resetsAt: limit.resetsAt }
5423
- }, candidate.reservePercent[limit.label] ?? 0, now));
5424
- const budget = candidate.quota.budget;
5425
- if (budget && typeof budget.remainingPercent === "number" && Number.isFinite(budget.remainingPercent)) {
5426
- weights.push(sustainableWindowWeight({
5427
- remainingPercent: budget.remainingPercent,
5428
- ...budget.resetsAt === void 0 ? {} : { resetsAt: budget.resetsAt }
5429
- }, 0, now));
5590
+ function composeConfig(config, next) {
5591
+ const out = {};
5592
+ for (const [key, value] of Object.entries(config)) {
5593
+ if (POOL_OWNED_KEYS.includes(key))
5594
+ defineKey(out, key, value);
5595
+ else if (Object.hasOwn(next, key))
5596
+ defineKey(out, key, next[key]);
5430
5597
  }
5431
- const weight = weights.length > 0 ? Math.min(...weights) : 0;
5432
- return weight > 0 ? { candidate, quotaCheckedAt, weight } : void 0;
5598
+ for (const [key, value] of Object.entries(next))
5599
+ if (!Object.hasOwn(config, key))
5600
+ defineKey(out, key, value);
5601
+ return out;
5433
5602
  }
5434
- function selectStickyCandidate(input) {
5435
- const eligibleCandidates = input.candidates.filter((candidate) => candidate.killswitchPasses !== false);
5436
- if (input.candidates.length === 0) {
5437
- throw new Error("Cannot select a sticky candidate: input.candidates is empty");
5438
- }
5439
- if (eligibleCandidates.length === 0)
5440
- return void 0;
5441
- const weighted = eligibleCandidates.map((candidate) => candidateWeight(candidate, input.now)).filter((candidate) => candidate !== void 0);
5442
- if (weighted.length > 0) {
5443
- weighted.sort((left, right) => {
5444
- const leftScore = ((input.pendingBytes.get(left.candidate.accountId) ?? 0) + input.requestBytes) / Math.max(left.weight, MIN_WEIGHT);
5445
- const rightScore = ((input.pendingBytes.get(right.candidate.accountId) ?? 0) + input.requestBytes) / Math.max(right.weight, MIN_WEIGHT);
5446
- return leftScore - rightScore || left.candidate.configuredOrder - right.candidate.configuredOrder || compareAccountIds(left.candidate.accountId, right.candidate.accountId);
5447
- });
5448
- const selected = weighted[0];
5449
- if (selected) {
5450
- return {
5451
- accountId: selected.candidate.accountId,
5452
- quotaCheckedAt: selected.quotaCheckedAt,
5453
- source: "weighted"
5454
- };
5455
- }
5456
- }
5457
- input.onEmptyWeightedSet?.();
5458
- const fallback = [...eligibleCandidates].sort((left, right) => {
5459
- const leftHasCredits = (left.resetCreditsApplicable ?? 0) > 0 ? 1 : 0;
5460
- const rightHasCredits = (right.resetCreditsApplicable ?? 0) > 0 ? 1 : 0;
5461
- return rightHasCredits - leftHasCredits || left.configuredOrder - right.configuredOrder || compareAccountIds(left.accountId, right.accountId);
5462
- })[0];
5463
- if (!fallback) {
5464
- throw new Error("Cannot select a sticky candidate: input.candidates is empty");
5465
- }
5466
- return {
5467
- accountId: fallback.accountId,
5468
- quotaCheckedAt: snapshotCheckedAt(fallback.quota, fallback.quotaCheckedAt),
5469
- source: "mode-fallback"
5470
- };
5603
+ function settingsRefusal(message) {
5604
+ return new PoolOperationError({
5605
+ operation: "updateSettings",
5606
+ phase: "before-first-write",
5607
+ retryable: false,
5608
+ kind: "invalid-input",
5609
+ message
5610
+ });
5471
5611
  }
5472
- function routeSticky(input) {
5473
- const admission = admit(input);
5474
- const admitted = new Map(admission.admitted.map((row) => [row.id, row]));
5475
- const refusals = new Map(admission.refused.map((r) => [r.id, r]));
5476
- const excluded = new Set(admission.excluded.map((row) => row.id));
5477
- const validIds = new Set(input.rows.map((row) => row.id));
5478
- const pinValid = input.pin !== void 0 && isPinValid(input.pin, validIds, input.identities?.get(input.pin.accountId));
5479
- if (pinValid && input.pin) {
5480
- const pinned = admitted.get(input.pin.accountId);
5481
- if (pinned && input.killswitch?.get(pinned.id) !== false) {
5482
- return {
5483
- outcome: "dispatch",
5484
- accountId: pinned.id,
5485
- source: "pin",
5486
- ...pinned.projection?.checkedAt === void 0 ? {} : { quotaCheckedAt: pinned.projection.checkedAt },
5487
- pin: { action: "retain" },
5488
- refusedSelections: [],
5489
- admission
5490
- };
5612
+ async function readPoolSettings(rt) {
5613
+ const result = await readPool(rt.ctx);
5614
+ if (result.status === "error")
5615
+ return result;
5616
+ return { status: result.status, settings: settingsOf2(result.config) };
5617
+ }
5618
+ async function updatePoolSettings(rt, mutator, options = {}) {
5619
+ assertNotInsideHook("updateSettings");
5620
+ const { ctx } = rt;
5621
+ const onFailure = options.onFailure;
5622
+ return runOperation(ctx, "updateSettings", void 0, onFailure && ((_rowId, error) => onFailure(error)), async (locks, progress) => {
5623
+ for (const extra of options.extraLocks ?? [])
5624
+ await locks.acquire(extra);
5625
+ const mark = locks.held.length;
5626
+ try {
5627
+ for (const spec of ctx.storeLocks)
5628
+ await locks.acquire(spec);
5629
+ const result = await readPool(ctx);
5630
+ if (result.status !== "ready")
5631
+ throw notReadyError(result, "updateSettings", void 0);
5632
+ const current = settingsOf2(result.config);
5633
+ const draft = structuredClone(current);
5634
+ const returned = await runInsideHook("updateSettings", () => mutator(draft));
5635
+ const next = returned === void 0 ? draft : returned;
5636
+ if (!isRecord4(next))
5637
+ throw settingsRefusal("the settings mutator must produce an object");
5638
+ const owned = POOL_OWNED_KEYS.filter((key) => Object.hasOwn(next, key));
5639
+ if (owned.length > 0)
5640
+ throw settingsRefusal(`settings cannot set the pool-owned key(s) ${owned.join(", ")}`);
5641
+ if (isDeepStrictEqual3(next, current))
5642
+ return { settings: current, outcome: "unchanged" };
5643
+ const config = composeConfig(result.config, next);
5644
+ const info = { operation: "updateSettings", rowId: void 0 };
5645
+ await writeJsonAtomic2(ctx.configPath, config, {
5646
+ beforeRename: async () => {
5647
+ await ctx.onStep?.("before-config-write", info);
5648
+ await locks.assertAll();
5649
+ }
5650
+ });
5651
+ progress.writes++;
5652
+ await ctx.onStep?.("after-config-write", info);
5653
+ return { settings: settingsOf2(config), outcome: "updated" };
5654
+ } finally {
5655
+ await locks.releaseTo(mark);
5491
5656
  }
5657
+ });
5658
+ }
5659
+ var POOL_OWNED_KEYS;
5660
+ var init_settings = __esm({
5661
+ "../core/dist/common-auth-embedded/store/settings.js"() {
5662
+ "use strict";
5663
+ init_atomic_write();
5664
+ init_errors();
5665
+ init_hooks();
5666
+ init_mutate();
5667
+ init_schema();
5668
+ POOL_OWNED_KEYS = Object.freeze([
5669
+ "version",
5670
+ "accounts",
5671
+ POOL_KEY
5672
+ ]);
5673
+ }
5674
+ });
5675
+
5676
+ // ../core/dist/common-auth-embedded/store/pool.js
5677
+ function memoryFor(configPath) {
5678
+ let memory = processMemory.get(configPath);
5679
+ if (!memory) {
5680
+ memory = { removedIds: /* @__PURE__ */ new Set(), firedAtLoad: /* @__PURE__ */ new Set() };
5681
+ processMemory.set(configPath, memory);
5492
5682
  }
5493
- const pinRefusal = input.pin ? refusals.get(input.pin.accountId) : void 0;
5494
- const pinMoves = pinValid && input.pin !== void 0 && input.refusedPinPolicy === "move-on-confirmed-exhaustion" && (input.killswitch?.get(input.pin.accountId) === false || pinRefusal?.reason === "exhausted" || pinRefusal?.reason === "budget-spent");
5495
- const reserveFor = (row) => {
5496
- const perRow = typeof input.rowReservePercent === "function" ? input.rowReservePercent(row) : input.rowReservePercent?.get(row.id);
5497
- return perRow ?? input.reservePercent ?? {};
5498
- };
5499
- const scope = input.scope;
5500
- let candidates = input.rows.map((row, configuredOrder) => ({ row, configuredOrder })).filter(({ row }) => !excluded.has(row.id)).map(({ row, configuredOrder }) => {
5501
- const killswitchPasses = input.killswitch?.get(row.id);
5502
- const credits = input.resetCreditsApplicable?.get(row.id);
5683
+ return memory;
5684
+ }
5685
+ function toLoad(result) {
5686
+ if (result.status === "ready")
5503
5687
  return {
5504
- accountId: row.id,
5505
- quota: row.kind === "api-key" ? void 0 : admitted.get(row.id)?.projection ?? projectQuota(row.quota, scope),
5506
- reservePercent: reserveFor(row),
5507
- configuredOrder,
5508
- ...credits === void 0 ? {} : { resetCreditsApplicable: credits },
5509
- ...killswitchPasses === void 0 ? {} : { killswitchPasses }
5688
+ status: "ready",
5689
+ schemaVersion: POOL_SCHEMA_VERSION,
5690
+ rows: result.rows
5510
5691
  };
5511
- });
5512
- const refusedSelections = [];
5513
- const unplaced = pinValid ? { action: "retain" } : input.pin ? { action: "clear" } : { action: "none" };
5514
- while (candidates.length > 0) {
5515
- const selection = selectStickyCandidate({
5516
- candidates,
5517
- pendingBytes: input.pendingBytes ?? /* @__PURE__ */ new Map(),
5518
- requestBytes: input.requestBytes,
5519
- now: input.now,
5520
- ...input.onEmptyWeightedSet ? { onEmptyWeightedSet: input.onEmptyWeightedSet } : {}
5521
- });
5522
- if (!selection)
5523
- break;
5524
- const refusal3 = refusals.get(selection.accountId);
5525
- if (refusal3) {
5526
- refusedSelections.push(refusal3);
5527
- candidates = candidates.filter((candidate) => candidate.accountId !== selection.accountId);
5528
- continue;
5529
- }
5530
- const identity = input.identities?.get(selection.accountId);
5692
+ if (result.status === "pending-migration")
5531
5693
  return {
5532
- outcome: "dispatch",
5533
- accountId: selection.accountId,
5534
- source: selection.source,
5535
- ...selection.quotaCheckedAt === void 0 ? {} : { quotaCheckedAt: selection.quotaCheckedAt },
5536
- pin: pinValid && !pinMoves ? { action: "retain" } : {
5537
- action: "assign",
5538
- pin: {
5539
- accountId: selection.accountId,
5540
- inputBytes: input.requestBytes,
5541
- ...identity === void 0 ? {} : { wireIdentity: identity },
5542
- ...selection.quotaCheckedAt === void 0 ? {} : { quotaCheckedAt: selection.quotaCheckedAt }
5543
- }
5544
- },
5545
- refusedSelections,
5546
- admission
5694
+ status: "pending-migration",
5695
+ roster: Array.isArray(result.config.accounts) ? result.config.accounts : []
5547
5696
  };
5548
- }
5697
+ return result;
5698
+ }
5699
+ function openPoolStore(options) {
5700
+ const memory = memoryFor(options.configPath);
5701
+ const lockDefaults = {
5702
+ ...POOL_LOCK_DEFAULTS,
5703
+ ...options.lockOptions
5704
+ };
5705
+ const ctx = {
5706
+ provider: options.provider,
5707
+ configPath: options.configPath,
5708
+ statePath: options.statePath,
5709
+ codec: options.quota,
5710
+ ...options.providerState ? { providerState: options.providerState } : {},
5711
+ now: options.now ?? Date.now,
5712
+ storeLocks: options.storeLocks ?? [
5713
+ { name: "save", path: options.configPath },
5714
+ { name: "save", path: options.statePath }
5715
+ ],
5716
+ lockDefaults,
5717
+ lockEnv: {
5718
+ ...options.onLockEvent ? { onLockEvent: options.onLockEvent } : {},
5719
+ ...options.onLockStep ? { onLockStep: options.onLockStep } : {},
5720
+ ...options.onRenewalTimer ? { onRenewalTimer: options.onRenewalTimer } : {}
5721
+ },
5722
+ removedIds: memory.removedIds,
5723
+ requireCredentialStamps: options.requireCredentialStamps === true,
5724
+ requireRemovedFingerprint: options.requireRemovedFingerprint === true,
5725
+ ...options.logger ? { logger: options.logger } : {},
5726
+ ...options.onStep ? { onStep: options.onStep } : {},
5727
+ ...options.hold ? { hold: options.hold } : {}
5728
+ };
5729
+ const pulls = new PullScheduler(() => rt, options.pull, options.onPullFailure, memory.firedAtLoad, options.logger);
5730
+ const rt = {
5731
+ ctx,
5732
+ providerLock: options.providerLock ?? {
5733
+ name: `provider-${encodeURIComponent(options.provider)}`,
5734
+ path: options.statePath
5735
+ },
5736
+ rowLockOptions: options.rowLockOptions ?? {},
5737
+ firePull: (id, reason) => pulls.fire(id, reason)
5738
+ };
5739
+ const quotaWriter = options.coalesceQuota ? new PoolQuotaWriter(rt, options.quotaDrainTimeoutMs) : void 0;
5740
+ const record3 = (id, attribution, observation) => quotaWriter ? quotaWriter.record(id, attribution, observation) : recordQuota(rt, id, attribution, observation);
5741
+ rt.publishQuota = record3;
5742
+ const overlay = (result) => {
5743
+ if (result.status === "ready" && quotaWriter)
5744
+ return { ...result, rows: quotaWriter.overlay(result.rows) };
5745
+ return result;
5746
+ };
5549
5747
  return {
5550
- outcome: "no-admissible-account",
5551
- pin: unplaced,
5552
- refusedSelections,
5553
- admission
5748
+ async load() {
5749
+ const result = overlay(await readPool(ctx));
5750
+ if (result.status === "ready") {
5751
+ for (const row of result.rows)
5752
+ if ((row.candidate || row.torn && row.enabled) && row.type === "oauth" && row.needsFirstReading)
5753
+ pulls.fire(row.id, "load");
5754
+ }
5755
+ return toLoad(result);
5756
+ },
5757
+ async read() {
5758
+ return toLoad(overlay(await readPool(ctx)));
5759
+ },
5760
+ async initialize(input = {}) {
5761
+ return { status: await initializePool(ctx, input.dropKeys ?? []) };
5762
+ },
5763
+ add: (input, callOptions) => addRow(rt, input, callOptions),
5764
+ publishRoster: (plan, callOptions) => publishRoster(rt, plan, callOptions),
5765
+ publication: (operationId) => publication(rt, operationId),
5766
+ replace: (id, credential, input, callOptions) => replaceRow(rt, id, credential, input, callOptions),
5767
+ rotate: (id, credential, input, callOptions) => rotateRow(rt, id, credential, input, callOptions),
5768
+ updateProviderState: (id, fence, mutator, callOptions) => updateProviderStateRow(rt, id, fence, mutator, callOptions),
5769
+ disable: (id, reason, callOptions) => disableRow(rt, id, reason, callOptions),
5770
+ enable: (id, callOptions) => enableRow(rt, id, callOptions),
5771
+ remove: (id, callOptions) => removeRow(rt, id, callOptions),
5772
+ reorder: (ids, callOptions) => reorderRows(rt, ids, callOptions),
5773
+ readSettings: () => readPoolSettings(rt),
5774
+ updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
5775
+ recordIdentity: (id, identity, attribution, callOptions) => recordRowIdentity(rt, id, identity, attribution, callOptions),
5776
+ refresh: (id, provider2, callOptions) => refreshRow(rt, id, provider2, callOptions),
5777
+ recordQuota: record3,
5778
+ close: () => quotaWriter?.close() ?? Promise.resolve(),
5779
+ dispose: () => quotaWriter?.close() ?? Promise.resolve(),
5780
+ requestReading: (id) => pulls.fire(id, "admission"),
5781
+ pullsSettled: () => pulls.settled()
5554
5782
  };
5555
5783
  }
5556
- var QUOTA_STALENESS_MS, MIN_RESET_HOURS, MIN_WEIGHT;
5557
- var init_sticky = __esm({
5558
- "../core/dist/common-auth-embedded/routing/sticky.js"() {
5784
+ var processMemory;
5785
+ var init_pool = __esm({
5786
+ "../core/dist/common-auth-embedded/store/pool.js"() {
5559
5787
  "use strict";
5560
- init_projection();
5561
- init_admission();
5562
- init_pins();
5563
- QUOTA_STALENESS_MS = 15 * 6e4;
5564
- MIN_RESET_HOURS = 1 / 60;
5565
- MIN_WEIGHT = 1e-6;
5788
+ init_attribution();
5789
+ init_mutate();
5790
+ init_provider_state();
5791
+ init_publication();
5792
+ init_pull();
5793
+ init_quota_writer();
5794
+ init_refresh();
5795
+ init_refresh_lock();
5796
+ init_rows();
5797
+ init_schema();
5798
+ init_settings();
5799
+ processMemory = /* @__PURE__ */ new Map();
5566
5800
  }
5567
5801
  });
5568
5802
 
5569
- // ../core/dist/common-auth-embedded/routing/index.js
5570
- var routing_exports = {};
5571
- __export(routing_exports, {
5572
- DEFAULT_FORMER_MAIN_ID: () => DEFAULT_FORMER_MAIN_ID,
5573
- MIN_RESET_HOURS: () => MIN_RESET_HOURS,
5574
- MIN_WEIGHT: () => MIN_WEIGHT,
5575
- QUOTA_STALENESS_MS: () => QUOTA_STALENESS_MS,
5576
- admit: () => admit,
5577
- decideStickyBreak: () => decideStickyBreak,
5578
- defaultStickyStatusClass: () => defaultStickyStatusClass,
5579
- exclusionFor: () => exclusionFor,
5580
- isPinValid: () => isPinValid,
5581
- nextOrderedAttempt: () => nextOrderedAttempt,
5582
- orderForPlacement: () => orderForPlacement,
5583
- pendingBytesForPins: () => pendingBytesForPins,
5584
- resolveRoutingMode: () => resolveRoutingMode,
5585
- routeOrdered: () => routeOrdered,
5586
- routeSticky: () => routeSticky,
5587
- selectStickyCandidate: () => selectStickyCandidate,
5588
- snapshotCheckedAt: () => snapshotCheckedAt,
5589
- sustainableWindowWeight: () => sustainableWindowWeight
5803
+ // ../core/dist/common-auth-embedded/store/index.js
5804
+ var store_exports = {};
5805
+ __export(store_exports, {
5806
+ DECLINE_TRANSITION: () => DECLINE_TRANSITION,
5807
+ DUPLICATE_IDENTITY_REASON: () => DUPLICATE_IDENTITY_REASON,
5808
+ LEGACY_STORE_VERSION: () => LEGACY_STORE_VERSION,
5809
+ POOL_KEY: () => POOL_KEY,
5810
+ POOL_LOCK_DEFAULTS: () => POOL_LOCK_DEFAULTS,
5811
+ POOL_OWNED_KEYS: () => POOL_OWNED_KEYS,
5812
+ POOL_ROWS_KEY: () => POOL_ROWS_KEY,
5813
+ POOL_SCHEMA_VERSION: () => POOL_SCHEMA_VERSION,
5814
+ PROVIDER_STATE_KEY: () => PROVIDER_STATE_KEY,
5815
+ PoolOperationError: () => PoolOperationError,
5816
+ PoolReentryError: () => PoolReentryError,
5817
+ REFRESH_STAMP_TOLERANCE_MS: () => REFRESH_STAMP_TOLERANCE_MS,
5818
+ countUnknownIdentityRows: () => countUnknownIdentityRows,
5819
+ fingerprintOf: () => fingerprintOf,
5820
+ openPoolStore: () => openPoolStore,
5821
+ rowLockKey: () => rowLockKey
5822
+ });
5823
+ var init_store = __esm({
5824
+ "../core/dist/common-auth-embedded/store/index.js"() {
5825
+ "use strict";
5826
+ init_errors();
5827
+ init_identity();
5828
+ init_pool();
5829
+ init_provider_state();
5830
+ init_refresh_lock();
5831
+ init_schema();
5832
+ init_settings();
5833
+ }
5834
+ });
5835
+
5836
+ // ../core/dist/common-auth-embedded/fs/lock-constants.js
5837
+ var WRITER_LOCK_CONSTANTS;
5838
+ var init_lock_constants = __esm({
5839
+ "../core/dist/common-auth-embedded/fs/lock-constants.js"() {
5840
+ "use strict";
5841
+ WRITER_LOCK_CONSTANTS = Object.freeze({
5842
+ sidebar: Object.freeze({
5843
+ name: "sidebar-write",
5844
+ ttlMs: 1e4,
5845
+ timeoutMs: 15e3,
5846
+ renew: true
5847
+ }),
5848
+ preferences: Object.freeze({
5849
+ name: "preferences",
5850
+ ttlMs: 1e4,
5851
+ timeoutMs: 2e3,
5852
+ renew: true
5853
+ })
5854
+ });
5855
+ }
5856
+ });
5857
+
5858
+ // ../core/dist/common-auth-embedded/fs/index.js
5859
+ var fs_exports = {};
5860
+ __export(fs_exports, {
5861
+ LockContentionError: () => LockContentionError,
5862
+ LockOwnershipError: () => LockOwnershipError,
5863
+ PrivateFileError: () => PrivateFileError,
5864
+ WRITER_LOCK_CONSTANTS: () => WRITER_LOCK_CONSTANTS,
5865
+ acquireRefreshFileLock: () => acquireRefreshFileLock,
5866
+ isLostMarkerRaceError: () => isLostMarkerRaceError,
5867
+ lockPathFor: () => lockPathFor,
5868
+ withLock: () => withLock,
5869
+ writeJsonAtomic: () => writeJsonAtomic2
5590
5870
  });
5591
- var init_routing = __esm({
5592
- "../core/dist/common-auth-embedded/routing/index.js"() {
5871
+ var init_fs = __esm({
5872
+ "../core/dist/common-auth-embedded/fs/index.js"() {
5593
5873
  "use strict";
5594
- init_admission();
5595
- init_ordered();
5596
- init_pins();
5597
- init_sticky();
5874
+ init_atomic_write();
5875
+ init_lock_constants();
5876
+ init_private_files();
5877
+ init_refresh_file_lock();
5878
+ init_with_lock();
5598
5879
  }
5599
5880
  });
5600
5881
 
5601
- // ../core/dist/common-auth-embedded/logger/capture-sink.js
5602
- function createCaptureSink() {
5603
- const records = [];
5604
- const sink = (record3) => {
5605
- records.push(record3);
5606
- };
5607
- return {
5608
- records,
5609
- sink,
5610
- clear: () => {
5611
- records.length = 0;
5612
- }
5613
- };
5614
- }
5615
- var init_capture_sink = __esm({
5616
- "../core/dist/common-auth-embedded/logger/capture-sink.js"() {
5617
- "use strict";
5882
+ // ../core/dist/common-auth-embedded/routing/admission.js
5883
+ function exclusionFor(id, inputs, now) {
5884
+ const markedUntil = inputs.rateLimitMarks?.get(id);
5885
+ if (markedUntil !== void 0 && now < markedUntil) {
5886
+ return { id, reason: "rate-limited", until: markedUntil };
5618
5887
  }
5619
- });
5620
-
5621
- // ../core/dist/common-auth-embedded/logger/redact.js
5622
- function isError(value) {
5623
- return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
5888
+ const backoffUntil = inputs.refreshBackoff?.get(id);
5889
+ if (backoffUntil !== void 0 && now < backoffUntil) {
5890
+ return { id, reason: "refresh-backoff", until: backoffUntil };
5891
+ }
5892
+ return void 0;
5624
5893
  }
5625
- function createRedactor(options = {}) {
5626
- const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
5627
- function isSecretKey(key) {
5628
- const normalized = key.toLowerCase().replace(/[-_]/g, "");
5629
- return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
5894
+ function judgeStageOne(id, projection, requiredLabels, now) {
5895
+ if (projection.limits.length === 0) {
5896
+ return {
5897
+ id,
5898
+ stage: 1,
5899
+ gate: 2,
5900
+ reason: "needs-first-reading",
5901
+ pullRequested: true
5902
+ };
5630
5903
  }
5631
- function errorEntries(error) {
5632
- const fields2 = error;
5633
- const entries = [
5634
- ["name", error.name],
5635
- ["message", error.message],
5636
- ["stack", error.stack]
5637
- ];
5638
- for (const key of ["code", "status", "cause"])
5639
- if (fields2[key] !== void 0)
5640
- entries.push([key, fields2[key]]);
5641
- const listed = new Set(entries.map(([key]) => key));
5642
- for (const entry of Object.entries(error))
5643
- if (!listed.has(entry[0]))
5644
- entries.push(entry);
5645
- return entries;
5904
+ for (const label of requiredLabels) {
5905
+ if (!projection.limits.some((limit) => limit.label === label)) {
5906
+ return {
5907
+ id,
5908
+ stage: 1,
5909
+ gate: 3,
5910
+ reason: "unknown-window",
5911
+ window: { scope: projection.scope, label },
5912
+ pullRequested: true
5913
+ };
5914
+ }
5646
5915
  }
5647
- function walk(value, keys, seen, errorDepth = 0) {
5648
- if (typeof value === "string") {
5649
- return patterns.reduce((text2, pattern) => text2.replace(pattern, MASK), value);
5916
+ const exhausted = projection.limits.filter(readsExhausted);
5917
+ for (const limit of exhausted) {
5918
+ if (futureResetAt(limit, now) === void 0) {
5919
+ return {
5920
+ id,
5921
+ stage: 1,
5922
+ gate: 4,
5923
+ reason: "unknown-reset",
5924
+ window: { scope: limit.scope, label: limit.label },
5925
+ pullRequested: true
5926
+ };
5650
5927
  }
5651
- if (!value || typeof value !== "object")
5652
- return value;
5653
- if (seen.has(value))
5654
- return "[Circular]";
5655
- seen.add(value);
5656
- try {
5657
- if (Array.isArray(value))
5658
- return value.map((item) => walk(item, keys, seen, errorDepth));
5659
- const error = isError(value);
5660
- if (error && errorDepth >= MAX_ERROR_DEPTH)
5661
- return "[Truncated]";
5662
- const childDepth = error ? errorDepth + 1 : errorDepth;
5663
- return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
5664
- key,
5665
- keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
5666
- ]));
5667
- } finally {
5668
- seen.delete(value);
5928
+ }
5929
+ for (const limit of exhausted) {
5930
+ const resetAtMs = futureResetAt(limit, now);
5931
+ if (resetAtMs !== void 0 && typeof limit.resetsAt === "string") {
5932
+ return {
5933
+ id,
5934
+ stage: 1,
5935
+ gate: 5,
5936
+ reason: "exhausted",
5937
+ window: { scope: limit.scope, label: limit.label },
5938
+ resetsAt: limit.resetsAt,
5939
+ resetAtMs
5940
+ };
5669
5941
  }
5670
5942
  }
5671
- return {
5672
- redact: (value) => walk(value, true, /* @__PURE__ */ new WeakSet()),
5673
- // Schema keys describe arguments, not credentials; only their string values are scrubbed.
5674
- redactStrings: (value) => walk(value, false, /* @__PURE__ */ new WeakSet())
5675
- };
5943
+ return void 0;
5676
5944
  }
5677
- var SECRET_KEY_EXACT, TOKEN_VALUE, MASK, MAX_ERROR_DEPTH, defaultRedactor, redact, redactStrings;
5678
- var init_redact = __esm({
5679
- "../core/dist/common-auth-embedded/logger/redact.js"() {
5680
- "use strict";
5681
- SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
5682
- TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
5683
- MASK = "***REDACTED***";
5684
- MAX_ERROR_DEPTH = 8;
5685
- defaultRedactor = createRedactor();
5686
- redact = defaultRedactor.redact;
5687
- redactStrings = defaultRedactor.redactStrings;
5688
- }
5689
- });
5690
-
5691
- // ../core/dist/common-auth-embedded/logger/engine.js
5692
- import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
5693
- import { open as open5 } from "node:fs/promises";
5694
- import { dirname as dirname8, resolve as resolve3 } from "node:path";
5695
- function chmodPrivate(path2) {
5696
- try {
5697
- chmodSync(path2, 384);
5698
- } catch {
5945
+ function admit(input) {
5946
+ const scope = input.scope ?? ALL_SCOPE;
5947
+ const requiredLabels = input.requiredLabels ?? DEFAULT_REQUIRED_LABELS;
5948
+ const excluded = [];
5949
+ const refused = [];
5950
+ const survivors = [];
5951
+ for (const row of input.rows) {
5952
+ const exclusion = exclusionFor(row.id, input, input.now);
5953
+ if (exclusion) {
5954
+ excluded.push(exclusion);
5955
+ continue;
5956
+ }
5957
+ if (row.kind === "api-key") {
5958
+ survivors.push({ id: row.id, kind: row.kind });
5959
+ continue;
5960
+ }
5961
+ const projection = projectQuota(row.quota, scope);
5962
+ const refusal3 = judgeStageOne(row.id, projection, requiredLabels, input.now);
5963
+ if (refusal3) {
5964
+ refused.push(refusal3);
5965
+ continue;
5966
+ }
5967
+ survivors.push({ id: row.id, kind: row.kind, projection });
5699
5968
  }
5700
- }
5701
- function rotateIfNeeded(f) {
5702
- try {
5703
- if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
5704
- return;
5705
- for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
5706
- if (existsSync(`${f}.${i}`)) {
5707
- const rotated2 = `${f}.${i + 1}`;
5708
- renameSync(`${f}.${i}`, rotated2);
5709
- chmodPrivate(rotated2);
5710
- }
5969
+ const spent = new Map(survivors.flatMap((row) => {
5970
+ const reset = budgetExhaustedResetAt(row.projection, input.now);
5971
+ return reset ? [[row.id, reset]] : [];
5972
+ }));
5973
+ const lastPath = spent.size > 0 && spent.size === survivors.length;
5974
+ const admitted = [];
5975
+ for (const row of survivors) {
5976
+ const reset = spent.get(row.id);
5977
+ if (reset === void 0) {
5978
+ admitted.push(row);
5979
+ } else if (lastPath) {
5980
+ admitted.push({ ...row, lastPath: true });
5981
+ } else {
5982
+ refused.push({ id: row.id, stage: 2, reason: "budget-spent", ...reset });
5711
5983
  }
5712
- const rotated = `${f}.1`;
5713
- renameSync(f, rotated);
5714
- chmodPrivate(rotated);
5715
- } catch {
5716
5984
  }
5985
+ const order = new Map(input.rows.map((row, index) => [row.id, index]));
5986
+ const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
5987
+ refused.sort(byInput);
5988
+ const pulls = refused.filter((refusal3) => "pullRequested" in refusal3).map((refusal3) => refusal3.id);
5989
+ for (const id of pulls)
5990
+ input.requestPull?.(id);
5991
+ return { admitted, refused, excluded, pulls };
5717
5992
  }
5718
- async function closeWindowsFile(sink) {
5719
- const { file, handle } = sink;
5720
- sink.file = void 0;
5721
- sink.handle = void 0;
5722
- if (file && handle)
5723
- await privateOperation(file, "log-close", () => handle.close());
5724
- }
5725
- async function openWindowsFile(sink, file) {
5726
- await ensurePrivateDirectory(dirname8(file));
5727
- try {
5728
- await verifyPrivate(file, "file", true);
5729
- } catch (error) {
5730
- if (error.code !== "ENOENT")
5731
- throw error;
5732
- try {
5733
- await createPrivateBytes(file, "");
5734
- } catch (creationError) {
5735
- if (creationError.code !== "EEXIST")
5736
- throw creationError;
5737
- await verifyPrivate(file, "file", true);
5738
- }
5993
+ var init_admission = __esm({
5994
+ "../core/dist/common-auth-embedded/routing/admission.js"() {
5995
+ "use strict";
5996
+ init_map();
5997
+ init_projection();
5998
+ }
5999
+ });
6000
+
6001
+ // ../core/dist/common-auth-embedded/routing/ordered.js
6002
+ function resolveRoutingMode(value) {
6003
+ switch (value) {
6004
+ case "sticky-balanced":
6005
+ return { mode: "sticky-balanced", placement: "roster" };
6006
+ case "main-first":
6007
+ return { mode: "ordered", placement: "main-first" };
6008
+ case "fallback-first":
6009
+ return { mode: "ordered", placement: "fallback-first" };
6010
+ default:
6011
+ return { mode: "ordered", placement: "roster" };
5739
6012
  }
5740
- sink.handle = await privateOperation(file, "log-open", () => open5(file, "a"));
5741
- sink.file = file;
5742
- return sink.handle;
5743
6013
  }
5744
- async function flushWindowsFile(sink, file, text2) {
5745
- file = resolve3(file);
5746
- try {
5747
- if (sink.file !== file)
5748
- await closeWindowsFile(sink);
5749
- let handle = sink.handle ?? await openWindowsFile(sink, file);
5750
- const info = await privateOperation(file, "log-stat", () => handle.stat());
5751
- if (info.size >= MAX_BYTES) {
5752
- await closeWindowsFile(sink);
5753
- for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
5754
- const source = i === 0 ? file : `${file}.${i}`;
5755
- const target = `${file}.${i + 1}`;
5756
- try {
5757
- await verifyPrivate(source, "file", true);
5758
- } catch (error) {
5759
- if (error.code === "ENOENT")
5760
- continue;
5761
- throw error;
5762
- }
5763
- try {
5764
- await verifyPrivate(target, "file", true);
5765
- } catch (error) {
5766
- if (error.code !== "ENOENT")
5767
- throw error;
5768
- }
5769
- await replaceWindowsFile(source, target);
5770
- await verifyPrivate(target, "file");
5771
- }
5772
- handle = await openWindowsFile(sink, file);
6014
+ function orderForPlacement(ids, placement, formerMainId = DEFAULT_FORMER_MAIN_ID) {
6015
+ if (placement === "roster" || !ids.includes(formerMainId))
6016
+ return [...ids];
6017
+ const rest = ids.filter((id) => id !== formerMainId);
6018
+ return placement === "main-first" ? [formerMainId, ...rest] : [...rest, formerMainId];
6019
+ }
6020
+ function routeOrdered(input) {
6021
+ const admission = admit(input);
6022
+ const admitted = new Set(admission.admitted.map((row) => row.id));
6023
+ const order = orderForPlacement(input.rows.map((row) => row.id), input.placement ?? "roster", input.formerMainId).filter((id) => admitted.has(id) && input.killswitch?.get(id) !== false);
6024
+ return { order, admission };
6025
+ }
6026
+ function nextOrderedAttempt(order, attempts2, retryStatuses) {
6027
+ const last = attempts2.at(-1);
6028
+ if (last !== void 0) {
6029
+ if (last.status === void 0 || !retryStatuses.includes(last.status)) {
6030
+ return void 0;
5773
6031
  }
5774
- await privateOperation(file, "log-append", () => handle.appendFile(text2, "utf8"));
5775
- } catch (error) {
5776
- await closeWindowsFile(sink).catch(() => {
5777
- });
5778
- throw error;
5779
6032
  }
6033
+ const tried = new Set(attempts2.map((attempt) => attempt.id));
6034
+ return order.find((id) => !tried.has(id));
5780
6035
  }
5781
- function safeSerialize(data) {
5782
- try {
5783
- return ` ${JSON.stringify(data)}`;
5784
- } catch {
5785
- return " [unserializable]";
6036
+ var DEFAULT_FORMER_MAIN_ID;
6037
+ var init_ordered = __esm({
6038
+ "../core/dist/common-auth-embedded/routing/ordered.js"() {
6039
+ "use strict";
6040
+ init_admission();
6041
+ DEFAULT_FORMER_MAIN_ID = "main";
5786
6042
  }
6043
+ });
6044
+
6045
+ // ../core/dist/common-auth-embedded/routing/pins.js
6046
+ function isPinValid(pin, validIds, currentIdentity) {
6047
+ if (!validIds.has(pin.accountId))
6048
+ return false;
6049
+ return !(typeof pin.wireIdentity === "string" && typeof currentIdentity === "string" && pin.wireIdentity !== currentIdentity);
5787
6050
  }
5788
- function createEngine(options) {
5789
- let logFileSource;
5790
- let initLevelSource;
5791
- let runtimeLevel;
5792
- let redactor = createRedactor();
5793
- let captureSink;
5794
- let buffer = [];
5795
- let timer;
5796
- let orderedSink = Promise.resolve();
5797
- let sinkError;
5798
- const windowsFile = {};
5799
- function queueWindows(operation) {
5800
- const next = orderedSink.then(operation);
5801
- orderedSink = next.catch((error) => {
5802
- sinkError = error;
5803
- });
5804
- return next;
5805
- }
5806
- function configure(next) {
5807
- if (windowsPrivateFiles && next.file !== logFileSource)
5808
- void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
5809
- });
5810
- logFileSource = next.file;
5811
- initLevelSource = next.level;
5812
- redactor = createRedactor(next);
5813
- captureSink = next.captureSink;
6051
+ function pendingBytesForPins(pins, quotaCheckedAtById, excludedSessionKey) {
6052
+ const pending = /* @__PURE__ */ new Map();
6053
+ for (const [sessionKey, pin] of pins) {
6054
+ if (sessionKey === excludedSessionKey)
6055
+ continue;
6056
+ if (pin.quotaCheckedAt !== quotaCheckedAtById.get(pin.accountId))
6057
+ continue;
6058
+ pending.set(pin.accountId, (pending.get(pin.accountId) ?? 0) + (pin.inputBytes ?? 0));
5814
6059
  }
5815
- function setLogLevel3(l) {
5816
- if (l === void 0 || l in ORDER)
5817
- runtimeLevel = l;
6060
+ return pending;
6061
+ }
6062
+ var init_pins = __esm({
6063
+ "../core/dist/common-auth-embedded/routing/pins.js"() {
6064
+ "use strict";
5818
6065
  }
5819
- function logFilePath() {
5820
- if (logFileSource === void 0)
5821
- return void 0;
5822
- const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
5823
- return resolved || void 0;
6066
+ });
6067
+
6068
+ // ../core/dist/common-auth-embedded/routing/sticky.js
6069
+ function snapshotCheckedAt(quota, entryCheckedAt) {
6070
+ for (const checkedAt of [quota?.checkedAt, entryCheckedAt]) {
6071
+ if (typeof checkedAt === "number" && Number.isFinite(checkedAt)) {
6072
+ return checkedAt;
6073
+ }
5824
6074
  }
5825
- function configuredLevel() {
5826
- if (runtimeLevel)
5827
- return runtimeLevel;
5828
- const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
5829
- if (floor && floor in ORDER)
5830
- return floor;
5831
- return "info";
6075
+ return void 0;
6076
+ }
6077
+ function defaultStickyStatusClass(status) {
6078
+ if (status === 401 || status === 403)
6079
+ return "permanent";
6080
+ if (status === void 0 || status === 0 || !Number.isFinite(status) || status >= 500 && status <= 599 || status === 429) {
6081
+ return "transient";
5832
6082
  }
5833
- function flushLogs3(close = true) {
5834
- if (timer) {
5835
- clearTimeout(timer);
5836
- timer = void 0;
5837
- }
5838
- if (!buffer.length) {
5839
- if (windowsPrivateFiles)
5840
- return queueWindows(async () => {
5841
- if (close)
5842
- await closeWindowsFile(windowsFile);
5843
- if (sinkError)
5844
- throw sinkError;
5845
- });
5846
- return;
5847
- }
5848
- let file;
5849
- try {
5850
- file = logFilePath();
5851
- } catch {
5852
- buffer = [];
5853
- if (windowsPrivateFiles && close)
5854
- return queueWindows(() => closeWindowsFile(windowsFile));
5855
- return;
5856
- }
5857
- const text2 = buffer.join("");
5858
- buffer = [];
5859
- if (!file) {
5860
- if (windowsPrivateFiles && close)
5861
- return queueWindows(() => closeWindowsFile(windowsFile));
5862
- return;
5863
- }
5864
- if (windowsPrivateFiles) {
5865
- return queueWindows(async () => {
5866
- try {
5867
- await flushWindowsFile(windowsFile, file, text2);
5868
- } finally {
5869
- if (close)
5870
- await closeWindowsFile(windowsFile);
5871
- }
5872
- });
5873
- }
5874
- try {
5875
- rotateIfNeeded(file);
5876
- if (existsSync(file))
5877
- chmodPrivate(file);
5878
- appendFileSync(file, text2, { encoding: "utf8", mode: 384 });
5879
- } catch {
6083
+ return "healthy";
6084
+ }
6085
+ function windowReadings(quota) {
6086
+ return quota.limits.filter((limit) => limit.kind === "reading").sort((left, right) => {
6087
+ const leftKnown = left.windowMinutes !== void 0;
6088
+ const rightKnown = right.windowMinutes !== void 0;
6089
+ if (leftKnown !== rightKnown)
6090
+ return leftKnown ? -1 : 1;
6091
+ if (leftKnown && rightKnown) {
6092
+ return (right.windowMinutes ?? 0) - (left.windowMinutes ?? 0);
5880
6093
  }
6094
+ return 0;
6095
+ });
6096
+ }
6097
+ function decideStickyBreak(input) {
6098
+ const statusClass = (input.classifyStatus ?? defaultStickyStatusClass)(input.status);
6099
+ if (statusClass === "permanent") {
6100
+ return { action: "migrate", reason: "permanent" };
5881
6101
  }
5882
- function schedule2() {
5883
- if (!timer)
5884
- timer = setTimeout(() => {
5885
- timer = void 0;
5886
- const flushed = flushLogs3(false);
5887
- if (flushed instanceof Promise)
5888
- void flushed.catch(() => {
5889
- });
5890
- }, 500);
5891
- }
5892
- function emit(channel, level, message, data) {
5893
- if (logFileSource === void 0 && captureSink === void 0)
5894
- return;
5895
- try {
5896
- if (ORDER[level] > ORDER[configuredLevel()])
5897
- return;
5898
- const scrubbedMessage = redactor.redactStrings(message);
5899
- let scrubbedData;
5900
- try {
5901
- scrubbedData = redactor.redact(data);
5902
- } catch {
5903
- scrubbedData = "[unserializable]";
5904
- }
5905
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${level.toUpperCase()} [${channel}] ${scrubbedMessage}` + (data === void 0 ? "" : safeSerialize(scrubbedData)) + "\n";
5906
- try {
5907
- captureSink?.({
5908
- channel,
5909
- level,
5910
- message: scrubbedMessage,
5911
- data: scrubbedData
5912
- });
5913
- } catch {
5914
- }
5915
- if (logFileSource === void 0)
5916
- return;
5917
- buffer.push(line);
5918
- if (buffer.length >= 50) {
5919
- const flushed = flushLogs3(false);
5920
- if (flushed instanceof Promise)
5921
- void flushed.catch(() => {
5922
- });
5923
- } else
5924
- schedule2();
5925
- } catch {
6102
+ if (!input.quota)
6103
+ return { action: "retain", reason: "unknown" };
6104
+ const checkedAt = snapshotCheckedAt(input.quota, input.quotaCheckedAt);
6105
+ if (checkedAt === void 0 || !Number.isFinite(checkedAt) || input.now - checkedAt > QUOTA_STALENESS_MS) {
6106
+ return { action: "retain", reason: "stale" };
6107
+ }
6108
+ if (input.killswitchPasses === false) {
6109
+ return { action: "migrate", reason: "killswitch" };
6110
+ }
6111
+ for (const limit of windowReadings(input.quota)) {
6112
+ const remaining = limit.remainingPercent;
6113
+ if (typeof remaining === "number" && Number.isFinite(remaining) && remaining <= 0) {
6114
+ return {
6115
+ action: "migrate",
6116
+ reason: "exhausted",
6117
+ window: { scope: limit.scope, label: limit.label },
6118
+ ...typeof limit.resetsAt === "string" ? { resetsAt: limit.resetsAt } : {}
6119
+ };
5926
6120
  }
5927
6121
  }
5928
- function createLogger5(channel) {
6122
+ const budgetReset = budgetExhaustedResetAt(input.quota, input.now);
6123
+ if (budgetReset) {
5929
6124
  return {
5930
- error: (m, d) => emit(channel, "error", m, d),
5931
- warn: (m, d) => emit(channel, "warn", m, d),
5932
- info: (m, d) => emit(channel, "info", m, d),
5933
- debug: (m, d) => emit(channel, "debug", m, d),
5934
- trace: (m, d) => emit(channel, "trace", m, d)
6125
+ action: "migrate",
6126
+ reason: "exhausted",
6127
+ resetsAt: budgetReset.resetsAt
5935
6128
  };
5936
6129
  }
5937
- function reset() {
5938
- if (windowsPrivateFiles)
5939
- void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
5940
- });
5941
- sinkError = void 0;
5942
- buffer = [];
5943
- if (timer) {
5944
- clearTimeout(timer);
5945
- timer = void 0;
5946
- }
5947
- logFileSource = void 0;
5948
- initLevelSource = void 0;
5949
- runtimeLevel = void 0;
5950
- redactor = createRedactor();
5951
- captureSink = void 0;
5952
- }
5953
- if (options)
5954
- configure(options);
5955
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3, reset };
5956
- }
5957
- function createLoggerInstance(options) {
5958
- const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine(options);
5959
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
5960
- }
5961
- function initLogger(options) {
5962
- defaultEngine.configure(options);
5963
- const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = defaultEngine;
5964
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
5965
- }
5966
- function setLogLevel(l) {
5967
- defaultEngine.setLogLevel(l);
6130
+ return { action: "retain", reason: statusClass };
5968
6131
  }
5969
- function flushLogs() {
5970
- return defaultEngine.flushLogs();
6132
+ function sustainableWindowWeight(window, reservePercent, now) {
6133
+ const spendable = Math.max(0, window.remainingPercent - reservePercent);
6134
+ if (spendable <= 0)
6135
+ return 0;
6136
+ if (!window.resetsAt)
6137
+ return spendable;
6138
+ const resetMs = Date.parse(window.resetsAt);
6139
+ if (!Number.isFinite(resetMs) || resetMs <= now)
6140
+ return spendable;
6141
+ const hours = Math.max((resetMs - now) / 36e5, MIN_RESET_HOURS);
6142
+ return spendable / hours;
5971
6143
  }
5972
- function createLogger2(channel) {
5973
- return defaultEngine.createLogger(channel);
6144
+ function compareAccountIds(left, right) {
6145
+ if (left < right)
6146
+ return -1;
6147
+ if (left > right)
6148
+ return 1;
6149
+ return 0;
5974
6150
  }
5975
- async function flushForTest() {
5976
- return defaultEngine.flushLogs();
6151
+ function candidateWeight(candidate, now) {
6152
+ if (!candidate.quota)
6153
+ return void 0;
6154
+ const quotaCheckedAt = snapshotCheckedAt(candidate.quota, candidate.quotaCheckedAt);
6155
+ if (quotaCheckedAt === void 0 || now - quotaCheckedAt > QUOTA_STALENESS_MS) {
6156
+ return void 0;
6157
+ }
6158
+ const weights = windowReadings(candidate.quota).map((limit) => sustainableWindowWeight({
6159
+ remainingPercent: limit.remainingPercent ?? Number.NaN,
6160
+ ...limit.resetsAt === void 0 ? {} : { resetsAt: limit.resetsAt }
6161
+ }, candidate.reservePercent[limit.label] ?? 0, now));
6162
+ const budget = candidate.quota.budget;
6163
+ if (budget && typeof budget.remainingPercent === "number" && Number.isFinite(budget.remainingPercent)) {
6164
+ weights.push(sustainableWindowWeight({
6165
+ remainingPercent: budget.remainingPercent,
6166
+ ...budget.resetsAt === void 0 ? {} : { resetsAt: budget.resetsAt }
6167
+ }, 0, now));
6168
+ }
6169
+ const weight = weights.length > 0 ? Math.min(...weights) : 0;
6170
+ return weight > 0 ? { candidate, quotaCheckedAt, weight } : void 0;
5977
6171
  }
5978
- function resetLoggerForTest() {
5979
- defaultEngine.reset();
6172
+ function selectStickyCandidate(input) {
6173
+ const eligibleCandidates = input.candidates.filter((candidate) => candidate.killswitchPasses !== false);
6174
+ if (input.candidates.length === 0) {
6175
+ throw new Error("Cannot select a sticky candidate: input.candidates is empty");
6176
+ }
6177
+ if (eligibleCandidates.length === 0)
6178
+ return void 0;
6179
+ const weighted = eligibleCandidates.map((candidate) => candidateWeight(candidate, input.now)).filter((candidate) => candidate !== void 0);
6180
+ if (weighted.length > 0) {
6181
+ weighted.sort((left, right) => {
6182
+ const leftScore = ((input.pendingBytes.get(left.candidate.accountId) ?? 0) + input.requestBytes) / Math.max(left.weight, MIN_WEIGHT);
6183
+ const rightScore = ((input.pendingBytes.get(right.candidate.accountId) ?? 0) + input.requestBytes) / Math.max(right.weight, MIN_WEIGHT);
6184
+ return leftScore - rightScore || left.candidate.configuredOrder - right.candidate.configuredOrder || compareAccountIds(left.candidate.accountId, right.candidate.accountId);
6185
+ });
6186
+ const selected = weighted[0];
6187
+ if (selected) {
6188
+ return {
6189
+ accountId: selected.candidate.accountId,
6190
+ quotaCheckedAt: selected.quotaCheckedAt,
6191
+ source: "weighted"
6192
+ };
6193
+ }
6194
+ }
6195
+ input.onEmptyWeightedSet?.();
6196
+ const fallback = [...eligibleCandidates].sort((left, right) => {
6197
+ const leftHasCredits = (left.resetCreditsApplicable ?? 0) > 0 ? 1 : 0;
6198
+ const rightHasCredits = (right.resetCreditsApplicable ?? 0) > 0 ? 1 : 0;
6199
+ return rightHasCredits - leftHasCredits || left.configuredOrder - right.configuredOrder || compareAccountIds(left.accountId, right.accountId);
6200
+ })[0];
6201
+ if (!fallback) {
6202
+ throw new Error("Cannot select a sticky candidate: input.candidates is empty");
6203
+ }
6204
+ return {
6205
+ accountId: fallback.accountId,
6206
+ quotaCheckedAt: snapshotCheckedAt(fallback.quota, fallback.quotaCheckedAt),
6207
+ source: "mode-fallback"
6208
+ };
5980
6209
  }
5981
- var ORDER, MAX_BYTES, ROTATE_KEEP, defaultEngine;
5982
- var init_engine = __esm({
5983
- "../core/dist/common-auth-embedded/logger/engine.js"() {
5984
- "use strict";
5985
- init_private_files();
5986
- init_redact();
5987
- ORDER = {
5988
- error: 0,
5989
- warn: 1,
5990
- info: 2,
5991
- debug: 3,
5992
- trace: 4
6210
+ function routeSticky(input) {
6211
+ const admission = admit(input);
6212
+ const admitted = new Map(admission.admitted.map((row) => [row.id, row]));
6213
+ const refusals = new Map(admission.refused.map((r) => [r.id, r]));
6214
+ const excluded = new Set(admission.excluded.map((row) => row.id));
6215
+ const validIds = new Set(input.rows.map((row) => row.id));
6216
+ const pinValid = input.pin !== void 0 && isPinValid(input.pin, validIds, input.identities?.get(input.pin.accountId));
6217
+ if (pinValid && input.pin) {
6218
+ const pinned = admitted.get(input.pin.accountId);
6219
+ if (pinned && input.killswitch?.get(pinned.id) !== false) {
6220
+ return {
6221
+ outcome: "dispatch",
6222
+ accountId: pinned.id,
6223
+ source: "pin",
6224
+ ...pinned.projection?.checkedAt === void 0 ? {} : { quotaCheckedAt: pinned.projection.checkedAt },
6225
+ pin: { action: "retain" },
6226
+ refusedSelections: [],
6227
+ admission
6228
+ };
6229
+ }
6230
+ }
6231
+ const pinRefusal = input.pin ? refusals.get(input.pin.accountId) : void 0;
6232
+ const pinMoves = pinValid && input.pin !== void 0 && input.refusedPinPolicy === "move-on-confirmed-exhaustion" && (input.killswitch?.get(input.pin.accountId) === false || pinRefusal?.reason === "exhausted" || pinRefusal?.reason === "budget-spent");
6233
+ const reserveFor = (row) => {
6234
+ const perRow = typeof input.rowReservePercent === "function" ? input.rowReservePercent(row) : input.rowReservePercent?.get(row.id);
6235
+ return perRow ?? input.reservePercent ?? {};
6236
+ };
6237
+ const scope = input.scope;
6238
+ let candidates = input.rows.map((row, configuredOrder) => ({ row, configuredOrder })).filter(({ row }) => !excluded.has(row.id)).map(({ row, configuredOrder }) => {
6239
+ const killswitchPasses = input.killswitch?.get(row.id);
6240
+ const credits = input.resetCreditsApplicable?.get(row.id);
6241
+ return {
6242
+ accountId: row.id,
6243
+ quota: row.kind === "api-key" ? void 0 : admitted.get(row.id)?.projection ?? projectQuota(row.quota, scope),
6244
+ reservePercent: reserveFor(row),
6245
+ configuredOrder,
6246
+ ...credits === void 0 ? {} : { resetCreditsApplicable: credits },
6247
+ ...killswitchPasses === void 0 ? {} : { killswitchPasses }
6248
+ };
6249
+ });
6250
+ const refusedSelections = [];
6251
+ const unplaced = pinValid ? { action: "retain" } : input.pin ? { action: "clear" } : { action: "none" };
6252
+ while (candidates.length > 0) {
6253
+ const selection = selectStickyCandidate({
6254
+ candidates,
6255
+ pendingBytes: input.pendingBytes ?? /* @__PURE__ */ new Map(),
6256
+ requestBytes: input.requestBytes,
6257
+ now: input.now,
6258
+ ...input.onEmptyWeightedSet ? { onEmptyWeightedSet: input.onEmptyWeightedSet } : {}
6259
+ });
6260
+ if (!selection)
6261
+ break;
6262
+ const refusal3 = refusals.get(selection.accountId);
6263
+ if (refusal3) {
6264
+ refusedSelections.push(refusal3);
6265
+ candidates = candidates.filter((candidate) => candidate.accountId !== selection.accountId);
6266
+ continue;
6267
+ }
6268
+ const identity = input.identities?.get(selection.accountId);
6269
+ return {
6270
+ outcome: "dispatch",
6271
+ accountId: selection.accountId,
6272
+ source: selection.source,
6273
+ ...selection.quotaCheckedAt === void 0 ? {} : { quotaCheckedAt: selection.quotaCheckedAt },
6274
+ pin: pinValid && !pinMoves ? { action: "retain" } : {
6275
+ action: "assign",
6276
+ pin: {
6277
+ accountId: selection.accountId,
6278
+ inputBytes: input.requestBytes,
6279
+ ...identity === void 0 ? {} : { wireIdentity: identity },
6280
+ ...selection.quotaCheckedAt === void 0 ? {} : { quotaCheckedAt: selection.quotaCheckedAt }
6281
+ }
6282
+ },
6283
+ refusedSelections,
6284
+ admission
5993
6285
  };
5994
- MAX_BYTES = 5 * 1024 * 1024;
5995
- ROTATE_KEEP = 3;
5996
- defaultEngine = createEngine();
6286
+ }
6287
+ return {
6288
+ outcome: "no-admissible-account",
6289
+ pin: unplaced,
6290
+ refusedSelections,
6291
+ admission
6292
+ };
6293
+ }
6294
+ var QUOTA_STALENESS_MS, MIN_RESET_HOURS, MIN_WEIGHT;
6295
+ var init_sticky = __esm({
6296
+ "../core/dist/common-auth-embedded/routing/sticky.js"() {
6297
+ "use strict";
6298
+ init_projection();
6299
+ init_admission();
6300
+ init_pins();
6301
+ QUOTA_STALENESS_MS = 15 * 6e4;
6302
+ MIN_RESET_HOURS = 1 / 60;
6303
+ MIN_WEIGHT = 1e-6;
5997
6304
  }
5998
6305
  });
5999
-
6000
- // ../core/dist/common-auth-embedded/logger/index.js
6001
- var logger_exports = {};
6002
- __export(logger_exports, {
6003
- createCaptureSink: () => createCaptureSink,
6004
- createLogger: () => createLogger2,
6005
- createLoggerInstance: () => createLoggerInstance,
6006
- createRedactor: () => createRedactor,
6007
- flushForTest: () => flushForTest,
6008
- flushLogs: () => flushLogs,
6009
- initLogger: () => initLogger,
6010
- redact: () => redact,
6011
- redactStrings: () => redactStrings,
6012
- resetLoggerForTest: () => resetLoggerForTest,
6013
- setLogLevel: () => setLogLevel
6014
- });
6015
- var init_logger = __esm({
6016
- "../core/dist/common-auth-embedded/logger/index.js"() {
6306
+
6307
+ // ../core/dist/common-auth-embedded/routing/index.js
6308
+ var routing_exports = {};
6309
+ __export(routing_exports, {
6310
+ DEFAULT_FORMER_MAIN_ID: () => DEFAULT_FORMER_MAIN_ID,
6311
+ MIN_RESET_HOURS: () => MIN_RESET_HOURS,
6312
+ MIN_WEIGHT: () => MIN_WEIGHT,
6313
+ QUOTA_STALENESS_MS: () => QUOTA_STALENESS_MS,
6314
+ admit: () => admit,
6315
+ decideStickyBreak: () => decideStickyBreak,
6316
+ defaultStickyStatusClass: () => defaultStickyStatusClass,
6317
+ exclusionFor: () => exclusionFor,
6318
+ isPinValid: () => isPinValid,
6319
+ nextOrderedAttempt: () => nextOrderedAttempt,
6320
+ orderForPlacement: () => orderForPlacement,
6321
+ pendingBytesForPins: () => pendingBytesForPins,
6322
+ resolveRoutingMode: () => resolveRoutingMode,
6323
+ routeOrdered: () => routeOrdered,
6324
+ routeSticky: () => routeSticky,
6325
+ selectStickyCandidate: () => selectStickyCandidate,
6326
+ snapshotCheckedAt: () => snapshotCheckedAt,
6327
+ sustainableWindowWeight: () => sustainableWindowWeight
6328
+ });
6329
+ var init_routing = __esm({
6330
+ "../core/dist/common-auth-embedded/routing/index.js"() {
6017
6331
  "use strict";
6018
- init_capture_sink();
6019
- init_engine();
6020
- init_redact();
6332
+ init_admission();
6333
+ init_ordered();
6334
+ init_pins();
6335
+ init_sticky();
6021
6336
  }
6022
6337
  });
6023
6338
 
@@ -6314,13 +6629,16 @@ function addedText(name, result) {
6314
6629
  function failureMessage(error) {
6315
6630
  return projectFailure(error).text;
6316
6631
  }
6317
- async function snapshot(store) {
6632
+ async function snapshot(options) {
6633
+ const { store } = options;
6318
6634
  const load = await store.read();
6319
6635
  const read = await store.readSettings();
6636
+ const vault = await options.routing?.vaultOrder?.();
6320
6637
  return {
6321
6638
  load,
6322
6639
  rows: distinctRows(load),
6323
- settings: read.status === "error" ? {} : read.settings
6640
+ settings: read.status === "error" ? {} : read.settings,
6641
+ ...vault ? { vault } : {}
6324
6642
  };
6325
6643
  }
6326
6644
  function accountView(row, options) {
@@ -6527,6 +6845,57 @@ function quotaSection(options, snap) {
6527
6845
  }
6528
6846
  };
6529
6847
  }
6848
+ async function reorderVault(vault, order) {
6849
+ try {
6850
+ return await vault.reorder(order);
6851
+ } catch (error) {
6852
+ if (error instanceof Error && error.name === "ClaustrumConsumerError" && error.kind === "invalid-order")
6853
+ throw new CommandError("vault-invalid-order", error.message, {
6854
+ cause: error
6855
+ });
6856
+ throw error;
6857
+ }
6858
+ }
6859
+ function invalidVaultOrder(message) {
6860
+ return new CommandError("vault-invalid-order", message);
6861
+ }
6862
+ function vaultNames(vault) {
6863
+ const rows = vault.rows.map((row) => ({
6864
+ id: row.id,
6865
+ label: row.label.trim() || row.id
6866
+ }));
6867
+ const matches2 = (entry) => rows.filter((row) => row.id === entry || row.label === entry);
6868
+ return {
6869
+ ids: rows.map((row) => row.id),
6870
+ nameOf: (id) => rows.find((row) => row.id === id)?.label ?? id,
6871
+ /**
6872
+ * What the order input starts with for an account: its label when
6873
+ * typing that label back names this account alone, else its route id
6874
+ * (two accounts sharing a label, or a label with a comma or line break
6875
+ * in it, either of which would split it into two entries).
6876
+ */
6877
+ entryOf: (id) => {
6878
+ const row = rows.find((entry) => entry.id === id);
6879
+ return row && !/[,\n]/.test(row.label) && matches2(row.label).length === 1 ? row.label : id;
6880
+ },
6881
+ /** The route ids the typed entries name, in order; refuses before any write. */
6882
+ resolve: (entries) => {
6883
+ const ids = [];
6884
+ for (const entry of entries) {
6885
+ const found = matches2(entry);
6886
+ if (found.length === 0)
6887
+ throw invalidVaultOrder(`"${entry}" is not a vault account.`);
6888
+ if (found.length > 1)
6889
+ throw invalidVaultOrder(`"${entry}" matches more than one vault account; enter those accounts by route id.`);
6890
+ const id = found[0].id;
6891
+ if (ids.includes(id))
6892
+ throw invalidVaultOrder(`"${entry}" names an account already in the order.`);
6893
+ ids.push(id);
6894
+ }
6895
+ return ids;
6896
+ }
6897
+ };
6898
+ }
6530
6899
  function routingSection(options, snap) {
6531
6900
  const { store, extraLocks } = options;
6532
6901
  const locks = extraLocks ? { extraLocks } : {};
@@ -6538,14 +6907,16 @@ function routingSection(options, snap) {
6538
6907
  const raw = record(snap.settings.routing).mode;
6539
6908
  const current = typeof raw === "string" && choices.some((choice) => choice.value === raw) ? raw : "ordered";
6540
6909
  const resolved = resolveRoutingMode(current);
6541
- const ids = snap.rows.map((row) => row.id);
6910
+ const vault = snap.vault ? vaultNames(snap.vault) : void 0;
6911
+ const ids = vault ? vault.ids : snap.rows.map((row) => row.id);
6912
+ const nameOf = (id) => vault ? vault.nameOf(id) : id;
6542
6913
  const tried = orderForPlacement(ids, resolved.placement, options.routing?.formerMainId ?? DEFAULT_FORMER_MAIN_ID);
6543
6914
  const label = choices.find((choice) => choice.value === current)?.label ?? current;
6544
6915
  const lines = [`Mode: ${label}`];
6545
6916
  if (ids.length > 0)
6546
- lines.push(`Roster order: ${ids.join(", ")}`);
6917
+ lines.push(`${vault ? "Vault account order" : "Roster order"}: ${ids.map(nameOf).join(", ")}`);
6547
6918
  if (resolved.mode === "ordered" && tried.join() !== ids.join())
6548
- lines.push(`Tried in order: ${tried.join(", ")}`);
6919
+ lines.push(`Tried in order: ${tried.map(nameOf).join(", ")}`);
6549
6920
  const actions = [
6550
6921
  {
6551
6922
  id: "mode",
@@ -6573,15 +6944,16 @@ function routingSection(options, snap) {
6573
6944
  {
6574
6945
  kind: "text",
6575
6946
  id: "order",
6576
- label: "Account ids, first to last",
6577
- value: ids.join(", "),
6947
+ label: vault ? "Vault accounts, first to last, separated by commas" : "Account ids, first to last",
6948
+ value: vault ? ids.map(vault.entryOf).join(", ") : ids.join(", "),
6578
6949
  required: true
6579
6950
  }
6580
6951
  ],
6581
6952
  run: async ({ values }) => {
6582
- const order = String(values.order).split(/[\s,]+/).filter((id) => id.length > 0);
6583
- const result = await store.reorder(order, locks);
6584
- return result.outcome === "unchanged" ? "The order is unchanged." : `Order set to ${result.ids.join(", ")}.`;
6953
+ const text2 = String(values.order);
6954
+ const entries = text2.split(vault ? /[,\n]+/ : /[\s,]+/).map((entry) => entry.trim()).filter((entry) => entry.length > 0);
6955
+ const result = snap.vault && vault ? await reorderVault(snap.vault, vault.resolve(entries)) : await store.reorder(entries, locks);
6956
+ return result.outcome === "unchanged" ? "The order is unchanged." : `Order set to ${result.ids.map(nameOf).join(", ")}.`;
6585
6957
  }
6586
6958
  });
6587
6959
  return {
@@ -6710,7 +7082,7 @@ function limitsSection(options, snap) {
6710
7082
  };
6711
7083
  }
6712
7084
  async function builtinSections(options) {
6713
- const snap = await snapshot(options.store);
7085
+ const snap = await snapshot(options);
6714
7086
  return [
6715
7087
  accountsSection(options, snap),
6716
7088
  quotaSection(options, snap),
@@ -8863,7 +9235,7 @@ var init_any_signal = __esm({
8863
9235
  import { createHash as createHash5, randomBytes as randomBytes2, randomUUID as randomUUID10 } from "node:crypto";
8864
9236
  import { constants as fsConstants } from "node:fs";
8865
9237
  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";
8866
- import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join5, resolve as resolve5 } from "node:path";
9238
+ import { basename as basename3, dirname as dirname9, extname, isAbsolute as isAbsolute2, join as join6, resolve as resolve5 } from "node:path";
8867
9239
  import { ClaustrumCredentialError as ClaustrumCredentialError2, ClaustrumClient as ClaustrumWireClient, writeEnrollmentTokenFile } from "@cortexkit/claustrum-client";
8868
9240
  function classifyEnrollmentError(error) {
8869
9241
  if (!(error instanceof ClaustrumCredentialError2))
@@ -8889,7 +9261,7 @@ function getClaustrumEnrollmentPaths(tokenPath) {
8889
9261
  const extension = extname(tokenPath) || ".json";
8890
9262
  const stem = basename3(tokenPath, extname(tokenPath));
8891
9263
  return {
8892
- statePath: join5(dirname9(tokenPath), `${stem}-state${extension}`),
9264
+ statePath: join6(dirname9(tokenPath), `${stem}-state${extension}`),
8893
9265
  tokenPath
8894
9266
  };
8895
9267
  }
@@ -8897,7 +9269,7 @@ function hostEnrollmentPaths(input) {
8897
9269
  const override = input.override?.trim();
8898
9270
  if (override && !isAbsolute2(override) && !input.cwd)
8899
9271
  throw new ClaustrumConsumerError("invalid-state", "A relative Claustrum enrollment override needs a base directory");
8900
- const tokenPath = override ? isAbsolute2(override) ? override : resolve5(input.cwd, override) : join5(input.stateDir, `${input.host}-enrollment.json`);
9272
+ const tokenPath = override ? isAbsolute2(override) ? override : resolve5(input.cwd, override) : join6(input.stateDir, `${input.host}-enrollment.json`);
8901
9273
  return getClaustrumEnrollmentPaths(tokenPath);
8902
9274
  }
8903
9275
  function isRecord6(value) {
@@ -9130,7 +9502,7 @@ async function writeStateAtomic(path2, state, ancestorOptions = {}) {
9130
9502
  }
9131
9503
  if (windowsPrivateFiles)
9132
9504
  return writePrivateAtomic(path2, bytes);
9133
- const temporary = join5(parent, `.${basename3(path2)}.${process.pid}.${randomUUID10()}.tmp`);
9505
+ const temporary = join6(parent, `.${basename3(path2)}.${process.pid}.${randomUUID10()}.tmp`);
9134
9506
  let descriptor;
9135
9507
  let created = false;
9136
9508
  try {
@@ -9307,7 +9679,7 @@ async function disconnectClaustrumEnrollment(paths, proposedName) {
9307
9679
  await lock.release();
9308
9680
  }
9309
9681
  }
9310
- var ENROLLMENT_SCHEMA, ENROLLMENT_FILE_MAX_BYTES, ENROLLMENT_LOCK_TTL_MS, TOKEN_RE, TERMINAL_ENROLLMENT_CODES, RETRYABLE_ENROLLMENT_CODES, ClaustrumEnrollmentManager;
9682
+ var ENROLLMENT_SCHEMA, ENROLLMENT_FILE_MAX_BYTES, ENROLLMENT_LOCK_TTL_MS, TOKEN_RE, UNSUPPORTED_ENROLLMENT_CODE, TERMINAL_ENROLLMENT_CODES, RETRYABLE_ENROLLMENT_CODES, ClaustrumEnrollmentManager;
9311
9683
  var init_enrollment = __esm({
9312
9684
  "../core/dist/common-auth-embedded/claustrum/enrollment.js"() {
9313
9685
  "use strict";
@@ -9318,7 +9690,13 @@ var init_enrollment = __esm({
9318
9690
  ENROLLMENT_FILE_MAX_BYTES = 16 * 1024;
9319
9691
  ENROLLMENT_LOCK_TTL_MS = 3e4;
9320
9692
  TOKEN_RE = /^[0-9a-f]{64}$/;
9693
+ UNSUPPORTED_ENROLLMENT_CODE = "unknown_method";
9321
9694
  TERMINAL_ENROLLMENT_CODES = /* @__PURE__ */ new Set([
9695
+ // The daemon's answer to an operation it does not implement: a vault built
9696
+ // before the enrollment ceremony. It arrives as a transport Error frame with
9697
+ // no class, which claustrum-client before 0.13.0 labels transient/retry, but
9698
+ // asking again can never succeed.
9699
+ UNSUPPORTED_ENROLLMENT_CODE,
9322
9700
  "invalid_params",
9323
9701
  "pending_exists",
9324
9702
  "not_found",
@@ -9452,6 +9830,18 @@ var init_enrollment = __esm({
9452
9830
  retryCode: refusal3.code
9453
9831
  };
9454
9832
  }
9833
+ if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE) {
9834
+ await lock.assertOwned();
9835
+ await unlink6(this.#paths.statePath).catch((cause) => {
9836
+ if (cause.code !== "ENOENT")
9837
+ throw cause;
9838
+ });
9839
+ return {
9840
+ state: "unavailable",
9841
+ proposedName: state.proposedName,
9842
+ code: refusal3.code
9843
+ };
9844
+ }
9455
9845
  return this.#block(state, refusal3.code);
9456
9846
  }
9457
9847
  }
@@ -10127,6 +10517,59 @@ var init_custody = __esm({
10127
10517
  }
10128
10518
  });
10129
10519
 
10520
+ // ../core/dist/common-auth-embedded/quota/pending.js
10521
+ function quotaFields(publication2, witness = "") {
10522
+ const result = /* @__PURE__ */ new Map();
10523
+ const { observation } = publication2;
10524
+ const add = (key, at, part) => result.set(`${witness}:${key}`, {
10525
+ at,
10526
+ order: 0,
10527
+ publication: { ...publication2, observation: part }
10528
+ });
10529
+ const keyFor = (scope, label) => JSON.stringify([scope ?? "all", label]);
10530
+ const read = /* @__PURE__ */ new Set();
10531
+ for (const reading of observation.readings ?? []) {
10532
+ const key = keyFor(reading.scope, reading.label);
10533
+ read.add(key);
10534
+ add(key, observation.checkedAt, {
10535
+ checkedAt: observation.checkedAt,
10536
+ readings: [{ ...reading }]
10537
+ });
10538
+ }
10539
+ for (const pair of observation.coverage ?? []) {
10540
+ const key = keyFor(pair.scope, pair.label);
10541
+ if (!read.has(key))
10542
+ add(key, observation.checkedAt, {
10543
+ checkedAt: observation.checkedAt,
10544
+ coverage: [{ ...pair }]
10545
+ });
10546
+ }
10547
+ if (observation.budget)
10548
+ add("budget", observation.checkedAt, {
10549
+ checkedAt: observation.checkedAt,
10550
+ budget: { ...observation.budget }
10551
+ });
10552
+ for (const [name, counter] of Object.entries(observation.counters ?? {})) {
10553
+ add(`counter:${name}`, counter.checkedAt, {
10554
+ checkedAt: observation.checkedAt,
10555
+ counters: { [name]: { ...counter } }
10556
+ });
10557
+ }
10558
+ if (observation.credits)
10559
+ add("credits", observation.credits.checkedAt, {
10560
+ checkedAt: observation.checkedAt,
10561
+ credits: { ...observation.credits }
10562
+ });
10563
+ if (!result.size)
10564
+ add("empty", observation.checkedAt, { checkedAt: observation.checkedAt });
10565
+ return result;
10566
+ }
10567
+ var init_pending = __esm({
10568
+ "../core/dist/common-auth-embedded/quota/pending.js"() {
10569
+ "use strict";
10570
+ }
10571
+ });
10572
+
10130
10573
  // ../core/dist/common-auth-embedded/claustrum/interlock.js
10131
10574
  function matches(entry, credentialId, accountIdentity) {
10132
10575
  if (entry.accountIdentity !== void 0 && accountIdentity !== void 0)
@@ -10427,6 +10870,52 @@ function acceptVaultRoute(path2, routeId) {
10427
10870
  };
10428
10871
  });
10429
10872
  }
10873
+ function invalidOrder(message) {
10874
+ return new ClaustrumConsumerError("invalid-order", message);
10875
+ }
10876
+ function vaultOrderProblem(rows, routeIds) {
10877
+ if (!Array.isArray(routeIds))
10878
+ return "route ids must be an array of route ids";
10879
+ const rosterIds = new Set(rows.map((row) => row.routeId));
10880
+ const given = /* @__PURE__ */ new Set();
10881
+ for (const id of routeIds) {
10882
+ if (typeof id !== "string")
10883
+ return "route ids must be an array of route ids";
10884
+ if (given.has(id))
10885
+ return `route id ${id} appears more than once`;
10886
+ if (!rosterIds.has(id))
10887
+ return `route id ${id} is not in the roster`;
10888
+ given.add(id);
10889
+ }
10890
+ const missing = [...rosterIds].filter((id) => !given.has(id)).length;
10891
+ if (missing > 0)
10892
+ return `the order leaves out ${missing} roster route id${missing === 1 ? "" : "s"}`;
10893
+ return void 0;
10894
+ }
10895
+ function reorderVaultRoster(path2, routeIds, options = {}) {
10896
+ return mutateVaultRoster(path2, (current) => {
10897
+ const rows = current?.rows ?? [];
10898
+ const problem = vaultOrderProblem(rows, routeIds);
10899
+ if (problem)
10900
+ throw invalidOrder(problem);
10901
+ const byId = /* @__PURE__ */ new Map();
10902
+ for (const row of rows) {
10903
+ const group = byId.get(row.routeId);
10904
+ if (group)
10905
+ group.push(row);
10906
+ else
10907
+ byId.set(row.routeId, [row]);
10908
+ }
10909
+ const ids = [...routeIds];
10910
+ const next = ids.flatMap((id) => byId.get(id) ?? []);
10911
+ if (!current || next.every((row, index) => row === rows[index]))
10912
+ return { result: { ids, outcome: "unchanged" } };
10913
+ return {
10914
+ next: { ...current, rows: next },
10915
+ result: { ids, outcome: "reordered" }
10916
+ };
10917
+ }, { ...options.signal && { signal: options.signal } });
10918
+ }
10430
10919
  function receiptFence(row, receipt2) {
10431
10920
  if (!memberIds(row).includes(receipt2.credentialId))
10432
10921
  return "refuse";
@@ -10572,8 +11061,8 @@ var init_roster = __esm({
10572
11061
  init_quota();
10573
11062
  init_errors2();
10574
11063
  init_interlock();
10575
- init_quota_writer();
10576
- init_quota_writer();
11064
+ init_quota_writer2();
11065
+ init_quota_writer2();
10577
11066
  DEFAULT_ROUTE_PREFIX = "vault:";
10578
11067
  SKIPPED_REASONS = /* @__PURE__ */ new Set([
10579
11068
  "empty credential id",
@@ -10622,56 +11111,12 @@ function retainVaultQuotaWriter(path2, listener) {
10622
11111
  })();
10623
11112
  }
10624
11113
  function fields(publication2) {
10625
- const result = /* @__PURE__ */ new Map();
10626
- const { observation } = publication2;
10627
- const witness = JSON.stringify([
11114
+ return quotaFields(publication2, JSON.stringify([
10628
11115
  publication2.routeId,
10629
11116
  publication2.receipt?.credentialId,
10630
11117
  publication2.receipt?.accountIdentitySource,
10631
11118
  publication2.receipt?.expectedAccountIdentity
10632
- ]);
10633
- const add = (key, at, part) => result.set(`${witness}:${key}`, {
10634
- at,
10635
- order: 0,
10636
- publication: { ...publication2, observation: part }
10637
- });
10638
- const keyFor = (scope, label) => JSON.stringify([scope ?? "all", label]);
10639
- const read = /* @__PURE__ */ new Set();
10640
- for (const reading of observation.readings ?? []) {
10641
- const key = keyFor(reading.scope, reading.label);
10642
- read.add(key);
10643
- add(key, observation.checkedAt, {
10644
- checkedAt: observation.checkedAt,
10645
- readings: [{ ...reading }]
10646
- });
10647
- }
10648
- for (const pair of observation.coverage ?? []) {
10649
- const key = keyFor(pair.scope, pair.label);
10650
- if (!read.has(key))
10651
- add(key, observation.checkedAt, {
10652
- checkedAt: observation.checkedAt,
10653
- coverage: [{ ...pair }]
10654
- });
10655
- }
10656
- if (observation.budget)
10657
- add("budget", observation.checkedAt, {
10658
- checkedAt: observation.checkedAt,
10659
- budget: { ...observation.budget }
10660
- });
10661
- for (const [name, counter] of Object.entries(observation.counters ?? {})) {
10662
- add(`counter:${name}`, counter.checkedAt, {
10663
- checkedAt: observation.checkedAt,
10664
- counters: { [name]: { ...counter } }
10665
- });
10666
- }
10667
- if (observation.credits)
10668
- add("credits", observation.credits.checkedAt, {
10669
- checkedAt: observation.checkedAt,
10670
- credits: { ...observation.credits }
10671
- });
10672
- if (!result.size)
10673
- add("empty", observation.checkedAt, { checkedAt: observation.checkedAt });
10674
- return result;
11119
+ ]));
10675
11120
  }
10676
11121
  function enqueueVaultQuota(path2, publication2) {
10677
11122
  if (!isQuotaObservation(publication2.observation))
@@ -10695,7 +11140,7 @@ function enqueueVaultQuota(path2, publication2) {
10695
11140
  writer.pending.set(account, pending);
10696
11141
  for (const listener of writer.listeners)
10697
11142
  listener(publication2);
10698
- schedule(writer, COALESCE_MS);
11143
+ schedule(writer, COALESCE_MS2);
10699
11144
  return Promise.resolve(true);
10700
11145
  }
10701
11146
  function orderedFields(pending) {
@@ -10760,7 +11205,7 @@ function flush(writer) {
10760
11205
  writer.running = void 0;
10761
11206
  for (const wake of writer.wake)
10762
11207
  wake();
10763
- const backoff = writer.failures ? Math.min(5e3, 100 * 2 ** Math.min(writer.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS;
11208
+ const backoff = writer.failures ? Math.min(5e3, 100 * 2 ** Math.min(writer.failures, 6)) * (0.5 + Math.random()) : COALESCE_MS2;
10764
11209
  schedule(writer, backoff);
10765
11210
  }
10766
11211
  })();
@@ -10806,16 +11251,17 @@ async function drainVaultQuota(path2, timeoutMs = 1e3) {
10806
11251
  }
10807
11252
  }
10808
11253
  }
10809
- var writers, logger, COALESCE_MS;
10810
- var init_quota_writer = __esm({
11254
+ var writers, logger, COALESCE_MS2;
11255
+ var init_quota_writer2 = __esm({
10811
11256
  "../core/dist/common-auth-embedded/claustrum/quota-writer.js"() {
10812
11257
  "use strict";
10813
11258
  init_logger();
10814
11259
  init_quota();
11260
+ init_pending();
10815
11261
  init_roster();
10816
11262
  writers = /* @__PURE__ */ new Map();
10817
11263
  logger = createLogger2("claustrum");
10818
- COALESCE_MS = 100;
11264
+ COALESCE_MS2 = 100;
10819
11265
  }
10820
11266
  });
10821
11267
 
@@ -10830,7 +11276,7 @@ var init_consumer = __esm({
10830
11276
  init_enrollment();
10831
11277
  init_errors2();
10832
11278
  init_insula();
10833
- init_quota_writer();
11279
+ init_quota_writer2();
10834
11280
  init_roster();
10835
11281
  init_watch();
10836
11282
  ClaustrumConsumer = class {
@@ -11261,7 +11707,10 @@ var init_consumer = __esm({
11261
11707
  let current;
11262
11708
  try {
11263
11709
  current = await this.authorize(routeId, signal);
11264
- } catch {
11710
+ signal?.throwIfAborted();
11711
+ } catch (error) {
11712
+ if (signal?.aborted)
11713
+ throw error;
11265
11714
  }
11266
11715
  if (decideScopedRetryAfter401(options.site, served, current, this.#logger)) {
11267
11716
  await response.body?.cancel().catch(() => {
@@ -11291,6 +11740,17 @@ var init_consumer = __esm({
11291
11740
  await acceptVaultRoute(this.#options.rosterPath, routeId);
11292
11741
  this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
11293
11742
  }
11743
+ /**
11744
+ * Set the order vault accounts are tried in (`reorderVaultRoster`), then
11745
+ * re-read the roster, so the next routing decision in this process uses
11746
+ * the new order without waiting for a discovery. Never contacts the vault.
11747
+ */
11748
+ async reorder(routeIds) {
11749
+ this.#assertOpen();
11750
+ const result = await reorderVaultRoster(this.#options.rosterPath, routeIds);
11751
+ this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
11752
+ return result;
11753
+ }
11294
11754
  /**
11295
11755
  * Store a quota or profile observation for a vault route. The receipt the
11296
11756
  * reading was taken with is required: the observation lands only while the
@@ -11406,6 +11866,7 @@ __export(claustrum_exports, {
11406
11866
  recordVaultAccountQuota: () => recordVaultAccountQuota,
11407
11867
  recordVaultQuota: () => recordVaultQuota,
11408
11868
  refreshVaultRoster: () => refreshVaultRoster,
11869
+ reorderVaultRoster: () => reorderVaultRoster,
11409
11870
  resetClaustrumEnrollmentState: () => resetClaustrumEnrollmentState,
11410
11871
  resolveVaultPrimary: () => resolveVaultPrimary,
11411
11872
  vaultRoutingRows: () => vaultRoutingRows
@@ -11428,7 +11889,7 @@ var init_claustrum = __esm({
11428
11889
  init_host_slot();
11429
11890
  init_insula();
11430
11891
  init_interlock();
11431
- init_quota_writer();
11892
+ init_quota_writer2();
11432
11893
  init_roster();
11433
11894
  init_watch();
11434
11895
  }
@@ -18449,15 +18910,15 @@ function maskSensitiveIdentifier(value) {
18449
18910
 
18450
18911
  // ../core/dist/pi-paths.js
18451
18912
  import { homedir } from "node:os";
18452
- import { dirname as dirname11, join as join6 } from "node:path";
18913
+ import { dirname as dirname11, join as join7 } from "node:path";
18453
18914
  function getPiConfigDir() {
18454
- return process.env.PI_AGENT_DIR?.trim() || join6(homedir(), ".pi", "agent");
18915
+ return process.env.PI_AGENT_DIR?.trim() || join7(homedir(), ".pi", "agent");
18455
18916
  }
18456
18917
  function getPiAntigravityAuthFile() {
18457
- return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join6(getPiConfigDir(), "antigravity-accounts.json");
18918
+ return process.env.PI_ANTIGRAVITY_AUTH_FILE?.trim() || join7(getPiConfigDir(), "antigravity-accounts.json");
18458
18919
  }
18459
18920
  function getPiAntigravityVaultDir() {
18460
- return join6(dirname11(getPiAntigravityAuthFile()), "antigravity-auth-vault");
18921
+ return join7(dirname11(getPiAntigravityAuthFile()), "antigravity-auth-vault");
18461
18922
  }
18462
18923
 
18463
18924
  // ../core/dist/project.js
@@ -19041,11 +19502,16 @@ function mostConstrainedWindow(windows) {
19041
19502
  };
19042
19503
  }
19043
19504
  function poolForBucketId(bucketId) {
19044
- if (bucketId.startsWith("gemini-"))
19045
- return "gemini";
19046
- if (bucketId.startsWith("3p-"))
19047
- return "non-gemini";
19048
- return null;
19505
+ switch (bucketId) {
19506
+ case "gemini-5h":
19507
+ case "gemini-weekly":
19508
+ return "gemini";
19509
+ case "3p-5h":
19510
+ case "3p-weekly":
19511
+ return "non-gemini";
19512
+ default:
19513
+ return null;
19514
+ }
19049
19515
  }
19050
19516
  function parseDescriptionModelCount(description) {
19051
19517
  const prefixMatch = description.match(/^[^:]+:\s*/);
@@ -19066,31 +19532,60 @@ function windowDurationMs(window) {
19066
19532
  }
19067
19533
  }
19068
19534
  function aggregateQuotaSummary(response) {
19069
- const groups = {};
19070
- let totalCount = 0;
19535
+ const windowsByPool = {
19536
+ gemini: /* @__PURE__ */ new Map(),
19537
+ "non-gemini": /* @__PURE__ */ new Map()
19538
+ };
19539
+ const modelCounts = {
19540
+ gemini: 0,
19541
+ "non-gemini": 0
19542
+ };
19543
+ const seenBucketIds = /* @__PURE__ */ new Set();
19544
+ const duplicateBucketIds = /* @__PURE__ */ new Set();
19071
19545
  for (const group of response.groups) {
19072
- const windows = [];
19546
+ const contributingPools = /* @__PURE__ */ new Set();
19073
19547
  for (const bucket of group.buckets) {
19074
- const pool2 = poolForBucketId(bucket.bucketId);
19075
- if (!pool2)
19548
+ if (bucket.disabled === true)
19549
+ continue;
19550
+ const pool = poolForBucketId(bucket.bucketId);
19551
+ if (!pool)
19076
19552
  continue;
19077
- windows.push({
19553
+ contributingPools.add(pool);
19554
+ const window = {
19078
19555
  window: bucket.window,
19079
19556
  remainingFraction: normalizeRemainingFraction(bucket.remainingFraction),
19080
19557
  resetTime: bucket.resetTime
19081
- });
19558
+ };
19559
+ const previous = windowsByPool[pool].get(bucket.bucketId);
19560
+ if (seenBucketIds.has(bucket.bucketId)) {
19561
+ duplicateBucketIds.add(bucket.bucketId);
19562
+ } else {
19563
+ seenBucketIds.add(bucket.bucketId);
19564
+ }
19565
+ if (!previous || window.remainingFraction < previous.remainingFraction) {
19566
+ windowsByPool[pool].set(bucket.bucketId, window);
19567
+ }
19082
19568
  }
19569
+ const modelCount = group.description ? parseDescriptionModelCount(group.description) : 0;
19570
+ for (const pool of contributingPools)
19571
+ modelCounts[pool] += modelCount;
19572
+ }
19573
+ if (duplicateBucketIds.size > 0) {
19574
+ log4.debug("duplicate quota summary bucket ids", {
19575
+ bucketIds: [...duplicateBucketIds].sort()
19576
+ });
19577
+ }
19578
+ const groups = {};
19579
+ let totalCount = 0;
19580
+ for (const pool of ["gemini", "non-gemini"]) {
19581
+ const windows = [...windowsByPool[pool].values()];
19083
19582
  if (windows.length === 0)
19084
19583
  continue;
19085
19584
  windows.sort((a, b) => windowDurationMs(a.window) - windowDurationMs(b.window));
19086
19585
  const constrained = mostConstrainedWindow(windows);
19087
- const recognizedBucket = group.buckets.find((bucket) => poolForBucketId(bucket.bucketId));
19088
- if (!recognizedBucket)
19089
- continue;
19090
- const pool = poolForBucketId(recognizedBucket.bucketId);
19091
- if (!pool || !constrained)
19586
+ if (!constrained)
19092
19587
  continue;
19093
- const modelCount = group.description ? parseDescriptionModelCount(group.description) : 0;
19588
+ const modelCount = modelCounts[pool];
19094
19589
  groups[pool] = {
19095
19590
  remainingFraction: constrained.remainingFraction,
19096
19591
  resetTime: constrained.resetTime,
@@ -19326,7 +19821,7 @@ import {
19326
19821
  writeFileSync
19327
19822
  } from "node:fs";
19328
19823
  import { homedir as homedir3 } from "node:os";
19329
- import { dirname as dirname14, join as join8, resolve as resolve11 } from "node:path";
19824
+ import { dirname as dirname14, join as join10, resolve as resolve11 } from "node:path";
19330
19825
 
19331
19826
  // src/common-auth-embedded/logger/engine.js
19332
19827
  import { appendFileSync as appendFileSync2, chmodSync as chmodSync2, existsSync as existsSync2, renameSync as renameSync2, statSync as statSync3 } from "node:fs";
@@ -19336,7 +19831,8 @@ import { dirname as dirname13, resolve as resolve10 } from "node:path";
19336
19831
  // src/common-auth-embedded/fs/private-files.js
19337
19832
  import { randomUUID as randomUUID11 } from "node:crypto";
19338
19833
  import { lstat as lstat4, readFile as readFile7, rename as rename7, unlink as unlink8 } from "node:fs/promises";
19339
- import { dirname as dirname12, resolve as resolve9 } from "node:path";
19834
+ import { tmpdir as tmpdir2 } from "node:os";
19835
+ import { dirname as dirname12, join as join8, resolve as resolve9 } from "node:path";
19340
19836
  var windowsPrivateFiles2 = process.platform === "win32";
19341
19837
  var migrationNotices2 = /* @__PURE__ */ new Set();
19342
19838
  function ioCode2(detail) {
@@ -19349,8 +19845,32 @@ function ioCode2(detail) {
19349
19845
  return detail?.code ?? "ERR_PRIVATE_FILE";
19350
19846
  }
19351
19847
  var backend2;
19848
+ var PRIVATE_FILES_UNAVAILABLE_REASON2 = "native-addon-unavailable";
19849
+ function privateFilesUnavailable2(cause) {
19850
+ return Object.assign(new Error("Windows private-files native addon is unavailable", { cause }), {
19851
+ code: "ERR_PRIVATE_FILES_UNAVAILABLE",
19852
+ reason: PRIVATE_FILES_UNAVAILABLE_REASON2
19853
+ });
19854
+ }
19855
+ function isUnavailable2(api, error) {
19856
+ return error instanceof api.PrivateFilesUnavailableError || error?.code === "ERR_PRIVATE_FILES_UNAVAILABLE";
19857
+ }
19858
+ async function assertNativeAddonLoads2(api) {
19859
+ try {
19860
+ await api.verifyPrivatePath(join8(tmpdir2(), `.common-auth-private-files-probe-${randomUUID11()}`), "file");
19861
+ } catch (error) {
19862
+ if (isUnavailable2(api, error))
19863
+ throw privateFilesUnavailable2(error);
19864
+ }
19865
+ }
19352
19866
  function loadBackend2() {
19353
- backend2 ??= import("@cortexkit/private-files");
19867
+ backend2 ??= import("@cortexkit/private-files").then(async (api) => {
19868
+ if (windowsPrivateFiles2)
19869
+ await assertNativeAddonLoads2(api);
19870
+ return api;
19871
+ }, (cause) => {
19872
+ throw windowsPrivateFiles2 ? privateFilesUnavailable2(cause) : cause;
19873
+ });
19354
19874
  return backend2;
19355
19875
  }
19356
19876
  var PrivateFileError2 = class extends Error {
@@ -19367,7 +19887,7 @@ var PrivateFileError2 = class extends Error {
19367
19887
  orphanPath;
19368
19888
  constructor(path2, stage, cause) {
19369
19889
  const detail = cause;
19370
- super(`Private file refused at ${stage}: ${path2} (${detail?.reason ?? detail?.code ?? "io-error"}). Use a safe parent directory. Repair only a named secret file in safe ancestry whose owner the published policy trusts, without changing its owner or any existing directory. Previously exposed credentials may need rotation. Windows requires the private-files native prebuild and an ACL-persisting local filesystem such as NTFS.`, { cause });
19890
+ super(detail?.code === "ERR_PRIVATE_FILES_UNAVAILABLE" ? `Private file refused at ${stage}: ${path2} (${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}: ${path2} (${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 });
19371
19891
  this.path = path2;
19372
19892
  this.stage = stage;
19373
19893
  this.name = "PrivateFileError";
@@ -19959,7 +20479,7 @@ import {
19959
20479
  unlinkSync
19960
20480
  } from "node:fs";
19961
20481
  import { homedir as homedir2 } from "node:os";
19962
- import { join as join7 } from "node:path";
20482
+ import { join as join9 } from "node:path";
19963
20483
  import { env } from "node:process";
19964
20484
 
19965
20485
  // src/plugin/logging-utils.ts
@@ -20090,16 +20610,16 @@ var liveLogFilePaths = /* @__PURE__ */ new Set();
20090
20610
  function getConfigDir() {
20091
20611
  const platform = process.platform;
20092
20612
  if (platform === "win32") {
20093
- return join7(
20094
- env.APPDATA || join7(homedir2(), "AppData", "Roaming"),
20613
+ return join9(
20614
+ env.APPDATA || join9(homedir2(), "AppData", "Roaming"),
20095
20615
  "opencode"
20096
20616
  );
20097
20617
  }
20098
- const xdgConfig2 = env.XDG_CONFIG_HOME || join7(homedir2(), ".config");
20099
- return join7(xdgConfig2, "opencode");
20618
+ const xdgConfig2 = env.XDG_CONFIG_HOME || join9(homedir2(), ".config");
20619
+ return join9(xdgConfig2, "opencode");
20100
20620
  }
20101
20621
  function getLogsDir(customLogDir) {
20102
- const logsDir = customLogDir || join7(getConfigDir(), "antigravity-logs");
20622
+ const logsDir = customLogDir || join9(getConfigDir(), "antigravity-logs");
20103
20623
  try {
20104
20624
  mkdirSync(logsDir, { recursive: true, mode: 448 });
20105
20625
  } catch {
@@ -20110,9 +20630,9 @@ function createLogFilePath(customLogDir) {
20110
20630
  const logsDir = getLogsDir(customLogDir);
20111
20631
  cleanupOldLogs(logsDir, 25);
20112
20632
  const timestamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
20113
- let candidate = join7(logsDir, `antigravity-debug-${timestamp}.log`);
20633
+ let candidate = join9(logsDir, `antigravity-debug-${timestamp}.log`);
20114
20634
  for (let suffix = 2; liveLogFilePaths.has(candidate); suffix++) {
20115
- candidate = join7(logsDir, `antigravity-debug-${timestamp}-${suffix}.log`);
20635
+ candidate = join9(logsDir, `antigravity-debug-${timestamp}-${suffix}.log`);
20116
20636
  }
20117
20637
  return candidate;
20118
20638
  }
@@ -20120,7 +20640,7 @@ function cleanupOldLogs(logsDir, maxFiles) {
20120
20640
  try {
20121
20641
  const files = readdirSync(logsDir).filter(
20122
20642
  (file) => file.startsWith("antigravity-debug-") && file.endsWith(".log")
20123
- ).map((file) => join7(logsDir, file));
20643
+ ).map((file) => join9(logsDir, file));
20124
20644
  if (files.length <= maxFiles) {
20125
20645
  return;
20126
20646
  }
@@ -20595,7 +21115,7 @@ var GITIGNORE_ENTRIES = [
20595
21115
  "antigravity-logs/"
20596
21116
  ];
20597
21117
  async function ensureGitignore(configDir) {
20598
- const gitignorePath = join8(configDir, ".gitignore");
21118
+ const gitignorePath = join10(configDir, ".gitignore");
20599
21119
  try {
20600
21120
  let content;
20601
21121
  let existingLines = [];
@@ -20641,7 +21161,7 @@ async function ensureGitignore(configDir) {
20641
21161
  }
20642
21162
  }
20643
21163
  function ensureGitignoreSync(configDir) {
20644
- const gitignorePath = join8(configDir, ".gitignore");
21164
+ const gitignorePath = join10(configDir, ".gitignore");
20645
21165
  try {
20646
21166
  let content;
20647
21167
  let existingLines = [];
@@ -20680,8 +21200,8 @@ function ensureGitignoreSync(configDir) {
20680
21200
  }
20681
21201
  }
20682
21202
  function getLegacyWindowsConfigDir() {
20683
- return join8(
20684
- process.env.APPDATA || join8(homedir3(), "AppData", "Roaming"),
21203
+ return join10(
21204
+ process.env.APPDATA || join10(homedir3(), "AppData", "Roaming"),
20685
21205
  "opencode"
20686
21206
  );
20687
21207
  }
@@ -20689,15 +21209,15 @@ function getConfigDir2() {
20689
21209
  if (process.env.OPENCODE_CONFIG_DIR) {
20690
21210
  return process.env.OPENCODE_CONFIG_DIR;
20691
21211
  }
20692
- const xdgConfig2 = process.env.XDG_CONFIG_HOME || join8(homedir3(), ".config");
20693
- return join8(xdgConfig2, "opencode");
21212
+ const xdgConfig2 = process.env.XDG_CONFIG_HOME || join10(homedir3(), ".config");
21213
+ return join10(xdgConfig2, "opencode");
20694
21214
  }
20695
21215
  function migrateLegacyWindowsConfig() {
20696
21216
  if (process.platform !== "win32") {
20697
21217
  return false;
20698
21218
  }
20699
- const newPath = join8(getConfigDir2(), "antigravity-accounts.json");
20700
- const legacyPath = join8(
21219
+ const newPath = join10(getConfigDir2(), "antigravity-accounts.json");
21220
+ const legacyPath = join10(
20701
21221
  getLegacyWindowsConfigDir(),
20702
21222
  "antigravity-accounts.json"
20703
21223
  );
@@ -20732,11 +21252,11 @@ function migrateLegacyWindowsConfig() {
20732
21252
  }
20733
21253
  }
20734
21254
  function getStoragePathWithMigration() {
20735
- const newPath = join8(getConfigDir2(), "antigravity-accounts.json");
21255
+ const newPath = join10(getConfigDir2(), "antigravity-accounts.json");
20736
21256
  if (process.platform === "win32") {
20737
21257
  migrateLegacyWindowsConfig();
20738
21258
  if (!existsSync3(newPath)) {
20739
- const legacyPath = join8(
21259
+ const legacyPath = join10(
20740
21260
  getLegacyWindowsConfigDir(),
20741
21261
  "antigravity-accounts.json"
20742
21262
  );
@@ -21683,7 +22203,7 @@ async function startOAuthListener({
21683
22203
 
21684
22204
  // src/setup.ts
21685
22205
  import { lstat as lstat5, readFile as readFile10 } from "node:fs/promises";
21686
- import { join as join15, resolve as resolve13 } from "node:path";
22206
+ import { join as join17, resolve as resolve13 } from "node:path";
21687
22207
 
21688
22208
  // src/auth-method-labels.ts
21689
22209
  var OPENCODE2_POOL_AUTH_LABEL = "Google (antigravity-auth pool, browser)";
@@ -21929,7 +22449,7 @@ async function select2(terminal, items, options) {
21929
22449
  import { createHash as createHash9, randomBytes as randomBytes3, randomUUID as randomUUID14 } from "node:crypto";
21930
22450
  import { constants as fsConstants2 } from "node:fs";
21931
22451
  import { chmod as chmod3, mkdir as mkdir12, open as open10, readFile as readFile9, realpath as realpath4, rename as rename9, stat as stat7, unlink as unlink9 } from "node:fs/promises";
21932
- import { basename as basename4, dirname as dirname16, extname as extname2, isAbsolute as isAbsolute3, join as join10, resolve as resolve12 } from "node:path";
22452
+ import { basename as basename4, dirname as dirname16, extname as extname2, isAbsolute as isAbsolute3, join as join12, resolve as resolve12 } from "node:path";
21933
22453
  import { ClaustrumCredentialError as ClaustrumCredentialError5, ClaustrumClient as ClaustrumWireClient2, writeEnrollmentTokenFile as writeEnrollmentTokenFile2 } from "@cortexkit/claustrum-client";
21934
22454
 
21935
22455
  // src/common-auth-embedded/fs/lock-constants.js
@@ -21951,7 +22471,7 @@ var WRITER_LOCK_CONSTANTS2 = Object.freeze({
21951
22471
  // src/common-auth-embedded/fs/refresh-file-lock.js
21952
22472
  import { randomUUID as randomUUID13 } from "node:crypto";
21953
22473
  import { mkdir as mkdir11, open as open9, readFile as readFile8, rename as rename8, rm as rm5, stat as stat6 } from "node:fs/promises";
21954
- import { dirname as dirname15, join as join9 } from "node:path";
22474
+ import { dirname as dirname15, join as join11 } from "node:path";
21955
22475
 
21956
22476
  // src/common-auth-embedded/fs/with-lock.js
21957
22477
  function lockPathFor2(target, name) {
@@ -21986,7 +22506,7 @@ function acquireRefreshFileLock2(options) {
21986
22506
  }
21987
22507
  async function acquireRefreshFileLockWithClock2(options) {
21988
22508
  const lockPath = lockPathFor2(options.path, options.name);
21989
- const legacyOwnerPath = join9(lockPath, "owner.json");
22509
+ const legacyOwnerPath = join11(lockPath, "owner.json");
21990
22510
  const ownerId = randomUUID13();
21991
22511
  const now = options.now ?? Date.now;
21992
22512
  let renewTimer = null;
@@ -22029,7 +22549,7 @@ async function acquireRefreshFileLockWithClock2(options) {
22029
22549
  let terminalIOError;
22030
22550
  let renewalInFlight = null;
22031
22551
  const evictPath = `${lockPath}.evicting`;
22032
- const evictOwnerPath = join9(evictPath, "owner.json");
22552
+ const evictOwnerPath = join11(evictPath, "owner.json");
22033
22553
  const evictOwnerId = randomUUID13();
22034
22554
  const EVICT_TTL = 5e3;
22035
22555
  const MAX_STEAL_ATTEMPTS = 8;
@@ -22600,7 +23120,13 @@ var ENROLLMENT_SCHEMA2 = 1;
22600
23120
  var ENROLLMENT_FILE_MAX_BYTES2 = 16 * 1024;
22601
23121
  var ENROLLMENT_LOCK_TTL_MS2 = 3e4;
22602
23122
  var TOKEN_RE2 = /^[0-9a-f]{64}$/;
23123
+ var UNSUPPORTED_ENROLLMENT_CODE2 = "unknown_method";
22603
23124
  var TERMINAL_ENROLLMENT_CODES2 = /* @__PURE__ */ new Set([
23125
+ // The daemon's answer to an operation it does not implement: a vault built
23126
+ // before the enrollment ceremony. It arrives as a transport Error frame with
23127
+ // no class, which claustrum-client before 0.13.0 labels transient/retry, but
23128
+ // asking again can never succeed.
23129
+ UNSUPPORTED_ENROLLMENT_CODE2,
22604
23130
  "invalid_params",
22605
23131
  "pending_exists",
22606
23132
  "not_found",
@@ -22630,7 +23156,7 @@ function getClaustrumEnrollmentPaths2(tokenPath) {
22630
23156
  const extension = extname2(tokenPath) || ".json";
22631
23157
  const stem = basename4(tokenPath, extname2(tokenPath));
22632
23158
  return {
22633
- statePath: join10(dirname16(tokenPath), `${stem}-state${extension}`),
23159
+ statePath: join12(dirname16(tokenPath), `${stem}-state${extension}`),
22634
23160
  tokenPath
22635
23161
  };
22636
23162
  }
@@ -22638,7 +23164,7 @@ function hostEnrollmentPaths2(input) {
22638
23164
  const override = input.override?.trim();
22639
23165
  if (override && !isAbsolute3(override) && !input.cwd)
22640
23166
  throw new ClaustrumConsumerError2("invalid-state", "A relative Claustrum enrollment override needs a base directory");
22641
- const tokenPath = override ? isAbsolute3(override) ? override : resolve12(input.cwd, override) : join10(input.stateDir, `${input.host}-enrollment.json`);
23167
+ const tokenPath = override ? isAbsolute3(override) ? override : resolve12(input.cwd, override) : join12(input.stateDir, `${input.host}-enrollment.json`);
22642
23168
  return getClaustrumEnrollmentPaths2(tokenPath);
22643
23169
  }
22644
23170
  function isRecord9(value) {
@@ -22871,7 +23397,7 @@ async function writeStateAtomic2(path2, state, ancestorOptions = {}) {
22871
23397
  }
22872
23398
  if (windowsPrivateFiles2)
22873
23399
  return writePrivateAtomic2(path2, bytes);
22874
- const temporary = join10(parent, `.${basename4(path2)}.${process.pid}.${randomUUID14()}.tmp`);
23400
+ const temporary = join12(parent, `.${basename4(path2)}.${process.pid}.${randomUUID14()}.tmp`);
22875
23401
  let descriptor;
22876
23402
  let created = false;
22877
23403
  try {
@@ -23095,6 +23621,18 @@ var ClaustrumEnrollmentManager2 = class {
23095
23621
  retryCode: refusal3.code
23096
23622
  };
23097
23623
  }
23624
+ if (refusal3.code === UNSUPPORTED_ENROLLMENT_CODE2) {
23625
+ await lock.assertOwned();
23626
+ await unlink9(this.#paths.statePath).catch((cause) => {
23627
+ if (cause.code !== "ENOENT")
23628
+ throw cause;
23629
+ });
23630
+ return {
23631
+ state: "unavailable",
23632
+ proposedName: state.proposedName,
23633
+ code: refusal3.code
23634
+ };
23635
+ }
23098
23636
  return this.#block(state, refusal3.code);
23099
23637
  }
23100
23638
  }
@@ -23372,8 +23910,8 @@ function recordSetupEnrollment(failure, enrollment) {
23372
23910
  // src/common-auth-embedded/setup/detect.js
23373
23911
  import { accessSync, constants as constants3, existsSync as existsSync5, readFileSync as readFileSync3, realpathSync, statSync as statSync5 } from "node:fs";
23374
23912
  import { mkdtemp, rm as rm6 } from "node:fs/promises";
23375
- import { tmpdir } from "node:os";
23376
- import { join as join11 } from "node:path";
23913
+ import { tmpdir as tmpdir3 } from "node:os";
23914
+ import { join as join13 } from "node:path";
23377
23915
  import { parse } from "jsonc-parser";
23378
23916
 
23379
23917
  // src/common-auth-embedded/setup/paths.js
@@ -23544,7 +24082,7 @@ async function detectHosts(plugin, io = {}) {
23544
24082
  return null;
23545
24083
  let root;
23546
24084
  try {
23547
- root = await mkdtemp(join11(tmpdir(), "common-auth-setup-version-"));
24085
+ root = await mkdtemp(join13(tmpdir3(), "common-auth-setup-version-"));
23548
24086
  const probeEnv = {
23549
24087
  ...env3,
23550
24088
  HOME: root,
@@ -23613,6 +24151,8 @@ import { writeEnrollmentTokenFile as writeEnrollmentTokenFile3 } from "@cortexki
23613
24151
  var WINDOWS_CIM_TIMEOUT_MS = 45e3;
23614
24152
  var HOSTS = /* @__PURE__ */ new Set(["opencode", "litecode", "opencode2", "pi"]);
23615
24153
  var RUNTIMES = /* @__PURE__ */ new Set(["node", "bun"]);
24154
+ var WINDOWS_FENCE_FILTER = [...HOSTS, ...RUNTIMES].map((name) => `Name LIKE '${name}%'`).join(" OR ");
24155
+ 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 }`;
23616
24156
  var PI_SCRIPT_PATTERN = /(?:^|[/\\])pi-coding-agent[/\\]dist[/\\](?:(?:bundle|bun)[/\\])?cli\.m?js$/i;
23617
24157
  function commandArguments(command) {
23618
24158
  return [...command.matchAll(/"([^"]*)"|(\S+)/g)].map((match) => match[1] ?? match[2] ?? "");
@@ -23752,6 +24292,29 @@ async function listSetupProcesses(runner = defaultCommandRunner, options = {}) {
23752
24292
  }
23753
24293
  };
23754
24294
  try {
24295
+ if (windows && options.hostImagesOnly) {
24296
+ const details = await inspect("CIM", "powershell.exe", ["-NoProfile", "-NonInteractive", "-Command", WINDOWS_FENCE_QUERY], WINDOWS_CIM_TIMEOUT_MS);
24297
+ if (details.exitCode !== 0)
24298
+ throw new ProcessInspectionError(inspection);
24299
+ const value = JSON.parse(details.stdout);
24300
+ if (!value || typeof value !== "object" || !("complete" in value) || value.complete !== true || !("processes" in value))
24301
+ throw new ProcessInspectionError(inspection);
24302
+ const listed = value.processes;
24303
+ const rows = listed === null ? [] : Array.isArray(listed) ? listed : [listed];
24304
+ const processes2 = [];
24305
+ for (const row of rows) {
24306
+ 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))
24307
+ throw new ProcessInspectionError(inspection);
24308
+ const pid = row.ProcessId;
24309
+ if (!/^(?:node|bun)\.exe$/i.test(row.Name))
24310
+ processes2.push({ pid, command: row.Name });
24311
+ else if (typeof row.CommandLine === "string")
24312
+ processes2.push({ pid, command: row.CommandLine });
24313
+ else if (pid !== selfPid)
24314
+ throw new ProcessInspectionError(inspection);
24315
+ }
24316
+ return processes2;
24317
+ }
23755
24318
  const result = await inspect(windows ? "tasklist" : "ps", windows ? "tasklist.exe" : "ps", windows ? ["/fo", "csv", "/nh"] : ["-eo", "pid,command"]);
23756
24319
  if (result.exitCode !== 0)
23757
24320
  throw new ProcessInspectionError(inspection);
@@ -23821,7 +24384,11 @@ function createProcessFence(runner = defaultCommandRunner, options = {}) {
23821
24384
  const isHost = (entry) => entry.pid !== selfPid && hostName(entry.command) !== null;
23822
24385
  return {
23823
24386
  async listRunningHosts(env3) {
23824
- return (await listSetupProcesses(runner, { ...options, env: env3 })).filter(isHost);
24387
+ return (await listSetupProcesses(runner, {
24388
+ ...options,
24389
+ env: env3,
24390
+ hostImagesOnly: true
24391
+ })).filter(isHost);
23825
24392
  },
23826
24393
  async previewRunningHosts(env3) {
23827
24394
  const processes = await listSetupProcesses(runner, {
@@ -23845,8 +24412,27 @@ async function assertHostsStopped(fence, env3) {
23845
24412
 
23846
24413
  // src/common-auth-embedded/setup/enroll.js
23847
24414
  var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
24415
+ 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.';
24416
+ var ENROLLMENT_WAIT_MS = 3e5;
24417
+ var APPROVAL_POLL_MS = 1e3;
24418
+ var PROPOSE_BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];
24419
+ function safeCode(code2) {
24420
+ return code2 && /^[a-z][a-z0-9_]{0,63}$/.test(code2) ? code2 : "unknown";
24421
+ }
23848
24422
  var HostNotEnrolledError = class extends Error {
24423
+ reason;
24424
+ lastErrorCode;
24425
+ constructor(message, details) {
24426
+ super(message);
24427
+ this.name = "HostNotEnrolledError";
24428
+ this.reason = details.reason;
24429
+ if (details.lastErrorCode !== void 0)
24430
+ this.lastErrorCode = safeCode(details.lastErrorCode);
24431
+ }
23849
24432
  };
24433
+ function approveCommand(requestId, name) {
24434
+ return `ck auth enroll approve --request-id ${requestId} --name ${name}`;
24435
+ }
23850
24436
  async function connectSetupHost(plugin, host, io, terminal, fence) {
23851
24437
  const { name, paths: input } = plugin.vault.hosts[host];
23852
24438
  const paths = hostEnrollmentPaths2(input);
@@ -23855,54 +24441,94 @@ async function connectSetupHost(plugin, host, io, terminal, fence) {
23855
24441
  connectionFile: plugin.vault.connectionFile,
23856
24442
  handshakeTimeoutMs: 2e3
23857
24443
  }).catch(() => {
23858
- throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.");
24444
+ throw new HostNotEnrolledError("Claustrum connection failed; start ck and rerun setup.", { reason: "connection-failed" });
23859
24445
  });
24446
+ const now = io.now ?? (() => performance.now());
24447
+ const wait2 = io.wait ?? delay;
23860
24448
  try {
23861
24449
  const manager = new ClaustrumEnrollmentManager2({
23862
24450
  proposedName: name,
23863
24451
  paths,
23864
- client: {
23865
- enrollPropose: async (input2) => {
23866
- await fence();
23867
- return client.enrollPropose(input2);
23868
- },
23869
- enrollPoll: async (input2) => {
23870
- await fence();
23871
- return client.enrollPoll(input2);
23872
- }
23873
- },
24452
+ // Each tick of the wait below checks the fence once, just before
24453
+ // reconcile proposes or polls. Checking again inside every vault call
24454
+ // doubled the process listings per tick, and on Windows each listing
24455
+ // starts PowerShell.
24456
+ client,
23874
24457
  writeTokenFile: async (path2, file) => {
23875
24458
  await fence();
23876
24459
  await writeEnrollmentTokenFile3(path2, file);
23877
24460
  }
23878
24461
  });
24462
+ printLine2(terminal, `Asking the vault to connect ${name}\u2026`);
24463
+ const deadline = now() + ENROLLMENT_WAIT_MS;
23879
24464
  let printedRequest;
23880
- for (let tick = 0; tick < 300; tick++) {
24465
+ let lastCode;
24466
+ let reportedCode;
24467
+ let failedProposals = 0;
24468
+ for (; ; ) {
23881
24469
  await fence();
23882
24470
  const status = await manager.reconcile();
23883
24471
  if (status.state === "approved") {
23884
24472
  printLine2(terminal, `Connected ${host} to Claustrum.`);
23885
24473
  return;
23886
24474
  }
24475
+ if (status.state === "unavailable" && status.code === UNSUPPORTED_ENROLLMENT_CODE2)
24476
+ throw new HostNotEnrolledError(UNSUPPORTED_VAULT_MESSAGE, {
24477
+ reason: "unsupported-vault",
24478
+ lastErrorCode: status.code
24479
+ });
23887
24480
  if (status.state !== "pending" && status.state !== "busy")
23888
- throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.");
23889
- if (status.state === "pending" && status.requestId && status.requestId !== printedRequest) {
23890
- if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
23891
- throw new HostNotEnrolledError("Invalid enrollment request id.");
23892
- printedRequest = status.requestId;
23893
- printLine2(terminal, "Waiting for approval. In another terminal, run:");
23894
- printLine2(terminal, ` ck auth enroll approve --request-id ${status.requestId} --name ${name}`);
23895
- printLine2(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
23896
- }
23897
- await (io.wait ?? delay)(1e3);
23898
- }
23899
- throw new HostNotEnrolledError("Claustrum approval is still pending; approve with ck and rerun setup.");
24481
+ throw new HostNotEnrolledError("Claustrum enrollment refused; inspect its status with ck before rerunning setup.", {
24482
+ reason: "refused",
24483
+ ..."code" in status && { lastErrorCode: status.code }
24484
+ });
24485
+ let pause = APPROVAL_POLL_MS;
24486
+ if (status.state === "busy")
24487
+ lastCode = "busy";
24488
+ else if (status.retryCode)
24489
+ lastCode = status.retryCode;
24490
+ if (status.state === "pending" && status.requestId) {
24491
+ failedProposals = 0;
24492
+ if (status.requestId !== printedRequest) {
24493
+ if (!/^[a-zA-Z0-9_-]+$/.test(status.requestId))
24494
+ throw new HostNotEnrolledError("Invalid enrollment request id.", {
24495
+ reason: "invalid-request"
24496
+ });
24497
+ printedRequest = status.requestId;
24498
+ printLine2(terminal, "Waiting for approval. In another terminal, run:");
24499
+ printLine2(terminal, ` ${approveCommand(status.requestId, name)}`);
24500
+ printLine2(terminal, `Enrollment files: ${paths.statePath}, ${paths.tokenPath}`);
24501
+ }
24502
+ } else if (status.state === "pending" && status.retryCode) {
24503
+ pause = PROPOSE_BACKOFF_MS[Math.min(failedProposals, PROPOSE_BACKOFF_MS.length - 1)] ?? APPROVAL_POLL_MS;
24504
+ failedProposals++;
24505
+ const code3 = safeCode(status.retryCode);
24506
+ if (code3 !== reportedCode) {
24507
+ reportedCode = code3;
24508
+ printLine2(terminal, `The vault has not created the request yet (${code3}); retrying.`);
24509
+ }
24510
+ }
24511
+ const remaining = deadline - now();
24512
+ if (remaining <= 0)
24513
+ break;
24514
+ await wait2(Math.min(pause, remaining));
24515
+ }
24516
+ if (printedRequest)
24517
+ throw new HostNotEnrolledError(`Claustrum approval is still pending. In another terminal, run: ${approveCommand(printedRequest, name)} and then rerun setup.`, {
24518
+ reason: "approval-pending",
24519
+ ...lastCode !== void 0 && { lastErrorCode: lastCode }
24520
+ });
24521
+ const code2 = safeCode(lastCode);
24522
+ 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 });
23900
24523
  } catch (error) {
23901
- if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError)
24524
+ if (error instanceof ProcessFenceViolationError || error instanceof ProcessInspectionError || // Built above from fixed text and vetted values only.
24525
+ error instanceof HostNotEnrolledError)
23902
24526
  throw error;
23903
- if (error instanceof HostNotEnrolledError)
23904
- throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE);
23905
- throw new Error(ENROLLMENT_INCOMPLETE_MESSAGE);
24527
+ const code2 = error?.code;
24528
+ throw new HostNotEnrolledError(ENROLLMENT_INCOMPLETE_MESSAGE, {
24529
+ reason: "incomplete",
24530
+ ...typeof code2 === "string" && { lastErrorCode: code2 }
24531
+ });
23906
24532
  } finally {
23907
24533
  client.close();
23908
24534
  }
@@ -23940,7 +24566,7 @@ import { applyEdits, createScanner, findNodeAtLocation, modify, parse as parse2,
23940
24566
  // src/common-auth-embedded/setup/config-write.js
23941
24567
  import { randomUUID as randomUUID15 } from "node:crypto";
23942
24568
  import { mkdir as mkdir13, open as open11, rename as rename10, stat as stat9, unlink as unlink10 } from "node:fs/promises";
23943
- import { basename as basename5, dirname as dirname17, join as join12 } from "node:path";
24569
+ import { basename as basename5, dirname as dirname17, join as join14 } from "node:path";
23944
24570
  import { setTimeout as delay2 } from "node:timers/promises";
23945
24571
  async function writeHostConfigAtomic(file, content, options = {}) {
23946
24572
  const windows = (options.platform ?? process.platform) === "win32";
@@ -23955,7 +24581,7 @@ async function writeHostConfigAtomic(file, content, options = {}) {
23955
24581
  throw error;
23956
24582
  }
23957
24583
  }
23958
- const stage = join12(parent, `.${basename5(file)}.${(options.stageName ?? randomUUID15)()}.tmp`);
24584
+ const stage = join14(parent, `.${basename5(file)}.${(options.stageName ?? randomUUID15)()}.tmp`);
23959
24585
  let created = false;
23960
24586
  try {
23961
24587
  const handle = await open11(stage, "wx", mode ?? 438);
@@ -24321,28 +24947,28 @@ ${write.content}`);
24321
24947
 
24322
24948
  // src/plugin/vault-activation.ts
24323
24949
  import { homedir as homedir5 } from "node:os";
24324
- import { join as join13 } from "node:path";
24950
+ import { join as join15 } from "node:path";
24325
24951
  function nativeOpenCodeAuthPath(env3 = process.env, home = homedir5()) {
24326
- return join13(
24327
- env3.XDG_DATA_HOME || join13(home, ".local", "share"),
24952
+ return join15(
24953
+ env3.XDG_DATA_HOME || join15(home, ".local", "share"),
24328
24954
  "opencode",
24329
24955
  "auth.json"
24330
24956
  );
24331
24957
  }
24332
24958
 
24333
24959
  // src/plugin/vault-custody.ts
24334
- import { dirname as dirname18, join as join14 } from "node:path";
24960
+ import { dirname as dirname18, join as join16 } from "node:path";
24335
24961
  var OPENCODE_VAULT_PROVIDER = "google";
24336
24962
  var OPENCODE_VAULT_HOST = "opencode";
24337
24963
  var OPENCODE_VAULT_ENROLLMENT_NAME = getAntigravityVaultEnrollmentName(OPENCODE_VAULT_HOST);
24338
24964
  var OPENCODE_VAULT_DIR_NAME = "antigravity-auth-vault";
24339
24965
  function openCodeVaultPaths(accountFile) {
24340
- const dir = join14(dirname18(accountFile), OPENCODE_VAULT_DIR_NAME);
24966
+ const dir = join16(dirname18(accountFile), OPENCODE_VAULT_DIR_NAME);
24341
24967
  return {
24342
24968
  dir,
24343
- modeFile: join14(dir, "opencode-mode.json"),
24344
- rosterFile: join14(dir, "opencode-roster.json"),
24345
- stateFile: join14(dir, "opencode-state.json")
24969
+ modeFile: join16(dir, "opencode-mode.json"),
24970
+ rosterFile: join16(dir, "opencode-roster.json"),
24971
+ stateFile: join16(dir, "opencode-state.json")
24346
24972
  };
24347
24973
  }
24348
24974
  var LOCAL_MODE = Object.freeze({
@@ -24358,7 +24984,7 @@ var OPENCODE_VAULT_GRANT_COMMAND = `ck auth grant --principal enrolled:${OPENCOD
24358
24984
  // src/setup.ts
24359
24985
  var PI_PLACEHOLDER_KEY = "antigravity-vault-custody";
24360
24986
  function nativeAuthPath(host, context) {
24361
- return host === "opencode" ? nativeOpenCodeAuthPath() : join15(context.piAgentDir, "auth.json");
24987
+ return host === "opencode" ? nativeOpenCodeAuthPath() : join17(context.piAgentDir, "auth.json");
24362
24988
  }
24363
24989
  function provider(host) {
24364
24990
  return host === "opencode" ? OPENCODE_VAULT_PROVIDER : ANTIGRAVITY_PROVIDER_ID;
@@ -24479,7 +25105,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
24479
25105
  const { openPiSlot: openPiSlot2 } = await loadCommonAuthPiSlot();
24480
25106
  if ((await openPiSlot2({
24481
25107
  authPath: nativeAuthPath(host, context),
24482
- stashPath: join15(piDir, "google-login-stash.json"),
25108
+ stashPath: join17(piDir, "google-login-stash.json"),
24483
25109
  provider: ANTIGRAVITY_PROVIDER_ID,
24484
25110
  placeholderKey: PI_PLACEHOLDER_KEY
24485
25111
  }).inspect()).slot === "placeholder")
@@ -24516,7 +25142,7 @@ async function createSetupPlugin(deps, migrateOpenCode, forceLogin = false) {
24516
25142
  const { openPiSlot: openPiSlot2 } = await loadCommonAuthPiSlot();
24517
25143
  const inspection = await openPiSlot2({
24518
25144
  authPath: nativeAuthPath("pi", context),
24519
- stashPath: join15(piDir, "google-login-stash.json"),
25145
+ stashPath: join17(piDir, "google-login-stash.json"),
24520
25146
  provider: ANTIGRAVITY_PROVIDER_ID,
24521
25147
  placeholderKey: PI_PLACEHOLDER_KEY
24522
25148
  }).inspect();
@@ -24635,7 +25261,7 @@ Setup has not completed the OpenCode 2 native Google connection.
24635
25261
  await assertSetupHostsStopped();
24636
25262
  await openPiSlot2({
24637
25263
  authPath: nativeAuthPath(host, context),
24638
- stashPath: join15(piDir, "google-login-stash.json"),
25264
+ stashPath: join17(piDir, "google-login-stash.json"),
24639
25265
  provider: ANTIGRAVITY_PROVIDER_ID,
24640
25266
  placeholderKey: PI_PLACEHOLDER_KEY
24641
25267
  }).enterVault();