@cortexkit/opencode-antigravity-auth 3.0.11 → 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 (80) hide show
  1. package/dist/cli.js +1607 -1189
  2. package/dist/cli.js.map +4 -4
  3. package/dist/cli.meta.json +164 -102
  4. package/dist/index.js +1752 -1333
  5. package/dist/index.js.map +4 -4
  6. package/dist/index.meta.json +167 -105
  7. package/dist/server.js +1752 -1333
  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/errors.d.ts +1 -1
  13. package/dist/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  14. package/dist/src/common-auth-embedded/claustrum/index.js +1 -1
  15. package/dist/src/common-auth-embedded/claustrum/quota-writer.js +4 -54
  16. package/dist/src/common-auth-embedded/claustrum/roster.d.ts +31 -0
  17. package/dist/src/common-auth-embedded/claustrum/roster.js +72 -0
  18. package/dist/src/common-auth-embedded/commands/builtins.d.ts +37 -0
  19. package/dist/src/common-auth-embedded/commands/builtins.js +95 -13
  20. package/dist/src/common-auth-embedded/commands/index.d.ts +1 -1
  21. package/dist/src/common-auth-embedded/opencode2/install.d.ts +3 -2
  22. package/dist/src/common-auth-embedded/opencode2/install.js +184 -63
  23. package/dist/src/common-auth-embedded/opencode2/types.d.ts +43 -6
  24. package/dist/src/common-auth-embedded/quota/pending.js +48 -0
  25. package/dist/src/common-auth-embedded/setup/enroll.d.ts +1 -1
  26. package/dist/src/common-auth-embedded/setup/enroll.js +1 -1
  27. package/dist/src/common-auth-embedded/source-output.json +89 -73
  28. package/dist/src/common-auth-embedded/store/attribution.d.ts +5 -0
  29. package/dist/src/common-auth-embedded/store/attribution.js +39 -25
  30. package/dist/src/common-auth-embedded/store/pool.d.ts +17 -0
  31. package/dist/src/common-auth-embedded/store/pool.js +18 -3
  32. package/dist/src/common-auth-embedded/store/pull.js +3 -1
  33. package/dist/src/common-auth-embedded/store/quota-writer.js +298 -0
  34. package/dist/src/common-auth-embedded/store/runtime.d.ts +2 -0
  35. package/dist/src/plugin/shared/request-services.d.ts.map +1 -1
  36. package/dist/src/plugin/shared/request-services.js +1 -0
  37. package/dist/src/plugin/shared/request-services.js.map +1 -1
  38. package/dist/src/plugin/vault-custody.js +2 -2
  39. package/dist/src/plugin/vault-custody.js.map +1 -1
  40. package/dist/tui-build-map.json +1 -1
  41. package/dist/tui-ga-build-map.json +1 -1
  42. package/dist/types/src/common-auth-embedded/claustrum/consumer.d.ts +7 -1
  43. package/dist/types/src/common-auth-embedded/claustrum/errors.d.ts +1 -1
  44. package/dist/types/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  45. package/dist/types/src/common-auth-embedded/claustrum/roster.d.ts +31 -0
  46. package/dist/types/src/common-auth-embedded/commands/builtins.d.ts +37 -0
  47. package/dist/types/src/common-auth-embedded/commands/index.d.ts +1 -1
  48. package/dist/types/src/common-auth-embedded/opencode2/install.d.ts +3 -2
  49. package/dist/types/src/common-auth-embedded/opencode2/types.d.ts +43 -6
  50. package/dist/types/src/common-auth-embedded/setup/enroll.d.ts +1 -1
  51. package/dist/types/src/common-auth-embedded/store/attribution.d.ts +5 -0
  52. package/dist/types/src/common-auth-embedded/store/pool.d.ts +17 -0
  53. package/dist/types/src/common-auth-embedded/store/runtime.d.ts +2 -0
  54. package/dist/types/src/plugin/shared/request-services.d.ts.map +1 -1
  55. package/package.json +2 -2
  56. package/src/common-auth-embedded/claustrum/consumer.d.ts +7 -1
  57. package/src/common-auth-embedded/claustrum/consumer.js +17 -2
  58. package/src/common-auth-embedded/claustrum/errors.d.ts +1 -1
  59. package/src/common-auth-embedded/claustrum/index.d.ts +1 -1
  60. package/src/common-auth-embedded/claustrum/index.js +1 -1
  61. package/src/common-auth-embedded/claustrum/quota-writer.js +4 -54
  62. package/src/common-auth-embedded/claustrum/roster.d.ts +31 -0
  63. package/src/common-auth-embedded/claustrum/roster.js +72 -0
  64. package/src/common-auth-embedded/commands/builtins.d.ts +37 -0
  65. package/src/common-auth-embedded/commands/builtins.js +95 -13
  66. package/src/common-auth-embedded/commands/index.d.ts +1 -1
  67. package/src/common-auth-embedded/opencode2/install.d.ts +3 -2
  68. package/src/common-auth-embedded/opencode2/install.js +184 -63
  69. package/src/common-auth-embedded/opencode2/types.d.ts +43 -6
  70. package/src/common-auth-embedded/quota/pending.js +48 -0
  71. package/src/common-auth-embedded/setup/enroll.d.ts +1 -1
  72. package/src/common-auth-embedded/setup/enroll.js +1 -1
  73. package/src/common-auth-embedded/source-output.json +89 -73
  74. package/src/common-auth-embedded/store/attribution.d.ts +5 -0
  75. package/src/common-auth-embedded/store/attribution.js +39 -25
  76. package/src/common-auth-embedded/store/pool.d.ts +17 -0
  77. package/src/common-auth-embedded/store/pool.js +18 -3
  78. package/src/common-auth-embedded/store/pull.js +3 -1
  79. package/src/common-auth-embedded/store/quota-writer.js +298 -0
  80. package/src/common-auth-embedded/store/runtime.d.ts +2 -0
package/dist/cli.js CHANGED
@@ -3197,13 +3197,40 @@ var init_runtime = __esm({
3197
3197
  });
3198
3198
 
