@cortexkit/common-auth 0.33.0 → 0.34.0

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 (106) hide show
  1. package/dist/claustrum/consumer.d.ts +12 -0
  2. package/dist/claustrum/consumer.js +36 -0
  3. package/dist/claustrum/custody.d.ts +16 -4
  4. package/dist/claustrum/custody.js +74 -9
  5. package/dist/claustrum/hub.d.ts +3 -2
  6. package/dist/claustrum/hub.js +8 -0
  7. package/dist/claustrum/index.d.ts +1 -0
  8. package/dist/claustrum/roster.d.ts +2 -0
  9. package/dist/claustrum/roster.js +2 -0
  10. package/dist/claustrum/usage.d.ts +41 -0
  11. package/dist/claustrum/usage.js +145 -0
  12. package/dist/commands/builtins.d.ts +5 -0
  13. package/dist/commands/builtins.js +38 -0
  14. package/dist/fs/private-files.d.ts +5 -0
  15. package/dist/fs/private-files.js +7 -0
  16. package/dist/fs/refresh-file-lock.js +142 -47
  17. package/dist/fs/with-lock.js +2 -5
  18. package/dist/limits/activity.d.ts +26 -0
  19. package/dist/limits/activity.js +52 -0
  20. package/dist/limits/axes.d.ts +63 -0
  21. package/dist/limits/axes.js +7 -0
  22. package/dist/limits/bridge.d.ts +4 -0
  23. package/dist/limits/bridge.js +10 -0
  24. package/dist/limits/decide.d.ts +141 -0
  25. package/dist/limits/decide.js +383 -0
  26. package/dist/limits/duration.d.ts +8 -0
  27. package/dist/limits/duration.js +20 -0
  28. package/dist/limits/envelope-loss.d.ts +29 -0
  29. package/dist/limits/envelope-loss.js +150 -0
  30. package/dist/limits/families.d.ts +57 -0
  31. package/dist/limits/families.js +143 -0
  32. package/dist/limits/header-classifier.d.ts +9 -0
  33. package/dist/limits/header-classifier.js +121 -0
  34. package/dist/limits/hold.d.ts +13 -0
  35. package/dist/limits/hold.js +25 -0
  36. package/dist/limits/identity.d.ts +14 -0
  37. package/dist/limits/identity.js +21 -0
  38. package/dist/limits/index.d.ts +44 -0
  39. package/dist/limits/index.js +25 -0
  40. package/dist/limits/jitter.d.ts +2 -0
  41. package/dist/limits/jitter.js +9 -0
  42. package/dist/limits/labels.d.ts +3 -0
  43. package/dist/limits/labels.js +11 -0
  44. package/dist/limits/marker.d.ts +64 -0
  45. package/dist/limits/marker.js +96 -0
  46. package/dist/limits/merge-laws.d.ts +14 -0
  47. package/dist/limits/merge-laws.js +31 -0
  48. package/dist/limits/namespace.d.ts +89 -0
  49. package/dist/limits/namespace.js +183 -0
  50. package/dist/limits/persistence.d.ts +33 -0
  51. package/dist/limits/persistence.js +9 -0
  52. package/dist/limits/pi-wait.d.ts +16 -0
  53. package/dist/limits/pi-wait.js +51 -0
  54. package/dist/limits/pool-adapter.d.ts +16 -0
  55. package/dist/limits/pool-adapter.js +162 -0
  56. package/dist/limits/presets.d.ts +11 -0
  57. package/dist/limits/presets.js +223 -0
  58. package/dist/limits/registry.d.ts +49 -0
  59. package/dist/limits/registry.js +471 -0
  60. package/dist/limits/request-history.d.ts +77 -0
  61. package/dist/limits/request-history.js +117 -0
  62. package/dist/limits/reset.d.ts +21 -0
  63. package/dist/limits/reset.js +44 -0
  64. package/dist/limits/routing-hold.d.ts +16 -0
  65. package/dist/limits/routing-hold.js +23 -0
  66. package/dist/limits/scope.d.ts +12 -0
  67. package/dist/limits/scope.js +10 -0
  68. package/dist/limits/signal.d.ts +41 -0
  69. package/dist/limits/signal.js +1 -0
  70. package/dist/limits/terminal.d.ts +52 -0
  71. package/dist/limits/terminal.js +133 -0
  72. package/dist/limits/vault-adapter.d.ts +16 -0
  73. package/dist/limits/vault-adapter.js +123 -0
  74. package/dist/limits/vault.d.ts +1 -0
  75. package/dist/limits/vault.js +1 -0
  76. package/dist/limits/wake.d.ts +21 -0
  77. package/dist/limits/wake.js +47 -0
  78. package/dist/limits/wording.d.ts +25 -0
  79. package/dist/limits/wording.js +114 -0
  80. package/dist/opencode2/index.d.ts +1 -1
  81. package/dist/opencode2/install.d.ts +2 -2
  82. package/dist/opencode2/install.js +161 -18
  83. package/dist/opencode2/types.d.ts +95 -9
  84. package/dist/routing/admission.d.ts +7 -2
  85. package/dist/routing/admission.js +17 -7
  86. package/dist/routing-accessor/handle.d.ts +1 -0
  87. package/dist/routing-accessor/handle.js +10 -0
  88. package/dist/routing-accessor/index.d.ts +13 -3
  89. package/dist/routing-accessor/index.js +11 -10
  90. package/dist/rpc/port-file.d.ts +12 -3
  91. package/dist/rpc/port-file.js +46 -4
  92. package/dist/store/attribution.js +3 -2
  93. package/dist/store/errors.d.ts +1 -1
  94. package/dist/store/hooks.d.ts +5 -1
  95. package/dist/store/hooks.js +20 -5
  96. package/dist/store/index.d.ts +1 -0
  97. package/dist/store/limits-namespace.d.ts +7 -0
  98. package/dist/store/limits-namespace.js +34 -0
  99. package/dist/store/pool.d.ts +10 -1
  100. package/dist/store/pool.js +2 -0
  101. package/dist/store/provider-state.js +5 -5
  102. package/dist/store/refresh.js +1 -1
  103. package/dist/store/schema.js +9 -4
  104. package/dist/store/settings.d.ts +2 -0
  105. package/dist/store/settings.js +11 -4
  106. package/package.json +10 -2
@@ -0,0 +1,31 @@
1
+ /** Apply supersession before expiry, so a short or zero overwrite removes a long mark. */
2
+ export function mergeTimedMarkEntries(law, entries, now, clearRevision = 0) {
3
+ const candidates = entries.filter((e) => e.baseRevision >= clearRevision);
4
+ if (law !== 'max-until') {
5
+ const winner = candidates.reduce((best, e) => {
6
+ if (!best)
7
+ return e;
8
+ if (law === 'latest-evidence' && e.evidenceAt !== best.evidenceAt) {
9
+ return e.evidenceAt > best.evidenceAt ? e : best;
10
+ }
11
+ return e.committedRevision > best.committedRevision ? e : best;
12
+ }, undefined);
13
+ return winner && now < winner.until ? [winner] : [];
14
+ }
15
+ return candidates
16
+ .filter((e, i) => now < e.until &&
17
+ !candidates.some((other, j) => j !== i &&
18
+ other.until >= e.until &&
19
+ other.baseRevision >= e.baseRevision &&
20
+ (other.until > e.until ||
21
+ other.baseRevision > e.baseRevision ||
22
+ other.committedRevision > e.committedRevision ||
23
+ (other.committedRevision === e.committedRevision && j < i))))
24
+ .sort((a, b) => a.committedRevision - b.committedRevision);
25
+ }
26
+ export function mergeAccessState(a, b) {
27
+ if (a.eligibilityStateUpdatedAt !== b.eligibilityStateUpdatedAt) {
28
+ return a.eligibilityStateUpdatedAt > b.eligibilityStateUpdatedAt ? a : b;
29
+ }
30
+ return a.committedRevision > b.committedRevision ? a : b;
31
+ }
@@ -0,0 +1,89 @@
1
+ import type { AuthorizeCredentialEpoch, IdentityBinding } from './identity.js';
2
+ import type { MergeLaw } from './marker.js';
3
+ import type { AccessOrder, TimedMarkEntry } from './merge-laws.js';
4
+ import type { Scope } from './scope.js';
5
+ import type { AccountKey } from './signal.js';
6
+ export declare const LIMITS_HISTORY_BOUND = 1024;
7
+ export interface MarkTarget {
8
+ readonly scope: Scope;
9
+ readonly window: string;
10
+ }
11
+ export interface TimedMarkKey extends MarkTarget {
12
+ readonly account: AccountKey;
13
+ }
14
+ export interface NamespaceMark {
15
+ readonly key: TimedMarkKey;
16
+ readonly mergeLaw: MergeLaw;
17
+ readonly entries: readonly TimedMarkEntry[];
18
+ }
19
+ export interface ClearTombstone {
20
+ readonly key: TimedMarkKey;
21
+ readonly revision: number;
22
+ }
23
+ export interface CommittedOperation {
24
+ readonly producerId: string;
25
+ readonly operationId: string;
26
+ readonly revision: number;
27
+ }
28
+ export interface NamespaceAccess<T = unknown> extends AccessOrder {
29
+ readonly account: AccountKey;
30
+ readonly state: T;
31
+ }
32
+ /** JSON-compatible state; adapters own generation creation, locking and persistence. */
33
+ export interface LimitsNamespace<T = unknown> {
34
+ readonly schemaVersion: 1;
35
+ readonly namespace: string;
36
+ readonly generation: string;
37
+ readonly revision: number;
38
+ readonly lowWatermark: number;
39
+ readonly marks: readonly NamespaceMark[];
40
+ readonly tombstones: readonly ClearTombstone[];
41
+ readonly operationIds: readonly CommittedOperation[];
42
+ readonly access: readonly NamespaceAccess<T>[];
43
+ }
44
+ interface CommandBase {
45
+ readonly producerId: string;
46
+ readonly operationId: string;
47
+ readonly binding: IdentityBinding;
48
+ readonly baseRevision: number;
49
+ }
50
+ export type LimitsCommand<T = unknown> = CommandBase & (({
51
+ readonly type: 'mark';
52
+ readonly until: number;
53
+ readonly evidenceAt: number;
54
+ readonly mergeLaw: MergeLaw;
55
+ } & MarkTarget) | {
56
+ readonly type: 'clear';
57
+ readonly keys: readonly MarkTarget[];
58
+ /** Absent for explicit user clears; automatic clears carry their evidence time. */
59
+ readonly evidenceAt?: number;
60
+ } | {
61
+ readonly type: 'access';
62
+ readonly state: T;
63
+ readonly eligibilityStateUpdatedAt: number;
64
+ });
65
+ export interface LimitsMergeContext {
66
+ readonly now: number;
67
+ /** Current identity bindings, loaded under the same lock as this merge. */
68
+ readonly bindings: readonly IdentityBinding[];
69
+ readonly authorizeEpoch: AuthorizeCredentialEpoch;
70
+ }
71
+ export type LimitsRejection = 'below-watermark' | 'future-revision' | 'wrong-namespace' | 'unknown-account' | 'identity-replaced' | 'credential-epoch' | 'cleared' | 'newer-evidence' | 'merge-law-conflict';
72
+ export interface LimitsCommandOutcome {
73
+ readonly producerId: string;
74
+ readonly operationId: string;
75
+ readonly status: 'committed' | 'duplicate' | 'rejected';
76
+ readonly revision?: number;
77
+ readonly reason?: LimitsRejection;
78
+ }
79
+ export interface LimitsMergeResult<T = unknown> {
80
+ readonly snapshot: LimitsNamespace<T>;
81
+ readonly outcomes: readonly LimitsCommandOutcome[];
82
+ }
83
+ export declare function createLimitsNamespace<T = unknown>(namespace: string, generation: string): LimitsNamespace<T>;
84
+ export declare function timedMarkKeyId(key: TimedMarkKey): string;
85
+ /** Apply tombstones before compacting them; the watermark then fences delayed commands. */
86
+ export declare function pruneLimitsNamespace<T>(snapshot: LimitsNamespace<T>, now: number): LimitsNamespace<T>;
87
+ /** Pure transaction body; load namespace state and identity bindings under one lock. */
88
+ export declare function applyLimitsCommands<T>(initial: LimitsNamespace<T>, commands: readonly LimitsCommand<T>[], context: LimitsMergeContext): LimitsMergeResult<T>;
89
+ export {};
@@ -0,0 +1,183 @@
1
+ import { validateIdentityFence } from './identity.js';
2
+ import { mergeAccessState, mergeTimedMarkEntries } from './merge-laws.js';
3
+ import { sameAccount } from './request-history.js';
4
+ export const LIMITS_HISTORY_BOUND = 1024;
5
+ export function createLimitsNamespace(namespace, generation) {
6
+ return {
7
+ schemaVersion: 1,
8
+ namespace,
9
+ generation,
10
+ revision: 0,
11
+ lowWatermark: 0,
12
+ marks: [],
13
+ tombstones: [],
14
+ operationIds: [],
15
+ access: [],
16
+ };
17
+ }
18
+ function accountId(account) {
19
+ return JSON.stringify([
20
+ account.namespace,
21
+ account.accountId,
22
+ account.incarnation,
23
+ ]);
24
+ }
25
+ export function timedMarkKeyId(key) {
26
+ const scope = key.scope;
27
+ return JSON.stringify([
28
+ accountId(key.account),
29
+ scope.kind,
30
+ scope.kind === 'model'
31
+ ? scope.model
32
+ : scope.kind === 'family'
33
+ ? scope.family
34
+ : null,
35
+ key.window,
36
+ ]);
37
+ }
38
+ function operationId(op) {
39
+ return JSON.stringify([op.producerId, op.operationId]);
40
+ }
41
+ /** Apply tombstones before compacting them; the watermark then fences delayed commands. */
42
+ export function pruneLimitsNamespace(snapshot, now) {
43
+ const clears = new Map(snapshot.tombstones.map((t) => [timedMarkKeyId(t.key), t.revision]));
44
+ const marks = snapshot.marks.flatMap((mark) => {
45
+ const entries = mergeTimedMarkEntries(mark.mergeLaw, mark.entries, now, clears.get(timedMarkKeyId(mark.key)));
46
+ return entries.length ? [{ ...mark, entries }] : [];
47
+ });
48
+ let lowWatermark = snapshot.lowWatermark;
49
+ const compact = (entries) => {
50
+ const ordered = [...entries].sort((a, b) => a.revision - b.revision);
51
+ const count = Math.max(0, ordered.length - LIMITS_HISTORY_BOUND);
52
+ for (const entry of ordered.slice(0, count)) {
53
+ lowWatermark = Math.max(lowWatermark, entry.revision + 1);
54
+ }
55
+ return ordered.slice(count);
56
+ };
57
+ const tombstones = compact(snapshot.tombstones);
58
+ const operationIds = compact(snapshot.operationIds);
59
+ return {
60
+ ...snapshot,
61
+ revision: Math.max(snapshot.revision, lowWatermark),
62
+ marks,
63
+ tombstones,
64
+ operationIds,
65
+ lowWatermark,
66
+ };
67
+ }
68
+ /** Pure transaction body; load namespace state and identity bindings under one lock. */
69
+ export function applyLimitsCommands(initial, commands, context) {
70
+ let snapshot = pruneLimitsNamespace(initial, context.now);
71
+ const outcomes = [];
72
+ for (const command of commands) {
73
+ const reject = (reason) => {
74
+ outcomes.push({
75
+ producerId: command.producerId,
76
+ operationId: command.operationId,
77
+ status: 'rejected',
78
+ reason,
79
+ });
80
+ };
81
+ if (command.binding.account.namespace !== snapshot.namespace) {
82
+ reject('wrong-namespace');
83
+ continue;
84
+ }
85
+ if (command.baseRevision < snapshot.lowWatermark) {
86
+ reject('below-watermark');
87
+ continue;
88
+ }
89
+ if (command.baseRevision > snapshot.revision) {
90
+ reject('future-revision');
91
+ continue;
92
+ }
93
+ const authoritative = context.bindings.find((b) => sameAccount(b.account, command.binding.account));
94
+ if (!authoritative) {
95
+ reject('unknown-account');
96
+ continue;
97
+ }
98
+ const fence = validateIdentityFence(command.binding, authoritative, context.authorizeEpoch);
99
+ if (fence) {
100
+ reject(fence);
101
+ continue;
102
+ }
103
+ const duplicate = snapshot.operationIds.find((op) => operationId(op) === operationId(command));
104
+ if (duplicate) {
105
+ outcomes.push({ ...duplicate, status: 'duplicate' });
106
+ continue;
107
+ }
108
+ const account = authoritative.account;
109
+ const revision = snapshot.revision + 1;
110
+ let marks = [...snapshot.marks];
111
+ let tombstones = [...snapshot.tombstones];
112
+ let access = [...snapshot.access];
113
+ if (command.type === 'mark') {
114
+ const key = { account, scope: command.scope, window: command.window };
115
+ const id = timedMarkKeyId(key);
116
+ const previous = marks.find((m) => timedMarkKeyId(m.key) === id);
117
+ const clear = tombstones.find((t) => timedMarkKeyId(t.key) === id);
118
+ if (clear && command.baseRevision < clear.revision) {
119
+ reject('cleared');
120
+ continue;
121
+ }
122
+ if (previous && previous.mergeLaw !== command.mergeLaw) {
123
+ reject('merge-law-conflict');
124
+ continue;
125
+ }
126
+ const entries = mergeTimedMarkEntries(command.mergeLaw, [
127
+ ...(previous?.entries ?? []),
128
+ {
129
+ until: command.until,
130
+ evidenceAt: command.evidenceAt,
131
+ baseRevision: command.baseRevision,
132
+ committedRevision: revision,
133
+ },
134
+ ], context.now, clear?.revision);
135
+ marks = marks.filter((m) => timedMarkKeyId(m.key) !== id);
136
+ if (entries.length)
137
+ marks.push({ key, mergeLaw: command.mergeLaw, entries });
138
+ }
139
+ else if (command.type === 'clear') {
140
+ const keys = command.keys.map((key) => ({ ...key, account }));
141
+ const ids = new Set(keys.map(timedMarkKeyId));
142
+ const evidenceAt = command.evidenceAt;
143
+ if (evidenceAt !== undefined &&
144
+ marks.some((m) => ids.has(timedMarkKeyId(m.key)) &&
145
+ m.entries.some((e) => e.evidenceAt > evidenceAt))) {
146
+ reject('newer-evidence');
147
+ continue;
148
+ }
149
+ marks = marks.filter((m) => !ids.has(timedMarkKeyId(m.key)));
150
+ tombstones = tombstones.filter((t) => !ids.has(timedMarkKeyId(t.key)));
151
+ // A clear enumerates covered keys, not all scopes on the account.
152
+ for (const key of new Map(keys.map((k) => [timedMarkKeyId(k), k])).values()) {
153
+ tombstones.push({ key, revision });
154
+ }
155
+ }
156
+ else {
157
+ const incoming = {
158
+ account,
159
+ state: command.state,
160
+ eligibilityStateUpdatedAt: command.eligibilityStateUpdatedAt,
161
+ committedRevision: revision,
162
+ };
163
+ const previous = access.find((a) => sameAccount(a.account, account));
164
+ access = access.filter((a) => !sameAccount(a.account, account));
165
+ access.push(previous ? mergeAccessState(previous, incoming) : incoming);
166
+ }
167
+ const op = {
168
+ producerId: command.producerId,
169
+ operationId: command.operationId,
170
+ revision,
171
+ };
172
+ snapshot = pruneLimitsNamespace({
173
+ ...snapshot,
174
+ revision,
175
+ marks,
176
+ tombstones,
177
+ access,
178
+ operationIds: [...snapshot.operationIds, op],
179
+ }, context.now);
180
+ outcomes.push({ ...op, status: 'committed' });
181
+ }
182
+ return { snapshot, outcomes };
183
+ }
@@ -0,0 +1,33 @@
1
+ import type { IdentityBinding } from './identity.js';
2
+ import type { LimitsCommand, LimitsCommandOutcome, LimitsNamespace } from './namespace.js';
3
+ /** Bindings and the namespace snapshot must be read from the same authoritative store view. */
4
+ export interface LimitsPersistenceSnapshot {
5
+ readonly snapshot: LimitsNamespace;
6
+ readonly bindings: readonly IdentityBinding[];
7
+ /** False for a cached or unverifiable view; it cannot restore agreement. */
8
+ readonly authoritative: boolean;
9
+ /** An adapter repaired missing or rewritten namespace state; require a later authoritative read without this flag. */
10
+ readonly degradedAgreement?: boolean;
11
+ }
12
+ export type LimitsPersistenceOutcome = Omit<LimitsCommandOutcome, 'reason'> & {
13
+ readonly reason?: LimitsCommandOutcome['reason'] | 'pool-not-ready';
14
+ };
15
+ export interface LimitsPersistenceCommit extends LimitsPersistenceSnapshot {
16
+ readonly outcomes: readonly LimitsPersistenceOutcome[];
17
+ }
18
+ /**
19
+ * One canonical namespace. Validate commands against current account identities
20
+ * and credential epochs, then merge under the existing store lock. Never
21
+ * implement commit by saving the caller's memory snapshot.
22
+ */
23
+ export interface PersistenceAdapter {
24
+ readonly namespace: string;
25
+ read(previous?: LimitsNamespace): Promise<LimitsPersistenceSnapshot>;
26
+ commit(commands: readonly LimitsCommand[], previous?: LimitsNamespace): Promise<LimitsPersistenceCommit>;
27
+ subscribe?(onChange: () => void): () => void;
28
+ }
29
+ /** A definitive refusal settles commands; an ordinary I/O error leaves them queued. */
30
+ export declare class LimitsPersistenceRefusal extends Error {
31
+ readonly code: 'pool-not-ready' | 'limits-unsupported';
32
+ constructor(code: 'pool-not-ready' | 'limits-unsupported');
33
+ }
@@ -0,0 +1,9 @@
1
+ /** A definitive refusal settles commands; an ordinary I/O error leaves them queued. */
2
+ export class LimitsPersistenceRefusal extends Error {
3
+ code;
4
+ constructor(code) {
5
+ super(code);
6
+ this.code = code;
7
+ this.name = 'LimitsPersistenceRefusal';
8
+ }
9
+ }
@@ -0,0 +1,16 @@
1
+ export type PiWaitResult = 'elapsed' | 'aborted';
2
+ export interface PiWaitOptions {
3
+ /** Forward the Pi stream's options.signal so cancellation ends the wait. */
4
+ signal?: AbortSignal;
5
+ setWorkingMessage: (text?: string) => void;
6
+ }
7
+ /**
8
+ * Wait in the caller's Pi stream without sending or selecting an account.
9
+ * After 'elapsed', the caller must re-check that the account remains eligible,
10
+ * its identity has not been replaced, and its credentials are still available
11
+ * for use. When waiting to reuse the same account's prompt cache, also check
12
+ * that the session's activity record still belongs to that account incarnation
13
+ * and that the wait target does not exceed its cache expiry. Only then send.
14
+ * After 'aborted', end the stream without a refusal; abort never rejects.
15
+ */
16
+ export declare function waitForPi(delayMs: number, options: PiWaitOptions): Promise<PiWaitResult>;
@@ -0,0 +1,51 @@
1
+ import { formatDuration } from './duration.js';
2
+ /**
3
+ * Wait in the caller's Pi stream without sending or selecting an account.
4
+ * After 'elapsed', the caller must re-check that the account remains eligible,
5
+ * its identity has not been replaced, and its credentials are still available
6
+ * for use. When waiting to reuse the same account's prompt cache, also check
7
+ * that the session's activity record still belongs to that account incarnation
8
+ * and that the wait target does not exceed its cache expiry. Only then send.
9
+ * After 'aborted', end the stream without a refusal; abort never rejects.
10
+ */
11
+ export function waitForPi(delayMs, options) {
12
+ if (!Number.isFinite(delayMs) || delayMs < 0) {
13
+ throw new RangeError('Pi wait requires a finite non-negative delay');
14
+ }
15
+ return new Promise((resolve) => {
16
+ const target = Date.now() + delayMs;
17
+ let timer;
18
+ let settled = false;
19
+ const workingMessage = (text) => {
20
+ // A presentation failure must not strand the stream or mask cancellation.
21
+ try {
22
+ options.setWorkingMessage(text);
23
+ }
24
+ catch { }
25
+ };
26
+ const finish = (result) => {
27
+ if (settled)
28
+ return;
29
+ settled = true;
30
+ clearTimeout(timer);
31
+ options.signal?.removeEventListener('abort', abort);
32
+ workingMessage();
33
+ resolve(result);
34
+ };
35
+ const abort = () => finish('aborted');
36
+ const tick = () => {
37
+ const remaining = target - Date.now();
38
+ if (remaining <= 0)
39
+ return finish('elapsed');
40
+ workingMessage(`Waiting for the account limit to reset · ${formatDuration(remaining)} · Esc to cancel`);
41
+ // The callback may itself cancel the stream. Do not arm a timer afterward.
42
+ if (!settled)
43
+ timer = setTimeout(tick, Math.min(1000, remaining));
44
+ };
45
+ options.signal?.addEventListener('abort', abort, { once: true });
46
+ if (options.signal?.aborted)
47
+ abort();
48
+ else
49
+ tick();
50
+ });
51
+ }
@@ -0,0 +1,16 @@
1
+ import type { PoolStore } from '../store/pool.js';
2
+ import { type LimitsRecoveryLogger } from './envelope-loss.js';
3
+ import { type PersistenceAdapter } from './persistence.js';
4
+ export interface PoolLimitsAdapterOptions {
5
+ /** Canonical provider and store namespace, shared by every process using this pool. */
6
+ readonly namespace: string;
7
+ readonly store: PoolStore;
8
+ readonly now?: () => number;
9
+ /** Receives a warning when a detached envelope repair fails. */
10
+ readonly logger?: LimitsRecoveryLogger;
11
+ }
12
+ /**
13
+ * Activate after initialize/load reports ready. Reads never acquire a write
14
+ * lock; recovery is detached and commits merge under the store locks.
15
+ */
16
+ export declare function createPoolLimitsAdapter(options: PoolLimitsAdapterOptions): Promise<PersistenceAdapter>;
@@ -0,0 +1,162 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { isDeepStrictEqual } from 'node:util';
3
+ import { PoolOperationError } from '../store/errors.js';
4
+ import { EnvelopeHistory, EnvelopeRepair, } from './envelope-loss.js';
5
+ import { applyLimitsCommands, createLimitsNamespace, } from './namespace.js';
6
+ import { LimitsPersistenceRefusal, } from './persistence.js';
7
+ function bindingsOf(namespace, rows) {
8
+ return rows.flatMap((row) => row.credentialEpoch === undefined
9
+ ? []
10
+ : [
11
+ {
12
+ account: {
13
+ namespace,
14
+ accountId: row.id,
15
+ // Pool epochs change on replacement, not on refresh or rotation.
16
+ incarnation: String(row.credentialEpoch),
17
+ },
18
+ credentialEpoch: String(row.credentialEpoch),
19
+ ...(row.identity === undefined ? {} : { identity: row.identity }),
20
+ },
21
+ ]);
22
+ }
23
+ function decodeEnvelope(value, namespace, generation) {
24
+ if (value === undefined)
25
+ return createLimitsNamespace(namespace, generation);
26
+ if (value === null ||
27
+ typeof value !== 'object' ||
28
+ !('schemaVersion' in value) ||
29
+ value.schemaVersion !== 1 ||
30
+ !('namespace' in value) ||
31
+ value.namespace !== namespace ||
32
+ !('generation' in value) ||
33
+ typeof value.generation !== 'string' ||
34
+ !('revision' in value) ||
35
+ !Number.isSafeInteger(value.revision) ||
36
+ value.revision < 0 ||
37
+ !('lowWatermark' in value) ||
38
+ !Number.isSafeInteger(value.lowWatermark) ||
39
+ value.lowWatermark < 0 ||
40
+ !('marks' in value) ||
41
+ !Array.isArray(value.marks) ||
42
+ !('tombstones' in value) ||
43
+ !Array.isArray(value.tombstones) ||
44
+ !('operationIds' in value) ||
45
+ !Array.isArray(value.operationIds) ||
46
+ !('access' in value) ||
47
+ !Array.isArray(value.access))
48
+ throw new TypeError('Invalid or unsupported pool limits namespace');
49
+ return value;
50
+ }
51
+ /**
52
+ * Activate after initialize/load reports ready. Reads never acquire a write
53
+ * lock; recovery is detached and commits merge under the store locks.
54
+ */
55
+ export async function createPoolLimitsAdapter(options) {
56
+ const { store, namespace } = options;
57
+ if (!store.updateLimitsNamespace)
58
+ throw new LimitsPersistenceRefusal('limits-unsupported');
59
+ const update = store.updateLimitsNamespace.bind(store);
60
+ const generation = randomUUID();
61
+ const history = new EnvelopeHistory();
62
+ const repair = new EnvelopeRepair(options.logger);
63
+ const now = options.now ?? Date.now;
64
+ const readBindings = async () => {
65
+ const pool = await store.read();
66
+ if (pool.status !== 'ready') {
67
+ if (pool.status === 'error' && pool.kind === 'snapshot-contended')
68
+ throw new Error(pool.reason);
69
+ throw new LimitsPersistenceRefusal('pool-not-ready');
70
+ }
71
+ return bindingsOf(namespace, pool.rows);
72
+ };
73
+ const readEnvelope = async () => {
74
+ const settings = await store.readSettings();
75
+ if (settings.status !== 'ready')
76
+ throw new LimitsPersistenceRefusal('pool-not-ready');
77
+ const envelope = settings.settings.commonAuthLimits;
78
+ return envelope === undefined
79
+ ? undefined
80
+ : decodeEnvelope(envelope, namespace, generation);
81
+ };
82
+ const read = async (previous) => {
83
+ let bindings = await readBindings();
84
+ let snapshot = await readEnvelope();
85
+ let last;
86
+ for (let attempt = 0; attempt < 3; attempt++) {
87
+ const checked = await readBindings();
88
+ const checkedSnapshot = await readEnvelope();
89
+ // A replacement between the envelope and binding reads must not make an
90
+ // old envelope authoritative for a new incarnation. Recheck the envelope
91
+ // too: its generation or revision can change while the rows stay the same.
92
+ // Bounded retries keep a busy writer from delaying a provider request.
93
+ const stable = isDeepStrictEqual(bindings, checked) &&
94
+ isDeepStrictEqual(snapshot, checkedSnapshot);
95
+ last = {
96
+ snapshot: snapshot ?? createLimitsNamespace(namespace, generation),
97
+ bindings,
98
+ authoritative: stable,
99
+ };
100
+ if (stable) {
101
+ if (history.lost(snapshot, previous)) {
102
+ repair.schedule(() => adapter.commit([], previous));
103
+ return {
104
+ snapshot: history.recover(snapshot, previous, namespace, now()),
105
+ bindings,
106
+ authoritative: false,
107
+ degradedAgreement: true,
108
+ };
109
+ }
110
+ if (snapshot)
111
+ history.remember(snapshot);
112
+ return last;
113
+ }
114
+ bindings = checked;
115
+ snapshot = checkedSnapshot;
116
+ }
117
+ return last;
118
+ };
119
+ const adapter = {
120
+ namespace,
121
+ read,
122
+ subscribe: repair.subscribe,
123
+ async commit(commands, previous) {
124
+ let committed;
125
+ try {
126
+ await update((envelope, rows) => {
127
+ const bindings = bindingsOf(namespace, rows);
128
+ const present = envelope === undefined
129
+ ? undefined
130
+ : decodeEnvelope(envelope, namespace, generation);
131
+ const degradedAgreement = history.lost(present, previous);
132
+ const result = applyLimitsCommands(degradedAgreement
133
+ ? history.recover(present, previous, namespace, now())
134
+ : (present ?? createLimitsNamespace(namespace, generation)), commands, {
135
+ now: now(),
136
+ bindings,
137
+ authorizeEpoch: (observed, current) => observed.credentialEpoch === current.credentialEpoch,
138
+ });
139
+ committed = {
140
+ ...result,
141
+ bindings,
142
+ authoritative: true,
143
+ degradedAgreement,
144
+ };
145
+ return result.snapshot;
146
+ });
147
+ }
148
+ catch (error) {
149
+ if (error instanceof PoolOperationError &&
150
+ (error.kind === 'pending-migration' || error.kind === 'load-error'))
151
+ throw new LimitsPersistenceRefusal('pool-not-ready');
152
+ throw error;
153
+ }
154
+ if (!committed)
155
+ throw new Error('Pool limits mutator was not called');
156
+ history.remember(committed.snapshot, previous);
157
+ return committed;
158
+ },
159
+ };
160
+ await read();
161
+ return adapter;
162
+ }
@@ -0,0 +1,11 @@
1
+ import type { LimitAxes } from './axes.js';
2
+ export declare const confirmedAffinity: LimitAxes;
3
+ export declare const earliestPoolEngine: LimitAxes;
4
+ export declare const windowRouter: LimitAxes;
5
+ export declare const statusVaultOrder: LimitAxes;
6
+ export declare const limitPresets: {
7
+ 'confirmed-affinity': LimitAxes;
8
+ 'earliest-pool-engine': LimitAxes;
9
+ 'window-router': LimitAxes;
10
+ 'status-vault-order': LimitAxes;
11
+ };