3199
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
+ }
3200
3228
  async function recordQuota(rt, id, attribution, observation) {
3201
3229
  const { ctx } = rt;
3202
3230
  const locks = new LockStack(ctx.lockDefaults, ctx.lockEnv);
3203
3231
  const progress = { writes: 0 };
3204
3232
  try {
3205
- if (!isCredentialEpoch(attribution?.credentialEpoch))
3206
- throw refusal2("pull", id, "invalid-input", "the credential epoch the reading was issued for must be a positive safe integer");
3233
+ assertQuotaEpoch(id, attribution);
3207
3234
  await withTransaction(
3208
3235
  ctx,
3209
3236
  locks,
@@ -3212,26 +3239,11 @@ async function recordQuota(rt, id, attribution, observation) {
3212
3239
  async (tx) => {
3213
3240
  tx.assertNotStaged(id);
3214
3241
  const row = tx.row(id);
3215
- if (!row)
3216
- throw unknownRow("pull", id);
3217
- if (row.invalid)
3218
- throw refusal2("pull", id, "invalid-row", `row ${id} is invalid`);
3219
- if (!row.credential)
3220
- throw refusal2("pull", id, "no-credential", `row ${id} holds no credential`);
3221
- requireBound("pull", row);
3242
+ assertQuotaRow(id, attribution, row);
3222
3243
  const entry = tx.entry(id);
3223
- if (row.torn || !entry || entry.credentialEpoch !== attribution.credentialEpoch || row.identity !== attribution.identity)
3224
- throw new PoolOperationError({
3225
- operation: "pull",
3226
- rowId: id,
3227
- phase: "pull",
3228
- retryable: true,
3229
- kind: "attribution",
3230
- message: `quota for ${id} was issued for a credential the row no longer holds`
3231
- });
3232
- const merged = ctx.codec.merge(entry.quota, observation);
3233
- if (!ctx.codec.validate(merged))
3234
- 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);
3235
3247
  tx.setEntry(id, { ...entry, quota: merged, needsFirstReading: false });
3236
3248
  await tx.commitConfig();
3237
3249
  },
@@ -4641,7 +4653,8 @@ var init_pull = __esm({
4641
4653
  cause
4642
4654
  });
4643
4655
  }
4644
- await recordQuota(rt, id, {
4656
+ const publish = rt.publishQuota ?? ((rowId2, attribution, value) => recordQuota(rt, rowId2, attribution, value));
4657
+ await publish(id, {
4645
4658
  credentialEpoch: request.credentialEpoch,
4646
4659
  ...request.identity !== void 0 ? { identity: request.identity } : {}
4647
4660
  }, observation);
@@ -4671,234 +4684,923 @@ var init_pull = __esm({
4671
4684
  }
4672
4685
  });
4673
4686
 
4674
- // ../core/dist/common-auth-embedded/store/refresh.js
4675
- import { randomUUID as randomUUID9 } from "node:crypto";
4676
- function requireRefreshable(id, row) {
4677
- assertNotReserved("refresh", id, row?.staged);
4678
- if (!row)
4679
- throw refusal2("refresh", id, "unknown-row", `no row ${id} in the pool`);
4680
- if (row.invalid)
4681
- throw refusal2("refresh", id, "invalid-row", `row ${id} is invalid`);
4682
- if (row.type !== "oauth" || row.credential?.type !== "oauth")
4683
- throw refusal2("refresh", id, "no-credential", `row ${id} holds no OAuth credential`);
4684
- if (!row.enabled)
4685
- throw refusal2("refresh", id, "row-disabled", `row ${id} is disabled`);
4686
- return row;
4687
- }
4688
- function stampAhead(id) {
4689
- 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);
4690
- }
4691
- async function refreshRow(rt, id, provider2, options = {}) {
4692
- assertNotInsideHook("refresh");
4693
- const { ctx } = rt;
4694
- return runOperation(ctx, "refresh", id, options.onFailure, async (locks, progress) => {
4695
- const { row: seen } = await readRow(rt, "refresh", id);
4696
- requireRefreshable(id, seen);
4697
- const early = await options.refuse?.(seen);
4698
- if (early !== void 0)
4699
- return { status: "refused", rowId: id, reason: early };
4700
- let key = rowLockKey(seen);
4701
- let captured;
4702
- for (let attempt = 0; ; attempt++) {
4703
- await locks.acquire(rowLockSpec(rt, { id, identity: key === id ? void 0 : key }));
4704
- await locks.acquire(options.providerLock ?? rt.providerLock);
4705
- for (const extra of options.extraLocks ?? [])
4706
- await locks.acquire(extra);
4707
- const captureProgress = { writes: 0 };
4708
- const read = await withTransaction(ctx, locks, captureProgress, { operation: "refresh", rowId: id }, async (tx) => {
4709
- let row = requireRefreshable(id, tx.row(id));
4710
- requireBound("refresh", row);
4711
- if (!row.hasEntry) {
4712
- tx.setEntry(id, { credentialEpoch: 1, needsFirstReading: true });
4713
- await tx.commitConfig();
4714
- row = requireRefreshable(id, tx.row(id));
4715
- }
4716
- if (rowLockKey(row) !== key)
4717
- return { keyNow: rowLockKey(row) };
4718
- const reason = await options.refuse?.(row);
4719
- if (reason !== void 0)
4720
- return { refused: reason };
4721
- return {
4722
- row,
4723
- credential: row.credential,
4724
- credentialEpoch: row.credentialEpoch,
4725
- identity: row.identity
4726
- };
4727
- });
4728
- if ("refused" in read)
4729
- return { status: "refused", rowId: id, reason: read.refused };
4730
- if ("keyNow" in read) {
4731
- await locks.releaseAll();
4732
- if (attempt >= 1)
4733
- throw refusal2("refresh", id, "row-key-changed", `row ${id}'s wire identity changed twice while its lock was held`, true);
4734
- key = read.keyNow;
4735
- continue;
4736
- }
4737
- captured = read;
4738
- break;
4739
- }
4740
- if (rotationStampUntrusted(captured.credential.lastRefreshedAt, ctx.now()))
4741
- throw stampAhead(id);
4742
- await ctx.hold?.("refresh-before-provider", id);
4743
- await locks.assertAll();
4744
- let result;
4745
- try {
4746
- result = await provider2(captured.credential, captured.row);
4747
- } catch (cause) {
4748
- throw new PoolOperationError({
4749
- operation: "refresh",
4750
- rowId: id,
4751
- phase: "before-first-write",
4752
- retryable: true,
4753
- kind: "provider",
4754
- message: "the provider refresh failed",
4755
- cause
4756
- });
4757
- }
4758
- if (typeof result?.refresh !== "string" || !result.refresh.trim())
4759
- throw refusal2("refresh", id, "provider", "the provider returned no refresh token", true);
4760
- const incoming = result.providerState === void 0 ? void 0 : acceptProviderState(ctx.providerState, "refresh", id, result.providerState, "the provider state the provider returned");
4761
- const commit = await withTransaction(ctx, locks, progress, { operation: "refresh", rowId: id }, async (tx) => {
4762
- const current = tx.row(id);
4763
- const entry = tx.entry(id);
4764
- if (!current || current.invalid || !entry || entry.credentialEpoch !== captured.credentialEpoch || current.identity !== captured.identity)
4765
- throw new PoolOperationError({
4766
- operation: "refresh",
4767
- rowId: id,
4768
- phase: "before-first-write",
4769
- retryable: true,
4770
- kind: "attribution",
4771
- message: `row ${id} changed credential while its refresh was in flight; the rotation is discarded`
4772
- });
4773
- requireBound("refresh", current);
4774
- const reason = await options.refuse?.(current);
4775
- if (reason !== void 0)
4776
- return { refused: reason };
4777
- const now = ctx.now();
4778
- const prior = current.credential?.type === "oauth" ? current.credential.lastRefreshedAt : void 0;
4779
- if (rotationStampUntrusted(prior, now))
4780
- throw stampAhead(id);
4781
- const credential = {
4782
- type: "oauth",
4783
- access: result.access,
4784
- refresh: result.refresh,
4785
- expires: result.expires
4786
- };
4787
- const contradiction = current.identity !== void 0 && result.identity !== void 0 && current.identity !== result.identity ? {
4788
- expectedIdentity: current.identity,
4789
- returnedIdentity: result.identity
4790
- } : void 0;
4791
- const transition = contradiction ? {
4792
- mark: randomUUID9(),
4793
- enabled: false,
4794
- reason: `${IDENTITY_CONTRADICTED_REASON_PREFIX}${JSON.stringify(contradiction)}`
4795
- } : void 0;
4796
- const learnt = current.identity === void 0 && result.identity ? result.identity : void 0;
4797
- const stored = await rotateIn(rt, tx, id, credential, {
4798
- stamp: rotationStamp(prior, now),
4799
- // Write state first with the disable marker, then config below.
4800
- // Once the successor is durable, recovery projects the disable even
4801
- // if config has not landed. A crash before the first rename still
4802
- // loses an in-memory provider reply, as in any ordinary refresh.
4803
- transition,
4804
- identity: learnt,
4805
- ...incoming !== void 0 ? {
4806
- providerState: mergedProviderState(ctx.providerState, "refresh", id, current.providerState, incoming)
4807
- } : {}
4808
- });
4809
- if (transition !== void 0) {
4810
- applyTransition(tx, id, transition);
4811
- await tx.commitConfig();
4812
- }
4813
- let identity = current.identity;
4814
- if (learnt !== void 0) {
4815
- recordIdentityIn(tx, id, learnt);
4816
- identity = learnt;
4817
- await tx.commitConfig();
4818
- }
4819
- return { stored, identity, contradiction, refused: void 0 };
4820
- });
4821
- if (commit.refused !== void 0)
4822
- return { status: "refused", rowId: id, reason: commit.refused };
4823
- if (commit.contradiction !== void 0)
4824
- return {
4825
- status: "identity-contradicted",
4826
- rowId: id,
4827
- ...commit.contradiction,
4828
- credential: commit.stored
4829
- };
4830
- if (options.onPersisted) {
4831
- try {
4832
- const persisted = options.onPersisted;
4833
- await runInsideHook("refresh", () => persisted(id, commit.stored));
4834
- } catch (cause) {
4835
- throw new PoolOperationError({
4836
- operation: "refresh",
4837
- rowId: id,
4838
- phase: "after-first-write",
4839
- retryable: false,
4840
- kind: "after-persist-hook",
4841
- committed: commit.stored,
4842
- message: "the after-persist hook threw; the rotation stays committed",
4843
- cause
4844
- });
4845
- }
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;
4846
4698
  }
4847
- return {
4848
- status: "rotated",
4849
- rowId: id,
4850
- credential: commit.stored,
4851
- ...commit.identity !== void 0 ? { identity: commit.identity } : {}
4852
- };
4853
- });
4699
+ };
4854
4700
  }
4855
- var init_refresh = __esm({
4856
- "../core/dist/common-auth-embedded/store/refresh.js"() {
4701
+ var init_capture_sink = __esm({
4702
+ "../core/dist/common-auth-embedded/logger/capture-sink.js"() {
4857
4703
  "use strict";
4858
- init_errors();
4859
- init_hooks();
4860
- init_identity();
4861
- init_mutate();
4862
- init_provider_state();
4863
- init_reserved();
4864
- init_rows();
4865
- init_runtime();
4866
- init_schema();
4867
- init_torn();
4868
4704
  }
4869
4705
  });
4870
4706
 
4871
- // ../core/dist/common-auth-embedded/store/settings.js
4872
- import { isDeepStrictEqual as isDeepStrictEqual3 } from "node:util";
4873
- function settingsOf2(config) {
4874
- const settings = {};
4875
- for (const [key, value] of Object.entries(config))
4876
- if (!POOL_OWNED_KEYS.includes(key))
4877
- defineKey(settings, key, value);
4878
- return settings;
4879
- }
4880
- function defineKey(target, key, value) {
4881
- Object.defineProperty(target, key, {
4882
- value,
4883
- enumerable: true,
4884
- writable: true,
4885
- configurable: true
4886
- });
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]";
4887
4710
  }
4888
- function composeConfig(config, next) {
4889
- const out = {};
4890
- for (const [key, value] of Object.entries(config)) {
4891
- if (POOL_OWNED_KEYS.includes(key))
4892
- defineKey(out, key, value);
4893
- else if (Object.hasOwn(next, key))
4894
- defineKey(out, key, next[key]);
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);
4895
4716
  }
4896
- for (const [key, value] of Object.entries(next))
4897
- if (!Object.hasOwn(config, key))
4898
- defineKey(out, key, value);
4899
- return out;
4900
- }
4901
- function settingsRefusal(message) {
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);
4742
+ try {
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
+ ]));
4753
+ } finally {
4754
+ seen.delete(value);
4755
+ }
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
+ };
4762
+ }
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"() {
4766
+ "use strict";
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;
4774
+ }
4775
+ });
4776
+
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 {
4785
+ }
4786
+ }
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);
4796
+ }
4797
+ }
4798
+ const rotated = `${f}.1`;
4799
+ renameSync(f, rotated);
4800
+ chmodPrivate(rotated);
4801
+ } catch {
4802
+ }
4803
+ }
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
+ }
4825
+ }
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(() => {
4863
+ });
4864
+ throw error;
4865
+ }
4866
+ }
4867
+ function safeSerialize(data) {
4868
+ try {
4869
+ return ` ${JSON.stringify(data)}`;
4870
+ } catch {
4871
+ return " [unserializable]";
4872
+ }
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;
4891
+ }
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;
4900
+ }
4901
+ function setLogLevel3(l) {
4902
+ if (l === void 0 || l in ORDER)
4903
+ runtimeLevel = l;
4904
+ }
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;
4910
+ }
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";
4918
+ }
4919
+ function flushLogs3(close = true) {
4920
+ if (timer) {
4921
+ clearTimeout(timer);
4922
+ timer = void 0;
4923
+ }
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;
4933
+ }
4934
+ let file;
4935
+ try {
4936
+ file = logFilePath();
4937
+ } catch {
4938
+ buffer = [];
4939
+ if (windowsPrivateFiles && close)
4940
+ return queueWindows(() => closeWindowsFile(windowsFile));
4941
+ return;
4942
+ }
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 {
4966
+ }
4967
+ }
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 {
5012
+ }
5013
+ }
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
+ };
5022
+ }
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;
5038
+ }
5039
+ if (options)
5040
+ configure(options);
5041
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3, reset };
5042
+ }
5043
+ function createLoggerInstance(options) {
5044
+ const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine(options);
5045
+ return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
5046
+ }
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 };
5051
+ }
5052
+ function setLogLevel(l) {
5053
+ defaultEngine.setLogLevel(l);
5054
+ }
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"() {
5070
+ "use strict";
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();
5083
+ }
5084
+ });
5085
+
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"() {
5103
+ "use strict";
5104
+ init_capture_sink();
5105
+ init_engine();
5106
+ init_redact();
5107
+ }
5108
+ });
5109
+
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
+ };
5373
+ }
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;
5389
+ }
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);
5392
+ }
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;
5441
+ }
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)
5526
+ return {
5527
+ status: "identity-contradicted",
5528
+ rowId: id,
5529
+ ...commit.contradiction,
5530
+ credential: commit.stored
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
+ }
5548
+ }
5549
+ return {
5550
+ status: "rotated",
5551
+ rowId: id,
5552
+ credential: commit.stored,
5553
+ ...commit.identity !== void 0 ? { identity: commit.identity } : {}
5554
+ };
5555
+ });
5556
+ }
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;
5581
+ }
5582
+ function defineKey(target, key, value) {
5583
+ Object.defineProperty(target, key, {
5584
+ value,
5585
+ enumerable: true,
5586
+ writable: true,
5587
+ configurable: true
5588
+ });
5589
+ }
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]);
5597
+ }
5598
+ for (const [key, value] of Object.entries(next))
5599
+ if (!Object.hasOwn(config, key))
5600
+ defineKey(out, key, value);
5601
+ return out;
5602
+ }
5603
+ function settingsRefusal(message) {
4902
5604
  return new PoolOperationError({
4903
5605
  operation: "updateSettings",
4904
5606
  phase: "before-first-write",
@@ -5034,9 +5736,17 @@ function openPoolStore(options) {
5034
5736
  rowLockOptions: options.rowLockOptions ?? {},
5035
5737
  firePull: (id, reason) => pulls.fire(id, reason)
5036
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
+ };
5037
5747
  return {
5038
5748
  async load() {
5039
- const result = await readPool(ctx);
5749
+ const result = overlay(await readPool(ctx));
5040
5750
  if (result.status === "ready") {
5041
5751
  for (const row of result.rows)
5042
5752
  if ((row.candidate || row.torn && row.enabled) && row.type === "oauth" && row.needsFirstReading)
@@ -5045,7 +5755,7 @@ function openPoolStore(options) {
5045
5755
  return toLoad(result);
5046
5756
  },
5047
5757
  async read() {
5048
- return toLoad(await readPool(ctx));
5758
+ return toLoad(overlay(await readPool(ctx)));
5049
5759
  },
5050
5760
  async initialize(input = {}) {
5051
5761
  return { status: await initializePool(ctx, input.dropKeys ?? []) };
@@ -5064,7 +5774,9 @@ function openPoolStore(options) {
5064
5774
  updateSettings: (mutator, callOptions) => updatePoolSettings(rt, mutator, callOptions),
5065
5775
  recordIdentity: (id, identity, attribution, callOptions) => recordRowIdentity(rt, id, identity, attribution, callOptions),
5066
5776
  refresh: (id, provider2, callOptions) => refreshRow(rt, id, provider2, callOptions),
5067
- recordQuota: (id, attribution, observation) => recordQuota(rt, id, attribution, observation),
5777
+ recordQuota: record3,
5778
+ close: () => quotaWriter?.close() ?? Promise.resolve(),
5779
+ dispose: () => quotaWriter?.close() ?? Promise.resolve(),
5068
5780
  requestReading: (id) => pulls.fire(id, "admission"),
5069
5781
  pullsSettled: () => pulls.settled()
5070
5782
  };
@@ -5078,6 +5790,7 @@ var init_pool = __esm({
5078
5790
  init_provider_state();
5079
5791
  init_publication();
5080
5792
  init_pull();
5793
+ init_quota_writer();
5081
5794
  init_refresh();
5082
5795
  init_refresh_lock();
5083
5796
  init_rows();
@@ -5090,959 +5803,536 @@ var init_pool = __esm({
5090
5803
  // ../core/dist/common-auth-embedded/store/index.js
5091
5804
  var store_exports = {};
5092
5805
  __export(store_exports, {
5093
- DECLINE_TRANSITION: () => DECLINE_TRANSITION,
5094
- DUPLICATE_IDENTITY_REASON: () => DUPLICATE_IDENTITY_REASON,
5095
- LEGACY_STORE_VERSION: () => LEGACY_STORE_VERSION,
5096
- POOL_KEY: () => POOL_KEY,
5097
- POOL_LOCK_DEFAULTS: () => POOL_LOCK_DEFAULTS,
5098
- POOL_OWNED_KEYS: () => POOL_OWNED_KEYS,
5099
- POOL_ROWS_KEY: () => POOL_ROWS_KEY,
5100
- POOL_SCHEMA_VERSION: () => POOL_SCHEMA_VERSION,
5101
- PROVIDER_STATE_KEY: () => PROVIDER_STATE_KEY,
5102
- PoolOperationError: () => PoolOperationError,
5103
- PoolReentryError: () => PoolReentryError,
5104
- REFRESH_STAMP_TOLERANCE_MS: () => REFRESH_STAMP_TOLERANCE_MS,
5105
- countUnknownIdentityRows: () => countUnknownIdentityRows,
5106
- fingerprintOf: () => fingerprintOf,
5107
- openPoolStore: () => openPoolStore,
5108
- rowLockKey: () => rowLockKey
5109
- });
5110
- var init_store = __esm({
5111
- "../core/dist/common-auth-embedded/store/index.js"() {
5112
- "use strict";
5113
- init_errors();
5114
- init_identity();
5115
- init_pool();
5116
- init_provider_state();
5117
- init_refresh_lock();
5118
- init_schema();
5119
- init_settings();
5120
- }
5121
- });
5122
-
5123
- // ../core/dist/common-auth-embedded/fs/lock-constants.js
5124
- var WRITER_LOCK_CONSTANTS;
5125
- var init_lock_constants = __esm({
5126
- "../core/dist/common-auth-embedded/fs/lock-constants.js"() {
5127
- "use strict";
5128
- WRITER_LOCK_CONSTANTS = Object.freeze({
5129
- sidebar: Object.freeze({
5130
- name: "sidebar-write",
5131
- ttlMs: 1e4,
5132
- timeoutMs: 15e3,
5133
- renew: true
5134
- }),
5135
- preferences: Object.freeze({
5136
- name: "preferences",
5137
- ttlMs: 1e4,
5138
- timeoutMs: 2e3,
5139
- renew: true
5140
- })
5141
- });
5142
- }
5143
- });
5144
-
5145
- // ../core/dist/common-auth-embedded/fs/index.js
5146
- var fs_exports = {};
5147
- __export(fs_exports, {
5148
- LockContentionError: () => LockContentionError,
5149
- LockOwnershipError: () => LockOwnershipError,
5150
- PrivateFileError: () => PrivateFileError,
5151
- WRITER_LOCK_CONSTANTS: () => WRITER_LOCK_CONSTANTS,
5152
- acquireRefreshFileLock: () => acquireRefreshFileLock,
5153
- isLostMarkerRaceError: () => isLostMarkerRaceError,
5154
- lockPathFor: () => lockPathFor,
5155
- withLock: () => withLock,
5156
- writeJsonAtomic: () => writeJsonAtomic2
5157
- });
5158
- var init_fs = __esm({
5159
- "../core/dist/common-auth-embedded/fs/index.js"() {
5160
- "use strict";
5161
- init_atomic_write();
5162
- init_lock_constants();
5163
- init_private_files();
5164
- init_refresh_file_lock();
5165
- init_with_lock();
5166
- }
5167
- });
5168
-
5169
- // ../core/dist/common-auth-embedded/routing/admission.js
5170
- function exclusionFor(id, inputs, now) {
5171
- const markedUntil = inputs.rateLimitMarks?.get(id);
5172
- if (markedUntil !== void 0 && now < markedUntil) {
5173
- return { id, reason: "rate-limited", until: markedUntil };
5174
- }
5175
- const backoffUntil = inputs.refreshBackoff?.get(id);
5176
- if (backoffUntil !== void 0 && now < backoffUntil) {
5177
- return { id, reason: "refresh-backoff", until: backoffUntil };
5178
- }
5179
- return void 0;
5180
- }
5181
- function judgeStageOne(id, projection, requiredLabels, now) {
5182
- if (projection.limits.length === 0) {
5183
- return {
5184
- id,
5185
- stage: 1,
5186
- gate: 2,
5187
- reason: "needs-first-reading",
5188
- pullRequested: true
5189
- };
5190
- }
5191
- for (const label of requiredLabels) {
5192
- if (!projection.limits.some((limit) => limit.label === label)) {
5193
- return {
5194
- id,
5195
- stage: 1,
5196
- gate: 3,
5197
- reason: "unknown-window",
5198
- window: { scope: projection.scope, label },
5199
- pullRequested: true
5200
- };
5201
- }
5202
- }
5203
- const exhausted = projection.limits.filter(readsExhausted);
5204
- for (const limit of exhausted) {
5205
- if (futureResetAt(limit, now) === void 0) {
5206
- return {
5207
- id,
5208
- stage: 1,
5209
- gate: 4,
5210
- reason: "unknown-reset",
5211
- window: { scope: limit.scope, label: limit.label },
5212
- pullRequested: true
5213
- };
5214
- }
5215
- }
5216
- for (const limit of exhausted) {
5217
- const resetAtMs = futureResetAt(limit, now);
5218
- if (resetAtMs !== void 0 && typeof limit.resetsAt === "string") {
5219
- return {
5220
- id,
5221
- stage: 1,
5222
- gate: 5,
5223
- reason: "exhausted",
5224
- window: { scope: limit.scope, label: limit.label },
5225
- resetsAt: limit.resetsAt,
5226
- resetAtMs
5227
- };
5228
- }
5229
- }
5230
- return void 0;
5231
- }
5232
- function admit(input) {
5233
- const scope = input.scope ?? ALL_SCOPE;
5234
- const requiredLabels = input.requiredLabels ?? DEFAULT_REQUIRED_LABELS;
5235
- const excluded = [];
5236
- const refused = [];
5237
- const survivors = [];
5238
- for (const row of input.rows) {
5239
- const exclusion = exclusionFor(row.id, input, input.now);
5240
- if (exclusion) {
5241
- excluded.push(exclusion);
5242
- continue;
5243
- }
5244
- if (row.kind === "api-key") {
5245
- survivors.push({ id: row.id, kind: row.kind });
5246
- continue;
5247
- }
5248
- const projection = projectQuota(row.quota, scope);
5249
- const refusal3 = judgeStageOne(row.id, projection, requiredLabels, input.now);
5250
- if (refusal3) {
5251
- refused.push(refusal3);
5252
- continue;
5253
- }
5254
- survivors.push({ id: row.id, kind: row.kind, projection });
5255
- }
5256
- const spent = new Map(survivors.flatMap((row) => {
5257
- const reset = budgetExhaustedResetAt(row.projection, input.now);
5258
- return reset ? [[row.id, reset]] : [];
5259
- }));
5260
- const lastPath = spent.size > 0 && spent.size === survivors.length;
5261
- const admitted = [];
5262
- for (const row of survivors) {
5263
- const reset = spent.get(row.id);
5264
- if (reset === void 0) {
5265
- admitted.push(row);
5266
- } else if (lastPath) {
5267
- admitted.push({ ...row, lastPath: true });
5268
- } else {
5269
- refused.push({ id: row.id, stage: 2, reason: "budget-spent", ...reset });
5270
- }
5271
- }
5272
- const order = new Map(input.rows.map((row, index) => [row.id, index]));
5273
- const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
5274
- refused.sort(byInput);
5275
- const pulls = refused.filter((refusal3) => "pullRequested" in refusal3).map((refusal3) => refusal3.id);
5276
- for (const id of pulls)
5277
- input.requestPull?.(id);
5278
- return { admitted, refused, excluded, pulls };
5279
- }
5280
- var init_admission = __esm({
5281
- "../core/dist/common-auth-embedded/routing/admission.js"() {
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"() {
5282
5825
  "use strict";
5283
- init_map();
5284
- init_projection();
5826
+ init_errors();
5827
+ init_identity();
5828
+ init_pool();
5829
+ init_provider_state();
5830
+ init_refresh_lock();
5831
+ init_schema();
5832
+ init_settings();
5285
5833
  }
5286
5834
  });
5287
5835
 
5288
- // ../core/dist/common-auth-embedded/routing/ordered.js
5289
- function resolveRoutingMode(value) {
5290
- switch (value) {
5291
- case "sticky-balanced":
5292
- return { mode: "sticky-balanced", placement: "roster" };
5293
- case "main-first":
5294
- return { mode: "ordered", placement: "main-first" };
5295
- case "fallback-first":
5296
- return { mode: "ordered", placement: "fallback-first" };
5297
- default:
5298
- return { mode: "ordered", placement: "roster" };
5299
- }
5300
- }
5301
- function orderForPlacement(ids, placement, formerMainId = DEFAULT_FORMER_MAIN_ID) {
5302
- if (placement === "roster" || !ids.includes(formerMainId))
5303
- return [...ids];
5304
- const rest = ids.filter((id) => id !== formerMainId);
5305
- return placement === "main-first" ? [formerMainId, ...rest] : [...rest, formerMainId];
5306
- }
5307
- function routeOrdered(input) {
5308
- const admission = admit(input);
5309
- const admitted = new Set(admission.admitted.map((row) => row.id));
5310
- const order = orderForPlacement(input.rows.map((row) => row.id), input.placement ?? "roster", input.formerMainId).filter((id) => admitted.has(id) && input.killswitch?.get(id) !== false);
5311
- return { order, admission };
5312
- }
5313
- function nextOrderedAttempt(order, attempts2, retryStatuses) {
5314
- const last = attempts2.at(-1);
5315
- if (last !== void 0) {
5316
- if (last.status === void 0 || !retryStatuses.includes(last.status)) {
5317
- return void 0;
5318
- }
5319
- }
5320
- const tried = new Set(attempts2.map((attempt) => attempt.id));
5321
- return order.find((id) => !tried.has(id));
5322
- }
5323
- var DEFAULT_FORMER_MAIN_ID;
5324
- var init_ordered = __esm({
5325
- "../core/dist/common-auth-embedded/routing/ordered.js"() {
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"() {
5326
5840
  "use strict";
5327
- init_admission();
5328
- DEFAULT_FORMER_MAIN_ID = "main";
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
+ });
5329
5855
  }
5330
5856
  });
5331
5857
 
5332
- // ../core/dist/common-auth-embedded/routing/pins.js
5333
- function isPinValid(pin, validIds, currentIdentity) {
5334
- if (!validIds.has(pin.accountId))
5335
- return false;
5336
- return !(typeof pin.wireIdentity === "string" && typeof currentIdentity === "string" && pin.wireIdentity !== currentIdentity);
5337
- }
5338
- function pendingBytesForPins(pins, quotaCheckedAtById, excludedSessionKey) {
5339
- const pending = /* @__PURE__ */ new Map();
5340
- for (const [sessionKey, pin] of pins) {
5341
- if (sessionKey === excludedSessionKey)
5342
- continue;
5343
- if (pin.quotaCheckedAt !== quotaCheckedAtById.get(pin.accountId))
5344
- continue;
5345
- pending.set(pin.accountId, (pending.get(pin.accountId) ?? 0) + (pin.inputBytes ?? 0));
5346
- }
5347
- return pending;
5348
- }
5349
- var init_pins = __esm({
5350
- "../core/dist/common-auth-embedded/routing/pins.js"() {
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
5870
+ });
5871
+ var init_fs = __esm({
5872
+ "../core/dist/common-auth-embedded/fs/index.js"() {
5351
5873
  "use strict";
5874
+ init_atomic_write();
5875
+ init_lock_constants();
5876
+ init_private_files();
5877
+ init_refresh_file_lock();
5878
+ init_with_lock();
5352
5879
  }
5353
5880
  });
5354
5881
 
5355
- // ../core/dist/common-auth-embedded/routing/sticky.js
5356
- function snapshotCheckedAt(quota, entryCheckedAt) {
5357
- for (const checkedAt of [quota?.checkedAt, entryCheckedAt]) {
5358
- if (typeof checkedAt === "number" && Number.isFinite(checkedAt)) {
5359
- return checkedAt;
5360
- }
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 };
5361
5887
  }
5362
- return void 0;
5363
- }
5364
- function defaultStickyStatusClass(status) {
5365
- if (status === 401 || status === 403)
5366
- return "permanent";
5367
- if (status === void 0 || status === 0 || !Number.isFinite(status) || status >= 500 && status <= 599 || status === 429) {
5368
- return "transient";
5888
+ const backoffUntil = inputs.refreshBackoff?.get(id);
5889
+ if (backoffUntil !== void 0 && now < backoffUntil) {
5890
+ return { id, reason: "refresh-backoff", until: backoffUntil };
5369
5891
  }
5370
- return "healthy";
5371
- }
5372
- function windowReadings(quota) {
5373
- return quota.limits.filter((limit) => limit.kind === "reading").sort((left, right) => {
5374
- const leftKnown = left.windowMinutes !== void 0;
5375
- const rightKnown = right.windowMinutes !== void 0;
5376
- if (leftKnown !== rightKnown)
5377
- return leftKnown ? -1 : 1;
5378
- if (leftKnown && rightKnown) {
5379
- return (right.windowMinutes ?? 0) - (left.windowMinutes ?? 0);
5380
- }
5381
- return 0;
5382
- });
5892
+ return void 0;
5383
5893
  }
5384
- function decideStickyBreak(input) {
5385
- const statusClass = (input.classifyStatus ?? defaultStickyStatusClass)(input.status);
5386
- if (statusClass === "permanent") {
5387
- return { action: "migrate", reason: "permanent" };
5388
- }
5389
- if (!input.quota)
5390
- return { action: "retain", reason: "unknown" };
5391
- const checkedAt = snapshotCheckedAt(input.quota, input.quotaCheckedAt);
5392
- if (checkedAt === void 0 || !Number.isFinite(checkedAt) || input.now - checkedAt > QUOTA_STALENESS_MS) {
5393
- return { action: "retain", reason: "stale" };
5394
- }
5395
- if (input.killswitchPasses === false) {
5396
- return { action: "migrate", reason: "killswitch" };
5397
- }
5398
- for (const limit of windowReadings(input.quota)) {
5399
- const remaining = limit.remainingPercent;
5400
- if (typeof remaining === "number" && Number.isFinite(remaining) && remaining <= 0) {
5401
- return {
5402
- action: "migrate",
5403
- reason: "exhausted",
5404
- window: { scope: limit.scope, label: limit.label },
5405
- ...typeof limit.resetsAt === "string" ? { resetsAt: limit.resetsAt } : {}
5406
- };
5407
- }
5408
- }
5409
- const budgetReset = budgetExhaustedResetAt(input.quota, input.now);
5410
- if (budgetReset) {
5894
+ function judgeStageOne(id, projection, requiredLabels, now) {
5895
+ if (projection.limits.length === 0) {
5411
5896
  return {
5412
- action: "migrate",
5413
- reason: "exhausted",
5414
- resetsAt: budgetReset.resetsAt
5415
- };
5416
- }
5417
- return { action: "retain", reason: statusClass };
5418
- }
5419
- function sustainableWindowWeight(window, reservePercent, now) {
5420
- const spendable = Math.max(0, window.remainingPercent - reservePercent);
5421
- if (spendable <= 0)
5422
- return 0;
5423
- if (!window.resetsAt)
5424
- return spendable;
5425
- const resetMs = Date.parse(window.resetsAt);
5426
- if (!Number.isFinite(resetMs) || resetMs <= now)
5427
- return spendable;
5428
- const hours = Math.max((resetMs - now) / 36e5, MIN_RESET_HOURS);
5429
- return spendable / hours;
5430
- }
5431
- function compareAccountIds(left, right) {
5432
- if (left < right)
5433
- return -1;
5434
- if (left > right)
5435
- return 1;
5436
- return 0;
5437
- }
5438
- function candidateWeight(candidate, now) {
5439
- if (!candidate.quota)
5440
- return void 0;
5441
- const quotaCheckedAt = snapshotCheckedAt(candidate.quota, candidate.quotaCheckedAt);
5442
- if (quotaCheckedAt === void 0 || now - quotaCheckedAt > QUOTA_STALENESS_MS) {
5443
- return void 0;
5444
- }
5445
- const weights = windowReadings(candidate.quota).map((limit) => sustainableWindowWeight({
5446
- remainingPercent: limit.remainingPercent ?? Number.NaN,
5447
- ...limit.resetsAt === void 0 ? {} : { resetsAt: limit.resetsAt }
5448
- }, candidate.reservePercent[limit.label] ?? 0, now));
5449
- const budget = candidate.quota.budget;
5450
- if (budget && typeof budget.remainingPercent === "number" && Number.isFinite(budget.remainingPercent)) {
5451
- weights.push(sustainableWindowWeight({
5452
- remainingPercent: budget.remainingPercent,
5453
- ...budget.resetsAt === void 0 ? {} : { resetsAt: budget.resetsAt }
5454
- }, 0, now));
5455
- }
5456
- const weight = weights.length > 0 ? Math.min(...weights) : 0;
5457
- return weight > 0 ? { candidate, quotaCheckedAt, weight } : void 0;
5458
- }
5459
- function selectStickyCandidate(input) {
5460
- const eligibleCandidates = input.candidates.filter((candidate) => candidate.killswitchPasses !== false);
5461
- if (input.candidates.length === 0) {
5462
- throw new Error("Cannot select a sticky candidate: input.candidates is empty");
5463
- }
5464
- if (eligibleCandidates.length === 0)
5465
- return void 0;
5466
- const weighted = eligibleCandidates.map((candidate) => candidateWeight(candidate, input.now)).filter((candidate) => candidate !== void 0);
5467
- if (weighted.length > 0) {
5468
- weighted.sort((left, right) => {
5469
- const leftScore = ((input.pendingBytes.get(left.candidate.accountId) ?? 0) + input.requestBytes) / Math.max(left.weight, MIN_WEIGHT);
5470
- const rightScore = ((input.pendingBytes.get(right.candidate.accountId) ?? 0) + input.requestBytes) / Math.max(right.weight, MIN_WEIGHT);
5471
- return leftScore - rightScore || left.candidate.configuredOrder - right.candidate.configuredOrder || compareAccountIds(left.candidate.accountId, right.candidate.accountId);
5472
- });
5473
- const selected = weighted[0];
5474
- if (selected) {
5897
+ id,
5898
+ stage: 1,
5899
+ gate: 2,
5900
+ reason: "needs-first-reading",
5901
+ pullRequested: true
5902
+ };
5903
+ }
5904
+ for (const label of requiredLabels) {
5905
+ if (!projection.limits.some((limit) => limit.label === label)) {
5475
5906
  return {
5476
- accountId: selected.candidate.accountId,
5477
- quotaCheckedAt: selected.quotaCheckedAt,
5478
- source: "weighted"
5907
+ id,
5908
+ stage: 1,
5909
+ gate: 3,
5910
+ reason: "unknown-window",
5911
+ window: { scope: projection.scope, label },
5912
+ pullRequested: true
5479
5913
  };
5480
5914
  }
5481
5915
  }
5482
- input.onEmptyWeightedSet?.();
5483
- const fallback = [...eligibleCandidates].sort((left, right) => {
5484
- const leftHasCredits = (left.resetCreditsApplicable ?? 0) > 0 ? 1 : 0;
5485
- const rightHasCredits = (right.resetCreditsApplicable ?? 0) > 0 ? 1 : 0;
5486
- return rightHasCredits - leftHasCredits || left.configuredOrder - right.configuredOrder || compareAccountIds(left.accountId, right.accountId);
5487
- })[0];
5488
- if (!fallback) {
5489
- throw new Error("Cannot select a sticky candidate: input.candidates is empty");
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
+ };
5927
+ }
5490
5928
  }
5491
- return {
5492
- accountId: fallback.accountId,
5493
- quotaCheckedAt: snapshotCheckedAt(fallback.quota, fallback.quotaCheckedAt),
5494
- source: "mode-fallback"
5495
- };
5496
- }
5497
- function routeSticky(input) {
5498
- const admission = admit(input);
5499
- const admitted = new Map(admission.admitted.map((row) => [row.id, row]));
5500
- const refusals = new Map(admission.refused.map((r) => [r.id, r]));
5501
- const excluded = new Set(admission.excluded.map((row) => row.id));
5502
- const validIds = new Set(input.rows.map((row) => row.id));
5503
- const pinValid = input.pin !== void 0 && isPinValid(input.pin, validIds, input.identities?.get(input.pin.accountId));
5504
- if (pinValid && input.pin) {
5505
- const pinned = admitted.get(input.pin.accountId);
5506
- if (pinned && input.killswitch?.get(pinned.id) !== false) {
5929
+ for (const limit of exhausted) {
5930
+ const resetAtMs = futureResetAt(limit, now);
5931
+ if (resetAtMs !== void 0 && typeof limit.resetsAt === "string") {
5507
5932
  return {
5508
- outcome: "dispatch",
5509
- accountId: pinned.id,
5510
- source: "pin",
5511
- ...pinned.projection?.checkedAt === void 0 ? {} : { quotaCheckedAt: pinned.projection.checkedAt },
5512
- pin: { action: "retain" },
5513
- refusedSelections: [],
5514
- admission
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
5515
5940
  };
5516
5941
  }
5517
5942
  }
5518
- const pinRefusal = input.pin ? refusals.get(input.pin.accountId) : void 0;
5519
- 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");
5520
- const reserveFor = (row) => {
5521
- const perRow = typeof input.rowReservePercent === "function" ? input.rowReservePercent(row) : input.rowReservePercent?.get(row.id);
5522
- return perRow ?? input.reservePercent ?? {};
5523
- };
5524
- const scope = input.scope;
5525
- let candidates = input.rows.map((row, configuredOrder) => ({ row, configuredOrder })).filter(({ row }) => !excluded.has(row.id)).map(({ row, configuredOrder }) => {
5526
- const killswitchPasses = input.killswitch?.get(row.id);
5527
- const credits = input.resetCreditsApplicable?.get(row.id);
5528
- return {
5529
- accountId: row.id,
5530
- quota: row.kind === "api-key" ? void 0 : admitted.get(row.id)?.projection ?? projectQuota(row.quota, scope),
5531
- reservePercent: reserveFor(row),
5532
- configuredOrder,
5533
- ...credits === void 0 ? {} : { resetCreditsApplicable: credits },
5534
- ...killswitchPasses === void 0 ? {} : { killswitchPasses }
5535
- };
5536
- });
5537
- const refusedSelections = [];
5538
- const unplaced = pinValid ? { action: "retain" } : input.pin ? { action: "clear" } : { action: "none" };
5539
- while (candidates.length > 0) {
5540
- const selection = selectStickyCandidate({
5541
- candidates,
5542
- pendingBytes: input.pendingBytes ?? /* @__PURE__ */ new Map(),
5543
- requestBytes: input.requestBytes,
5544
- now: input.now,
5545
- ...input.onEmptyWeightedSet ? { onEmptyWeightedSet: input.onEmptyWeightedSet } : {}
5546
- });
5547
- if (!selection)
5548
- break;
5549
- const refusal3 = refusals.get(selection.accountId);
5943
+ return void 0;
5944
+ }
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);
5550
5963
  if (refusal3) {
5551
- refusedSelections.push(refusal3);
5552
- candidates = candidates.filter((candidate) => candidate.accountId !== selection.accountId);
5964
+ refused.push(refusal3);
5553
5965
  continue;
5554
5966
  }
5555
- const identity = input.identities?.get(selection.accountId);
5556
- return {
5557
- outcome: "dispatch",
5558
- accountId: selection.accountId,
5559
- source: selection.source,
5560
- ...selection.quotaCheckedAt === void 0 ? {} : { quotaCheckedAt: selection.quotaCheckedAt },
5561
- pin: pinValid && !pinMoves ? { action: "retain" } : {
5562
- action: "assign",
5563
- pin: {
5564
- accountId: selection.accountId,
5565
- inputBytes: input.requestBytes,
5566
- ...identity === void 0 ? {} : { wireIdentity: identity },
5567
- ...selection.quotaCheckedAt === void 0 ? {} : { quotaCheckedAt: selection.quotaCheckedAt }
5568
- }
5569
- },
5570
- refusedSelections,
5571
- admission
5572
- };
5967
+ survivors.push({ id: row.id, kind: row.kind, projection });
5573
5968
  }
5574
- return {
5575
- outcome: "no-admissible-account",
5576
- pin: unplaced,
5577
- refusedSelections,
5578
- admission
5579
- };
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 });
5983
+ }
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 };
5580
5992
  }
5581
- var QUOTA_STALENESS_MS, MIN_RESET_HOURS, MIN_WEIGHT;
5582
- var init_sticky = __esm({
5583
- "../core/dist/common-auth-embedded/routing/sticky.js"() {
5993
+ var init_admission = __esm({
5994
+ "../core/dist/common-auth-embedded/routing/admission.js"() {
5584
5995
  "use strict";
5996
+ init_map();
5585
5997
  init_projection();
5586
- init_admission();
5587
- init_pins();
5588
- QUOTA_STALENESS_MS = 15 * 6e4;
5589
- MIN_RESET_HOURS = 1 / 60;
5590
- MIN_WEIGHT = 1e-6;
5591
5998
  }
5592
5999
  });
5593
6000
 
5594
- // ../core/dist/common-auth-embedded/routing/index.js
5595
- var routing_exports = {};
5596
- __export(routing_exports, {
5597
- DEFAULT_FORMER_MAIN_ID: () => DEFAULT_FORMER_MAIN_ID,
5598
- MIN_RESET_HOURS: () => MIN_RESET_HOURS,
5599
- MIN_WEIGHT: () => MIN_WEIGHT,
5600
- QUOTA_STALENESS_MS: () => QUOTA_STALENESS_MS,
5601
- admit: () => admit,
5602
- decideStickyBreak: () => decideStickyBreak,
5603
- defaultStickyStatusClass: () => defaultStickyStatusClass,
5604
- exclusionFor: () => exclusionFor,
5605
- isPinValid: () => isPinValid,
5606
- nextOrderedAttempt: () => nextOrderedAttempt,
5607
- orderForPlacement: () => orderForPlacement,
5608
- pendingBytesForPins: () => pendingBytesForPins,
5609
- resolveRoutingMode: () => resolveRoutingMode,
5610
- routeOrdered: () => routeOrdered,
5611
- routeSticky: () => routeSticky,
5612
- selectStickyCandidate: () => selectStickyCandidate,
5613
- snapshotCheckedAt: () => snapshotCheckedAt,
5614
- sustainableWindowWeight: () => sustainableWindowWeight
5615
- });
5616
- var init_routing = __esm({
5617
- "../core/dist/common-auth-embedded/routing/index.js"() {
5618
- "use strict";
5619
- init_admission();
5620
- init_ordered();
5621
- init_pins();
5622
- init_sticky();
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" };
5623
6012
  }
5624
- });
5625
-
5626
- // ../core/dist/common-auth-embedded/logger/capture-sink.js
5627
- function createCaptureSink() {
5628
- const records = [];
5629
- const sink = (record3) => {
5630
- records.push(record3);
5631
- };
5632
- return {
5633
- records,
5634
- sink,
5635
- clear: () => {
5636
- records.length = 0;
6013
+ }
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;
5637
6031
  }
5638
- };
6032
+ }
6033
+ const tried = new Set(attempts2.map((attempt) => attempt.id));
6034
+ return order.find((id) => !tried.has(id));
5639
6035
  }
5640
- var init_capture_sink = __esm({
5641
- "../core/dist/common-auth-embedded/logger/capture-sink.js"() {
6036
+ var DEFAULT_FORMER_MAIN_ID;
6037
+ var init_ordered = __esm({
6038
+ "../core/dist/common-auth-embedded/routing/ordered.js"() {
5642
6039
  "use strict";
6040
+ init_admission();
6041
+ DEFAULT_FORMER_MAIN_ID = "main";
5643
6042
  }
5644
6043
  });
5645
6044
 
5646
- // ../core/dist/common-auth-embedded/logger/redact.js
5647
- function isError(value) {
5648
- return value instanceof Error || Object.prototype.toString.call(value) === "[object Error]";
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);
5649
6050
  }
5650
- function createRedactor(options = {}) {
5651
- const patterns = [TOKEN_VALUE, ...options.extraValuePatterns ?? []].map((pattern) => new RegExp(pattern.source, pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`));
5652
- function isSecretKey(key) {
5653
- const normalized = key.toLowerCase().replace(/[-_]/g, "");
5654
- return SECRET_KEY_EXACT.test(key) || normalized.includes("apikey") || normalized.endsWith("secret") || normalized.endsWith("password") || normalized.endsWith("token") && !normalized.endsWith("tokens") || !!options.extraSecretKeys?.(normalized);
5655
- }
5656
- function errorEntries(error) {
5657
- const fields2 = error;
5658
- const entries = [
5659
- ["name", error.name],
5660
- ["message", error.message],
5661
- ["stack", error.stack]
5662
- ];
5663
- for (const key of ["code", "status", "cause"])
5664
- if (fields2[key] !== void 0)
5665
- entries.push([key, fields2[key]]);
5666
- const listed = new Set(entries.map(([key]) => key));
5667
- for (const entry of Object.entries(error))
5668
- if (!listed.has(entry[0]))
5669
- entries.push(entry);
5670
- return entries;
5671
- }
5672
- function walk(value, keys, seen, errorDepth = 0) {
5673
- if (typeof value === "string") {
5674
- return patterns.reduce((text2, pattern) => text2.replace(pattern, MASK), value);
5675
- }
5676
- if (!value || typeof value !== "object")
5677
- return value;
5678
- if (seen.has(value))
5679
- return "[Circular]";
5680
- seen.add(value);
5681
- try {
5682
- if (Array.isArray(value))
5683
- return value.map((item) => walk(item, keys, seen, errorDepth));
5684
- const error = isError(value);
5685
- if (error && errorDepth >= MAX_ERROR_DEPTH)
5686
- return "[Truncated]";
5687
- const childDepth = error ? errorDepth + 1 : errorDepth;
5688
- return Object.fromEntries((error ? errorEntries(value) : Object.entries(value)).map(([key, item]) => [
5689
- key,
5690
- keys && isSecretKey(key) ? MASK : walk(item, keys, seen, childDepth)
5691
- ]));
5692
- } finally {
5693
- seen.delete(value);
5694
- }
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));
5695
6059
  }
5696
- return {
5697
- redact: (value) => walk(value, true, /* @__PURE__ */ new WeakSet()),
5698
- // Schema keys describe arguments, not credentials; only their string values are scrubbed.
5699
- redactStrings: (value) => walk(value, false, /* @__PURE__ */ new WeakSet())
5700
- };
6060
+ return pending;
5701
6061
  }
5702
- var SECRET_KEY_EXACT, TOKEN_VALUE, MASK, MAX_ERROR_DEPTH, defaultRedactor, redact, redactStrings;
5703
- var init_redact = __esm({
5704
- "../core/dist/common-auth-embedded/logger/redact.js"() {
6062
+ var init_pins = __esm({
6063
+ "../core/dist/common-auth-embedded/routing/pins.js"() {
5705
6064
  "use strict";
5706
- SECRET_KEY_EXACT = /^(authorization|x-api-key|cookie|set-cookie|refresh|access|token)$/i;
5707
- TOKEN_VALUE = /\b(Bearer\s+[\w.-]+|sk-[\w-]+|eyJ[\w.-]+)\b|ckh_[A-Za-z0-9_-]{20,}/g;
5708
- MASK = "***REDACTED***";
5709
- MAX_ERROR_DEPTH = 8;
5710
- defaultRedactor = createRedactor();
5711
- redact = defaultRedactor.redact;
5712
- redactStrings = defaultRedactor.redactStrings;
5713
6065
  }
5714
6066
  });
5715
6067
 
5716
- // ../core/dist/common-auth-embedded/logger/engine.js
5717
- import { appendFileSync, chmodSync, existsSync, renameSync, statSync } from "node:fs";
5718
- import { open as open5 } from "node:fs/promises";
5719
- import { dirname as dirname8, resolve as resolve3 } from "node:path";
5720
- function chmodPrivate(path2) {
5721
- try {
5722
- chmodSync(path2, 384);
5723
- } catch {
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
+ }
5724
6074
  }
6075
+ return void 0;
5725
6076
  }
5726
- function rotateIfNeeded(f) {
5727
- try {
5728
- if (!(existsSync(f) && statSync(f).size >= MAX_BYTES))
5729
- return;
5730
- for (let i = ROTATE_KEEP - 1; i >= 1; i--) {
5731
- if (existsSync(`${f}.${i}`)) {
5732
- const rotated2 = `${f}.${i + 1}`;
5733
- renameSync(`${f}.${i}`, rotated2);
5734
- chmodPrivate(rotated2);
5735
- }
5736
- }
5737
- const rotated = `${f}.1`;
5738
- renameSync(f, rotated);
5739
- chmodPrivate(rotated);
5740
- } catch {
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";
5741
6082
  }
6083
+ return "healthy";
5742
6084
  }
5743
- async function closeWindowsFile(sink) {
5744
- const { file, handle } = sink;
5745
- sink.file = void 0;
5746
- sink.handle = void 0;
5747
- if (file && handle)
5748
- await privateOperation(file, "log-close", () => handle.close());
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);
6093
+ }
6094
+ return 0;
6095
+ });
5749
6096
  }
5750
- async function openWindowsFile(sink, file) {
5751
- await ensurePrivateDirectory(dirname8(file));
5752
- try {
5753
- await verifyPrivate(file, "file", true);
5754
- } catch (error) {
5755
- if (error.code !== "ENOENT")
5756
- throw error;
5757
- try {
5758
- await createPrivateBytes(file, "");
5759
- } catch (creationError) {
5760
- if (creationError.code !== "EEXIST")
5761
- throw creationError;
5762
- await verifyPrivate(file, "file", true);
6097
+ function decideStickyBreak(input) {
6098
+ const statusClass = (input.classifyStatus ?? defaultStickyStatusClass)(input.status);
6099
+ if (statusClass === "permanent") {
6100
+ return { action: "migrate", reason: "permanent" };
6101
+ }
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
+ };
5763
6120
  }
5764
6121
  }
5765
- sink.handle = await privateOperation(file, "log-open", () => open5(file, "a"));
5766
- sink.file = file;
5767
- return sink.handle;
6122
+ const budgetReset = budgetExhaustedResetAt(input.quota, input.now);
6123
+ if (budgetReset) {
6124
+ return {
6125
+ action: "migrate",
6126
+ reason: "exhausted",
6127
+ resetsAt: budgetReset.resetsAt
6128
+ };
6129
+ }
6130
+ return { action: "retain", reason: statusClass };
5768
6131
  }
5769
- async function flushWindowsFile(sink, file, text2) {
5770
- file = resolve3(file);
5771
- try {
5772
- if (sink.file !== file)
5773
- await closeWindowsFile(sink);
5774
- let handle = sink.handle ?? await openWindowsFile(sink, file);
5775
- const info = await privateOperation(file, "log-stat", () => handle.stat());
5776
- if (info.size >= MAX_BYTES) {
5777
- await closeWindowsFile(sink);
5778
- for (let i = ROTATE_KEEP - 1; i >= 0; i--) {
5779
- const source = i === 0 ? file : `${file}.${i}`;
5780
- const target = `${file}.${i + 1}`;
5781
- try {
5782
- await verifyPrivate(source, "file", true);
5783
- } catch (error) {
5784
- if (error.code === "ENOENT")
5785
- continue;
5786
- throw error;
5787
- }
5788
- try {
5789
- await verifyPrivate(target, "file", true);
5790
- } catch (error) {
5791
- if (error.code !== "ENOENT")
5792
- throw error;
5793
- }
5794
- await replaceWindowsFile(source, target);
5795
- await verifyPrivate(target, "file");
5796
- }
5797
- handle = await openWindowsFile(sink, file);
5798
- }
5799
- await privateOperation(file, "log-append", () => handle.appendFile(text2, "utf8"));
5800
- } catch (error) {
5801
- await closeWindowsFile(sink).catch(() => {
5802
- });
5803
- throw error;
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;
6143
+ }
6144
+ function compareAccountIds(left, right) {
6145
+ if (left < right)
6146
+ return -1;
6147
+ if (left > right)
6148
+ return 1;
6149
+ return 0;
6150
+ }
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));
5804
6168
  }
6169
+ const weight = weights.length > 0 ? Math.min(...weights) : 0;
6170
+ return weight > 0 ? { candidate, quotaCheckedAt, weight } : void 0;
5805
6171
  }
5806
- function safeSerialize(data) {
5807
- try {
5808
- return ` ${JSON.stringify(data)}`;
5809
- } catch {
5810
- return " [unserializable]";
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");
5811
6176
  }
5812
- }
5813
- function createEngine(options) {
5814
- let logFileSource;
5815
- let initLevelSource;
5816
- let runtimeLevel;
5817
- let redactor = createRedactor();
5818
- let captureSink;
5819
- let buffer = [];
5820
- let timer;
5821
- let orderedSink = Promise.resolve();
5822
- let sinkError;
5823
- const windowsFile = {};
5824
- function queueWindows(operation) {
5825
- const next = orderedSink.then(operation);
5826
- orderedSink = next.catch((error) => {
5827
- sinkError = error;
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);
5828
6185
  });
5829
- return next;
5830
- }
5831
- function configure(next) {
5832
- if (windowsPrivateFiles && next.file !== logFileSource)
5833
- void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
5834
- });
5835
- logFileSource = next.file;
5836
- initLevelSource = next.level;
5837
- redactor = createRedactor(next);
5838
- captureSink = next.captureSink;
5839
- }
5840
- function setLogLevel3(l) {
5841
- if (l === void 0 || l in ORDER)
5842
- runtimeLevel = l;
5843
- }
5844
- function logFilePath() {
5845
- if (logFileSource === void 0)
5846
- return void 0;
5847
- const resolved = typeof logFileSource === "function" ? logFileSource() : logFileSource;
5848
- return resolved || void 0;
5849
- }
5850
- function configuredLevel() {
5851
- if (runtimeLevel)
5852
- return runtimeLevel;
5853
- const floor = typeof initLevelSource === "function" ? initLevelSource() : initLevelSource;
5854
- if (floor && floor in ORDER)
5855
- return floor;
5856
- return "info";
5857
- }
5858
- function flushLogs3(close = true) {
5859
- if (timer) {
5860
- clearTimeout(timer);
5861
- timer = void 0;
5862
- }
5863
- if (!buffer.length) {
5864
- if (windowsPrivateFiles)
5865
- return queueWindows(async () => {
5866
- if (close)
5867
- await closeWindowsFile(windowsFile);
5868
- if (sinkError)
5869
- throw sinkError;
5870
- });
5871
- return;
5872
- }
5873
- let file;
5874
- try {
5875
- file = logFilePath();
5876
- } catch {
5877
- buffer = [];
5878
- if (windowsPrivateFiles && close)
5879
- return queueWindows(() => closeWindowsFile(windowsFile));
5880
- return;
5881
- }
5882
- const text2 = buffer.join("");
5883
- buffer = [];
5884
- if (!file) {
5885
- if (windowsPrivateFiles && close)
5886
- return queueWindows(() => closeWindowsFile(windowsFile));
5887
- return;
5888
- }
5889
- if (windowsPrivateFiles) {
5890
- return queueWindows(async () => {
5891
- try {
5892
- await flushWindowsFile(windowsFile, file, text2);
5893
- } finally {
5894
- if (close)
5895
- await closeWindowsFile(windowsFile);
5896
- }
5897
- });
5898
- }
5899
- try {
5900
- rotateIfNeeded(file);
5901
- if (existsSync(file))
5902
- chmodPrivate(file);
5903
- appendFileSync(file, text2, { encoding: "utf8", mode: 384 });
5904
- } catch {
6186
+ const selected = weighted[0];
6187
+ if (selected) {
6188
+ return {
6189
+ accountId: selected.candidate.accountId,
6190
+ quotaCheckedAt: selected.quotaCheckedAt,
6191
+ source: "weighted"
6192
+ };
5905
6193
  }
5906
6194
  }
5907
- function schedule2() {
5908
- if (!timer)
5909
- timer = setTimeout(() => {
5910
- timer = void 0;
5911
- const flushed = flushLogs3(false);
5912
- if (flushed instanceof Promise)
5913
- void flushed.catch(() => {
5914
- });
5915
- }, 500);
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");
5916
6203
  }
5917
- function emit(channel, level, message, data) {
5918
- if (logFileSource === void 0 && captureSink === void 0)
5919
- return;
5920
- try {
5921
- if (ORDER[level] > ORDER[configuredLevel()])
5922
- return;
5923
- const scrubbedMessage = redactor.redactStrings(message);
5924
- let scrubbedData;
5925
- try {
5926
- scrubbedData = redactor.redact(data);
5927
- } catch {
5928
- scrubbedData = "[unserializable]";
5929
- }
5930
- const line = `[${(/* @__PURE__ */ new Date()).toISOString()}] ${level.toUpperCase()} [${channel}] ${scrubbedMessage}` + (data === void 0 ? "" : safeSerialize(scrubbedData)) + "\n";
5931
- try {
5932
- captureSink?.({
5933
- channel,
5934
- level,
5935
- message: scrubbedMessage,
5936
- data: scrubbedData
5937
- });
5938
- } catch {
5939
- }
5940
- if (logFileSource === void 0)
5941
- return;
5942
- buffer.push(line);
5943
- if (buffer.length >= 50) {
5944
- const flushed = flushLogs3(false);
5945
- if (flushed instanceof Promise)
5946
- void flushed.catch(() => {
5947
- });
5948
- } else
5949
- schedule2();
5950
- } catch {
6204
+ return {
6205
+ accountId: fallback.accountId,
6206
+ quotaCheckedAt: snapshotCheckedAt(fallback.quota, fallback.quotaCheckedAt),
6207
+ source: "mode-fallback"
6208
+ };
6209
+ }
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
+ };
5951
6229
  }
5952
6230
  }
5953
- function createLogger5(channel) {
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);
5954
6241
  return {
5955
- error: (m, d) => emit(channel, "error", m, d),
5956
- warn: (m, d) => emit(channel, "warn", m, d),
5957
- info: (m, d) => emit(channel, "info", m, d),
5958
- debug: (m, d) => emit(channel, "debug", m, d),
5959
- trace: (m, d) => emit(channel, "trace", m, d)
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 }
5960
6248
  };
5961
- }
5962
- function reset() {
5963
- if (windowsPrivateFiles)
5964
- void queueWindows(() => closeWindowsFile(windowsFile)).catch(() => {
5965
- });
5966
- sinkError = void 0;
5967
- buffer = [];
5968
- if (timer) {
5969
- clearTimeout(timer);
5970
- timer = void 0;
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;
5971
6267
  }
5972
- logFileSource = void 0;
5973
- initLevelSource = void 0;
5974
- runtimeLevel = void 0;
5975
- redactor = createRedactor();
5976
- captureSink = void 0;
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
6285
+ };
5977
6286
  }
5978
- if (options)
5979
- configure(options);
5980
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3, reset };
5981
- }
5982
- function createLoggerInstance(options) {
5983
- const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = createEngine(options);
5984
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
5985
- }
5986
- function initLogger(options) {
5987
- defaultEngine.configure(options);
5988
- const { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 } = defaultEngine;
5989
- return { configure, createLogger: createLogger5, setLogLevel: setLogLevel3, flushLogs: flushLogs3 };
5990
- }
5991
- function setLogLevel(l) {
5992
- defaultEngine.setLogLevel(l);
5993
- }
5994
- function flushLogs() {
5995
- return defaultEngine.flushLogs();
5996
- }
5997
- function createLogger2(channel) {
5998
- return defaultEngine.createLogger(channel);
5999
- }
6000
- async function flushForTest() {
6001
- return defaultEngine.flushLogs();
6002
- }
6003
- function resetLoggerForTest() {
6004
- defaultEngine.reset();
6287
+ return {
6288
+ outcome: "no-admissible-account",
6289
+ pin: unplaced,
6290
+ refusedSelections,
6291
+ admission
6292
+ };
6005
6293
  }
6006
- var ORDER, MAX_BYTES, ROTATE_KEEP, defaultEngine;
6007
- var init_engine = __esm({
6008
- "../core/dist/common-auth-embedded/logger/engine.js"() {
6294
+ var QUOTA_STALENESS_MS, MIN_RESET_HOURS, MIN_WEIGHT;
6295
+ var init_sticky = __esm({
6296
+ "../core/dist/common-auth-embedded/routing/sticky.js"() {
6009
6297
  "use strict";
6010
- init_private_files();
6011
- init_redact();
6012
- ORDER = {
6013
- error: 0,
6014
- warn: 1,
6015
- info: 2,
6016
- debug: 3,
6017
- trace: 4
6018
- };
6019
- MAX_BYTES = 5 * 1024 * 1024;
6020
- ROTATE_KEEP = 3;
6021
- defaultEngine = createEngine();
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;
6022
6304
  }
6023
6305
  });
6024
6306
 
6025
- // ../core/dist/common-auth-embedded/logger/index.js
6026
- var logger_exports = {};
6027
- __export(logger_exports, {
6028
- createCaptureSink: () => createCaptureSink,
6029
- createLogger: () => createLogger2,
6030
- createLoggerInstance: () => createLoggerInstance,
6031
- createRedactor: () => createRedactor,
6032
- flushForTest: () => flushForTest,
6033
- flushLogs: () => flushLogs,
6034
- initLogger: () => initLogger,
6035
- redact: () => redact,
6036
- redactStrings: () => redactStrings,
6037
- resetLoggerForTest: () => resetLoggerForTest,
6038
- setLogLevel: () => setLogLevel
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
6039
6328
  });
6040
- var init_logger = __esm({
6041
- "../core/dist/common-auth-embedded/logger/index.js"() {
6329
+ var init_routing = __esm({
6330
+ "../core/dist/common-auth-embedded/routing/index.js"() {
6042
6331
  "use strict";
6043
- init_capture_sink();
6044
- init_engine();
6045
- init_redact();
6332
+ init_admission();
6333
+ init_ordered();
6334
+ init_pins();
6335
+ init_sticky();
6046
6336
  }
6047
6337
  });
6048
6338
 
@@ -6339,13 +6629,16 @@ function addedText(name, result) {
6339
6629
  function failureMessage(error) {
6340
6630
  return projectFailure(error).text;
6341
6631
  }
6342
- async function snapshot(store) {
6632
+ async function snapshot(options) {
6633
+ const { store } = options;
6343
6634
  const load = await store.read();
6344
6635
  const read = await store.readSettings();
6636
+ const vault = await options.routing?.vaultOrder?.();
6345
6637
  return {
6346
6638
  load,
6347
6639
  rows: distinctRows(load),
6348
- settings: read.status === "error" ? {} : read.settings
6640
+ settings: read.status === "error" ? {} : read.settings,
6641
+ ...vault ? { vault } : {}
6349
6642
  };
6350
6643
  }
6351
6644
  function accountView(row, options) {
@@ -6552,6 +6845,57 @@ function quotaSection(options, snap) {
6552
6845
  }
6553
6846
  };
6554
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
+ }
6555
6899
  function routingSection(options, snap) {
6556
6900
  const { store, extraLocks } = options;
6557
6901
  const locks = extraLocks ? { extraLocks } : {};
@@ -6563,14 +6907,16 @@ function routingSection(options, snap) {
6563
6907
  const raw = record(snap.settings.routing).mode;
6564
6908
  const current = typeof raw === "string" && choices.some((choice) => choice.value === raw) ? raw : "ordered";
6565
6909
  const resolved = resolveRoutingMode(current);
6566
- 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;
6567
6913
  const tried = orderForPlacement(ids, resolved.placement, options.routing?.formerMainId ?? DEFAULT_FORMER_MAIN_ID);
6568
6914
  const label = choices.find((choice) => choice.value === current)?.label ?? current;
6569
6915
  const lines = [`Mode: ${label}`];
6570
6916
  if (ids.length > 0)
6571
- lines.push(`Roster order: ${ids.join(", ")}`);
6917
+ lines.push(`${vault ? "Vault account order" : "Roster order"}: ${ids.map(nameOf).join(", ")}`);
6572
6918
  if (resolved.mode === "ordered" && tried.join() !== ids.join())
6573
- lines.push(`Tried in order: ${tried.join(", ")}`);
6919
+ lines.push(`Tried in order: ${tried.map(nameOf).join(", ")}`);
6574
6920
  const actions = [
6575
6921
  {
6576
6922
  id: "mode",
@@ -6598,15 +6944,16 @@ function routingSection(options, snap) {
6598
6944
  {
6599
6945
  kind: "text",
6600
6946
  id: "order",
6601
- label: "Account ids, first to last",
6602
- 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(", "),
6603
6949
  required: true
6604
6950
  }
6605
6951
  ],
6606
6952
  run: async ({ values }) => {
6607
- const order = String(values.order).split(/[\s,]+/).filter((id) => id.length > 0);
6608
- const result = await store.reorder(order, locks);
6609
- 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(", ")}.`;
6610
6957
  }
6611
6958
  });
6612
6959
  return {
@@ -6735,7 +7082,7 @@ function limitsSection(options, snap) {
6735
7082
  };
6736
7083
  }
6737
7084
  async function builtinSections(options) {
6738
- const snap = await snapshot(options.store);
7085
+ const snap = await snapshot(options);
6739
7086
  return [
6740
7087
  accountsSection(options, snap),
6741
7088
  quotaSection(options, snap),
@@ -10170,6 +10517,59 @@ var init_custody = __esm({
10170
10517
  }
10171
10518
  });
10172
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
+
10173
10573
  // ../core/dist/common-auth-embedded/claustrum/interlock.js
10174
10574
  function matches(entry, credentialId, accountIdentity) {
10175
10575
  if (entry.accountIdentity !== void 0 && accountIdentity !== void 0)
@@ -10470,6 +10870,52 @@ function acceptVaultRoute(path2, routeId) {
10470
10870
  };
10471
10871
  });
10472
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
+ }
10473
10919
  function receiptFence(row, receipt2) {
10474
10920
  if (!memberIds(row).includes(receipt2.credentialId))
10475
10921
  return "refuse";
@@ -10615,8 +11061,8 @@ var init_roster = __esm({
10615
11061
  init_quota();
10616
11062
  init_errors2();
10617
11063
  init_interlock();
10618
- init_quota_writer();
10619
- init_quota_writer();
11064
+ init_quota_writer2();
11065
+ init_quota_writer2();
10620
11066
  DEFAULT_ROUTE_PREFIX = "vault:";
10621
11067
  SKIPPED_REASONS = /* @__PURE__ */ new Set([
10622
11068
  "empty credential id",
@@ -10665,56 +11111,12 @@ function retainVaultQuotaWriter(path2, listener) {
10665
11111
  })();
10666
11112
  }
10667
11113
  function fields(publication2) {
10668
- const result = /* @__PURE__ */ new Map();
10669
- const { observation } = publication2;
10670
- const witness = JSON.stringify([
11114
+ return quotaFields(publication2, JSON.stringify([
10671
11115
  publication2.routeId,
10672
11116
  publication2.receipt?.credentialId,
10673
11117
  publication2.receipt?.accountIdentitySource,
10674
11118
  publication2.receipt?.expectedAccountIdentity
10675
- ]);
10676
- const add = (key, at, part) => result.set(`${witness}:${key}`, {
10677
- at,
10678
- order: 0,
10679
- publication: { ...publication2, observation: part }
10680
- });
10681
- const keyFor = (scope, label) => JSON.stringify([scope ?? "all", label]);
10682
- const read = /* @__PURE__ */ new Set();
10683
- for (const reading of observation.readings ?? []) {
10684
- const key = keyFor(reading.scope, reading.label);
10685
- read.add(key);
10686
- add(key, observation.checkedAt, {
10687
- checkedAt: observation.checkedAt,
10688
- readings: [{ ...reading }]
10689
- });
10690
- }
10691
- for (const pair of observation.coverage ?? []) {
10692
- const key = keyFor(pair.scope, pair.label);
10693
- if (!read.has(key))
10694
- add(key, observation.checkedAt, {
10695
- checkedAt: observation.checkedAt,
10696
- coverage: [{ ...pair }]
10697
- });
10698
- }
10699
- if (observation.budget)
10700
- add("budget", observation.checkedAt, {
10701
- checkedAt: observation.checkedAt,
10702
- budget: { ...observation.budget }
10703
- });
10704
- for (const [name, counter] of Object.entries(observation.counters ?? {})) {
10705
- add(`counter:${name}`, counter.checkedAt, {
10706
- checkedAt: observation.checkedAt,
10707
- counters: { [name]: { ...counter } }
10708
- });
10709
- }
10710
- if (observation.credits)
10711
- add("credits", observation.credits.checkedAt, {
10712
- checkedAt: observation.checkedAt,
10713
- credits: { ...observation.credits }
10714
- });
10715
- if (!result.size)
10716
- add("empty", observation.checkedAt, { checkedAt: observation.checkedAt });
10717
- return result;
11119
+ ]));
10718
11120
  }
10719
11121
  function enqueueVaultQuota(path2, publication2) {
10720
11122
  if (!isQuotaObservation(publication2.observation))
@@ -10738,7 +11140,7 @@ function enqueueVaultQuota(path2, publication2) {
10738
11140
  writer.pending.set(account, pending);
10739
11141
  for (const listener of writer.listeners)
10740
11142
  listener(publication2);
10741
- schedule(writer, COALESCE_MS);
11143
+ schedule(writer, COALESCE_MS2);
10742
11144
  return Promise.resolve(true);
10743
11145
  }
10744
11146
  function orderedFields(pending) {
@@ -10803,7 +11205,7 @@ function flush(writer) {
10803
11205
  writer.running = void 0;
10804
11206
  for (const wake of writer.wake)
10805
11207
  wake();
10806
- 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;
10807
11209
  schedule(writer, backoff);
10808
11210
  }
10809
11211
  })();
@@ -10849,16 +11251,17 @@ async function drainVaultQuota(path2, timeoutMs = 1e3) {
10849
11251
  }
10850
11252
  }
10851
11253
  }
10852
- var writers, logger, COALESCE_MS;
10853
- var init_quota_writer = __esm({
11254
+ var writers, logger, COALESCE_MS2;
11255
+ var init_quota_writer2 = __esm({
10854
11256
  "../core/dist/common-auth-embedded/claustrum/quota-writer.js"() {
10855
11257
  "use strict";
10856
11258
  init_logger();
10857
11259
  init_quota();
11260
+ init_pending();
10858
11261
  init_roster();
10859
11262
  writers = /* @__PURE__ */ new Map();
10860
11263
  logger = createLogger2("claustrum");
10861
- COALESCE_MS = 100;
11264
+ COALESCE_MS2 = 100;
10862
11265
  }
10863
11266
  });
10864
11267
 
@@ -10873,7 +11276,7 @@ var init_consumer = __esm({
10873
11276
  init_enrollment();
10874
11277
  init_errors2();
10875
11278
  init_insula();
10876
- init_quota_writer();
11279
+ init_quota_writer2();
10877
11280
  init_roster();
10878
11281
  init_watch();
10879
11282
  ClaustrumConsumer = class {
@@ -11304,7 +11707,10 @@ var init_consumer = __esm({
11304
11707
  let current;
11305
11708
  try {
11306
11709
  current = await this.authorize(routeId, signal);
11307
- } catch {
11710
+ signal?.throwIfAborted();
11711
+ } catch (error) {
11712
+ if (signal?.aborted)
11713
+ throw error;
11308
11714
  }
11309
11715
  if (decideScopedRetryAfter401(options.site, served, current, this.#logger)) {
11310
11716
  await response.body?.cancel().catch(() => {
@@ -11334,6 +11740,17 @@ var init_consumer = __esm({
11334
11740
  await acceptVaultRoute(this.#options.rosterPath, routeId);
11335
11741
  this.#roster = pendingVaultQuota(this.#options.rosterPath, await readVaultRoster(this.#options.rosterPath));
11336
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
+ }
11337
11754
  /**
11338
11755
  * Store a quota or profile observation for a vault route. The receipt the
11339
11756
  * reading was taken with is required: the observation lands only while the
@@ -11449,6 +11866,7 @@ __export(claustrum_exports, {
11449
11866
  recordVaultAccountQuota: () => recordVaultAccountQuota,
11450
11867
  recordVaultQuota: () => recordVaultQuota,
11451
11868
  refreshVaultRoster: () => refreshVaultRoster,
11869
+ reorderVaultRoster: () => reorderVaultRoster,
11452
11870
  resetClaustrumEnrollmentState: () => resetClaustrumEnrollmentState,
11453
11871
  resolveVaultPrimary: () => resolveVaultPrimary,
11454
11872
  vaultRoutingRows: () => vaultRoutingRows
@@ -11471,7 +11889,7 @@ var init_claustrum = __esm({
11471
11889
  init_host_slot();
11472
11890
  init_insula();
11473
11891
  init_interlock();
11474
- init_quota_writer();
11892
+ init_quota_writer2();
11475
11893
  init_roster();
11476
11894
  init_watch();
11477
11895
  }
@@ -23994,7 +24412,7 @@ async function assertHostsStopped(fence, env3) {
23994
24412
 
23995
24413
  // src/common-auth-embedded/setup/enroll.js
23996
24414
  var ENROLLMENT_INCOMPLETE_MESSAGE = "Claustrum enrollment did not complete. Inspect and approve with ck, then rerun setup.";
23997
- var UNSUPPORTED_VAULT_MESSAGE = "This Claustrum vault does not support connecting plugins yet, so setup cannot connect to it. Run setup without --claustrum to use local accounts.";
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.';
23998
24416
  var ENROLLMENT_WAIT_MS = 3e5;
23999
24417
  var APPROVAL_POLL_MS = 1e3;
24000
24418
  var PROPOSE_BACKOFF_MS = [1e3, 2e3, 4e3, 8e3, 16e3, 3e4];