@cortexkit/common-auth 0.33.0 → 0.35.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 (108) 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 +69 -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 +146 -0
  25. package/dist/limits/decide.js +425 -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 +59 -0
  31. package/dist/limits/families.js +149 -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 +45 -0
  39. package/dist/limits/index.js +26 -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 +69 -0
  45. package/dist/limits/marker.js +107 -0
  46. package/dist/limits/merge-laws.d.ts +15 -0
  47. package/dist/limits/merge-laws.js +31 -0
  48. package/dist/limits/namespace.d.ts +92 -0
  49. package/dist/limits/namespace.js +191 -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 +240 -0
  58. package/dist/limits/registry.d.ts +61 -0
  59. package/dist/limits/registry.js +478 -0
  60. package/dist/limits/request-history.d.ts +79 -0
  61. package/dist/limits/request-history.js +120 -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/unconfirmed-retain-counter.d.ts +13 -0
  73. package/dist/limits/unconfirmed-retain-counter.js +41 -0
  74. package/dist/limits/vault-adapter.d.ts +16 -0
  75. package/dist/limits/vault-adapter.js +123 -0
  76. package/dist/limits/vault.d.ts +1 -0
  77. package/dist/limits/vault.js +1 -0
  78. package/dist/limits/wake.d.ts +21 -0
  79. package/dist/limits/wake.js +47 -0
  80. package/dist/limits/wording.d.ts +25 -0
  81. package/dist/limits/wording.js +114 -0
  82. package/dist/opencode2/index.d.ts +1 -1
  83. package/dist/opencode2/install.d.ts +2 -2
  84. package/dist/opencode2/install.js +161 -18
  85. package/dist/opencode2/types.d.ts +95 -9
  86. package/dist/routing/admission.d.ts +7 -2
  87. package/dist/routing/admission.js +17 -7
  88. package/dist/routing-accessor/handle.d.ts +1 -0
  89. package/dist/routing-accessor/handle.js +10 -0
  90. package/dist/routing-accessor/index.d.ts +13 -3
  91. package/dist/routing-accessor/index.js +11 -10
  92. package/dist/rpc/port-file.d.ts +12 -3
  93. package/dist/rpc/port-file.js +46 -4
  94. package/dist/store/attribution.js +3 -2
  95. package/dist/store/errors.d.ts +1 -1
  96. package/dist/store/hooks.d.ts +5 -1
  97. package/dist/store/hooks.js +20 -5
  98. package/dist/store/index.d.ts +1 -0
  99. package/dist/store/limits-namespace.d.ts +7 -0
  100. package/dist/store/limits-namespace.js +34 -0
  101. package/dist/store/pool.d.ts +10 -1
  102. package/dist/store/pool.js +2 -0
  103. package/dist/store/provider-state.js +5 -5
  104. package/dist/store/refresh.js +1 -1
  105. package/dist/store/schema.js +9 -4
  106. package/dist/store/settings.d.ts +2 -0
  107. package/dist/store/settings.js +11 -4
  108. package/package.json +10 -2
@@ -0,0 +1,478 @@
1
+ import { AsyncResource } from 'node:async_hooks';
2
+ import { createSessionActivityStore } from './activity.js';
3
+ import { isIdentityCompatible, retainVerifiedIdentity } from './identity.js';
4
+ import { applyLimitsCommands, pruneLimitsNamespace } from './namespace.js';
5
+ import { LimitsPersistenceRefusal } from './persistence.js';
6
+ import { sameAccount } from './request-history.js';
7
+ export const LIMITS_REGISTRY_KEY = Symbol.for('@cortexkit/common-auth/limits-registry/schema-v1');
8
+ const PREFIX = '@cortexkit/common-auth/limits-registry/schema-v';
9
+ const RELOAD_MS = 1000;
10
+ const IDLE_MS = 5000;
11
+ // Run timers and I/O in the module's async context rather than inheriting a
12
+ // caller's lock-holding callback context, which can prohibit store re-entry.
13
+ const detached = new AsyncResource('common-auth-limits');
14
+ const clock = {
15
+ now: () => Date.now(),
16
+ setTimeout(callback, delay) {
17
+ const timer = setTimeout(callback, delay);
18
+ timer.unref?.();
19
+ return timer;
20
+ },
21
+ clearTimeout: (timer) => clearTimeout(timer),
22
+ };
23
+ /** Publish a recovery fence even when expiry already removed the observed timer.
24
+ * Capture binding/baseRevision with observe before the probe; dispatch to that
25
+ * account joins the clear acknowledgment through beforeDispatch, not here.
26
+ */
27
+ export function clearLimitsAfterProbe(registry, input) {
28
+ registry.enqueue({ ...input, type: 'clear' }, 'success');
29
+ }
30
+ function schemaRegistry() {
31
+ for (const symbol of Object.getOwnPropertySymbols(globalThis)) {
32
+ const key = Symbol.keyFor(symbol);
33
+ if (key?.startsWith(PREFIX) && symbol !== LIMITS_REGISTRY_KEY) {
34
+ throw new Error('limits-schema-mismatch');
35
+ }
36
+ }
37
+ const current = Reflect.get(globalThis, LIMITS_REGISTRY_KEY);
38
+ if (current) {
39
+ if (current.schemaVersion !== 1 || !(current.namespaces instanceof Map))
40
+ throw new Error('limits-schema-mismatch');
41
+ return current;
42
+ }
43
+ const created = { schemaVersion: 1, namespaces: new Map() };
44
+ Reflect.set(globalThis, LIMITS_REGISTRY_KEY, created);
45
+ return created;
46
+ }
47
+ function opId(command) {
48
+ return JSON.stringify([command.producerId, command.operationId]);
49
+ }
50
+ class Runtime {
51
+ adapter;
52
+ clock;
53
+ restrictive;
54
+ listeners = new Set();
55
+ owners = 0;
56
+ activity = createSessionActivityStore();
57
+ journal = new Map();
58
+ failed = new Set();
59
+ restrictions = new Map();
60
+ snapshot;
61
+ recoveryView;
62
+ bindings = [];
63
+ lastReloadAt = Number.NEGATIVE_INFINITY;
64
+ lastActivity = Number.NEGATIVE_INFINITY;
65
+ lastReadAttempt = Number.NEGATIVE_INFINITY;
66
+ generation = 0;
67
+ degradedAgreement = false;
68
+ lastFailure;
69
+ dirty = true;
70
+ live = false;
71
+ publicationTimer;
72
+ reloadTimer;
73
+ unsubscribe;
74
+ reading;
75
+ writing;
76
+ handoff = Promise.resolve();
77
+ constructor(options) {
78
+ this.adapter = options.adapter;
79
+ this.clock = options.clock ?? clock;
80
+ this.restrictive = options.isAccessRestrictive;
81
+ }
82
+ fail(error) {
83
+ this.degradedAgreement = true;
84
+ this.lastFailure = error;
85
+ }
86
+ reconcile(view) {
87
+ if (view.snapshot.schemaVersion !== 1 ||
88
+ view.snapshot.namespace !== this.adapter.namespace)
89
+ throw new Error('limits-schema-mismatch');
90
+ if (!view.authoritative) {
91
+ // Use repaired restrictions for dispatch, but never expose an unwritten
92
+ // recovery revision as a durable basis for new commands.
93
+ if (view.degradedAgreement &&
94
+ this.snapshot &&
95
+ view.snapshot.revision > this.snapshot.revision)
96
+ this.recoveryView = view;
97
+ this.fail(new Error('limits-unverifiable-snapshot'));
98
+ return false;
99
+ }
100
+ // A read started before a commit may finish after it. Never roll that commit back.
101
+ if (this.snapshot &&
102
+ view.snapshot.generation === this.snapshot.generation &&
103
+ view.snapshot.revision < this.snapshot.revision)
104
+ return false;
105
+ this.snapshot = view.snapshot;
106
+ this.recoveryView = undefined;
107
+ this.bindings = view.bindings.map((binding) => {
108
+ const previous = this.bindings.find((b) => sameAccount(b.account, binding.account));
109
+ return previous ? retainVerifiedIdentity(previous, binding) : binding;
110
+ });
111
+ for (const [id, restriction] of this.restrictions) {
112
+ const command = restriction.command;
113
+ const binding = this.bindings.find((b) => sameAccount(b.account, command.binding.account));
114
+ const access = this.snapshot.access.find((a) => sameAccount(a.account, command.binding.account));
115
+ if (!binding ||
116
+ !isIdentityCompatible(binding, command.binding) ||
117
+ (command.type === 'access' &&
118
+ access &&
119
+ access.committedRevision > restriction.revision &&
120
+ access.eligibilityStateUpdatedAt >= command.eligibilityStateUpdatedAt)) {
121
+ this.restrictions.delete(id);
122
+ }
123
+ }
124
+ if (view.degradedAgreement)
125
+ this.fail(new Error('limits-envelope-recovered'));
126
+ return !view.degradedAgreement;
127
+ }
128
+ touch() {
129
+ this.lastActivity = this.clock.now();
130
+ this.armReload();
131
+ }
132
+ cancelTimers() {
133
+ if (this.publicationTimer !== undefined)
134
+ this.clock.clearTimeout(this.publicationTimer);
135
+ if (this.reloadTimer !== undefined)
136
+ this.clock.clearTimeout(this.reloadTimer);
137
+ this.publicationTimer = this.reloadTimer = undefined;
138
+ }
139
+ schedulePublish(delay) {
140
+ if (!this.live)
141
+ return;
142
+ if (this.publicationTimer !== undefined)
143
+ this.clock.clearTimeout(this.publicationTimer);
144
+ detached.runInAsyncScope(() => {
145
+ this.publicationTimer = this.clock.setTimeout(() => {
146
+ this.publicationTimer = undefined;
147
+ detached.runInAsyncScope(() => {
148
+ void this.flush();
149
+ });
150
+ }, delay);
151
+ });
152
+ }
153
+ armReload() {
154
+ if (!this.live ||
155
+ this.reading ||
156
+ this.reloadTimer !== undefined ||
157
+ this.clock.now() - this.lastActivity >= IDLE_MS)
158
+ return;
159
+ detached.runInAsyncScope(() => {
160
+ this.reloadTimer = this.clock.setTimeout(() => {
161
+ this.reloadTimer = undefined;
162
+ if (!this.live || this.clock.now() - this.lastActivity >= IDLE_MS)
163
+ return;
164
+ detached.runInAsyncScope(() => {
165
+ void this.reload();
166
+ });
167
+ }, Math.max(0, this.lastReadAttempt + RELOAD_MS - this.clock.now()));
168
+ });
169
+ }
170
+ async start(adapter) {
171
+ this.adapter = adapter;
172
+ this.live = true;
173
+ const generation = ++this.generation;
174
+ await this.reload();
175
+ if (!this.snapshot)
176
+ throw this.lastFailure ?? new Error('limits-hydration-failed');
177
+ this.unsubscribe = adapter.subscribe?.(() => {
178
+ if (!this.live || this.generation !== generation)
179
+ return;
180
+ this.dirty = true;
181
+ detached.runInAsyncScope(() => {
182
+ void this.reload();
183
+ });
184
+ });
185
+ if (this.journal.size)
186
+ this.schedulePublish(0);
187
+ }
188
+ reload() {
189
+ if (this.reading)
190
+ return this.reading;
191
+ const started = this.clock.now();
192
+ this.lastReadAttempt = started;
193
+ this.reading = detached
194
+ .runInAsyncScope(async () => {
195
+ try {
196
+ this.dirty = false;
197
+ const clean = this.reconcile(await this.adapter.read(this.snapshot));
198
+ if (clean) {
199
+ this.lastReloadAt = started;
200
+ if (!this.journal.size &&
201
+ !this.failed.size &&
202
+ !this.restrictions.size) {
203
+ this.degradedAgreement = false;
204
+ this.lastFailure = undefined;
205
+ }
206
+ }
207
+ }
208
+ catch (error) {
209
+ this.dirty = true;
210
+ this.fail(error);
211
+ }
212
+ })
213
+ .finally(() => {
214
+ this.reading = undefined;
215
+ this.armReload();
216
+ });
217
+ return this.reading;
218
+ }
219
+ provisional() {
220
+ const snapshot = this.recoveryView?.snapshot ?? this.snapshot;
221
+ const pending = [...this.journal.values()]
222
+ .map((p) => p.command)
223
+ .filter((c) => c.type === 'mark');
224
+ const provisional = applyLimitsCommands(pruneLimitsNamespace(snapshot, this.clock.now()), pending, {
225
+ now: this.clock.now(),
226
+ bindings: this.bindings,
227
+ authorizeEpoch: (a, b) => a.credentialEpoch === b.credentialEpoch,
228
+ }).snapshot;
229
+ // Pending evidence may restrict routing, but cannot invent durable revisions
230
+ // or acknowledged operation ids for subsequent observations.
231
+ return {
232
+ ...this.snapshot,
233
+ marks: provisional.marks,
234
+ tombstones: snapshot.tombstones,
235
+ access: snapshot.access,
236
+ };
237
+ }
238
+ enqueue(command, event) {
239
+ if (command.binding.account.namespace !== this.adapter.namespace)
240
+ throw new Error('wrong-namespace');
241
+ const id = opId(command);
242
+ if (this.journal.has(id) ||
243
+ this.snapshot.operationIds.some((op) => opId(op) === id))
244
+ return;
245
+ this.journal.set(id, { command: structuredClone(command), event });
246
+ this.touch();
247
+ // A control must include all earlier evidence, even if the mark debounce has not fired.
248
+ const hasControl = [...this.journal.values()].some((p) => p.command.type !== 'mark');
249
+ this.schedulePublish(hasControl ? 0 : RELOAD_MS);
250
+ }
251
+ flush() {
252
+ if (this.writing)
253
+ return this.writing;
254
+ if (!this.journal.size)
255
+ return Promise.resolve();
256
+ this.writing = detached
257
+ .runInAsyncScope(async () => {
258
+ let batch = [...this.journal.values()];
259
+ while (batch.length) {
260
+ try {
261
+ const result = await this.adapter.commit(batch.map((p) => p.command), this.snapshot);
262
+ this.reconcile(result);
263
+ if (!result.authoritative)
264
+ throw new Error('limits-unverifiable-commit');
265
+ for (const pending of batch) {
266
+ const outcome = result.outcomes.find((o) => opId(o) === opId(pending.command));
267
+ if (!outcome)
268
+ throw new Error('limits-missing-acknowledgement');
269
+ this.settle(pending, outcome);
270
+ }
271
+ }
272
+ catch (error) {
273
+ if (error instanceof LimitsPersistenceRefusal &&
274
+ error.code === 'pool-not-ready') {
275
+ for (const pending of batch)
276
+ this.settle(pending, {
277
+ ...pending.command,
278
+ status: 'rejected',
279
+ reason: 'pool-not-ready',
280
+ });
281
+ }
282
+ else {
283
+ for (const pending of batch)
284
+ if (this.journal.has(opId(pending.command)))
285
+ this.failed.add(opId(pending.command));
286
+ this.fail(error);
287
+ break;
288
+ }
289
+ }
290
+ const remaining = [...this.journal.values()];
291
+ const lastControl = remaining.findLastIndex((p) => p.command.type !== 'mark');
292
+ // Marks arriving while adapter.commit() runs retain their own debounce.
293
+ // Only a later control needs earlier marks in its acknowledgement.
294
+ batch = remaining.slice(0, lastControl + 1);
295
+ }
296
+ })
297
+ .finally(() => {
298
+ this.writing = undefined;
299
+ if (this.journal.size && this.live)
300
+ this.schedulePublish(RELOAD_MS);
301
+ if (this.degradedAgreement && this.live)
302
+ this.armReload();
303
+ });
304
+ return this.writing;
305
+ }
306
+ settle(pending, outcome) {
307
+ const command = pending.command;
308
+ const id = opId(command);
309
+ this.journal.delete(id);
310
+ this.failed.delete(id);
311
+ if (outcome.status === 'rejected') {
312
+ this.fail(new Error(outcome.reason ?? 'limits-command-rejected'));
313
+ if (command.type === 'access' && this.restrictive(command.state)) {
314
+ this.restrictions.set(id, { command, revision: this.snapshot.revision });
315
+ // Recovery rejects pre-barrier observations. Restrictive access alone
316
+ // can be resubmitted at that barrier without granting availability.
317
+ // Repeated competing recoveries must not keep a dispatch waiting forever;
318
+ // after three retries, keep the account blocked and agreement degraded
319
+ // instead of retrying again.
320
+ if (outcome.reason === 'below-watermark' &&
321
+ command.baseRevision < this.snapshot.lowWatermark &&
322
+ (pending.recoveryRetries ?? 0) < 3) {
323
+ this.journal.set(id, {
324
+ ...pending,
325
+ recoveryRetries: (pending.recoveryRetries ?? 0) + 1,
326
+ command: { ...command, baseRevision: this.snapshot.revision },
327
+ });
328
+ }
329
+ }
330
+ for (const listener of this.listeners) {
331
+ try {
332
+ listener.onRejected?.(command, outcome);
333
+ }
334
+ catch {
335
+ /* Observers cannot change settlement. */
336
+ }
337
+ }
338
+ }
339
+ else if (outcome.revision !== undefined &&
340
+ (command.type === 'mark' || pending.event === 'success')) {
341
+ for (const listener of this.listeners) {
342
+ try {
343
+ listener.onEvent?.({
344
+ type: command.type === 'mark' ? 'mark' : 'success',
345
+ command,
346
+ revision: outcome.revision,
347
+ });
348
+ }
349
+ catch {
350
+ /* Observers cannot change settlement. */
351
+ }
352
+ }
353
+ }
354
+ }
355
+ async beforeDispatch(binding) {
356
+ this.touch();
357
+ const controls = () => [...this.journal.values()].some((p) => p.command.type !== 'mark' &&
358
+ sameAccount(p.command.binding.account, binding.account));
359
+ if (controls())
360
+ await this.flush();
361
+ if (this.dirty || this.clock.now() - this.lastReloadAt >= RELOAD_MS)
362
+ await this.reload();
363
+ const current = (this.recoveryView?.bindings ?? this.bindings).find((b) => sameAccount(b.account, binding.account));
364
+ const snapshot = this.provisional();
365
+ return {
366
+ snapshot,
367
+ blocked: controls() ||
368
+ !current ||
369
+ !isIdentityCompatible(current, binding) ||
370
+ [...this.restrictions.values()].some((r) => sameAccount(r.command.binding.account, binding.account)) ||
371
+ [...this.snapshot.access, ...snapshot.access].some((a) => sameAccount(a.account, binding.account) &&
372
+ this.restrictive(a.state)),
373
+ };
374
+ }
375
+ async stop() {
376
+ this.live = false;
377
+ this.generation++;
378
+ this.cancelTimers();
379
+ await this.flush();
380
+ await this.reading;
381
+ this.unsubscribe?.();
382
+ this.unsubscribe = undefined;
383
+ this.cancelTimers();
384
+ }
385
+ }
386
+ /** Shared owners use one journal/listener; a last-owner replacement waits for handoff. */
387
+ export async function acquireLimitsRegistry(options) {
388
+ const registry = schemaRegistry();
389
+ let runtime = registry.namespaces.get(options.adapter.namespace);
390
+ if (!runtime) {
391
+ runtime = new Runtime(options);
392
+ registry.namespaces.set(options.adapter.namespace, runtime);
393
+ }
394
+ const state = runtime;
395
+ const listener = {
396
+ onEvent: options.onEvent,
397
+ onRejected: options.onRejected,
398
+ };
399
+ // Reserve the owner synchronously so concurrent acquisitions cannot start two listeners.
400
+ const first = state.owners++ === 0;
401
+ state.listeners.add(listener);
402
+ if (first)
403
+ state.handoff = state.handoff
404
+ .catch(() => { })
405
+ .then(() => state.start(options.adapter));
406
+ try {
407
+ await state.handoff;
408
+ }
409
+ catch (error) {
410
+ state.listeners.delete(listener);
411
+ state.owners--;
412
+ state.live = false;
413
+ state.cancelTimers();
414
+ throw error;
415
+ }
416
+ let disposed = false;
417
+ const active = () => {
418
+ if (disposed)
419
+ throw new Error('limits-registry-disposed');
420
+ };
421
+ return {
422
+ get snapshot() {
423
+ active();
424
+ return state.provisional();
425
+ },
426
+ get lastReloadAt() {
427
+ return state.lastReloadAt;
428
+ },
429
+ get degradedAgreement() {
430
+ return state.degradedAgreement;
431
+ },
432
+ get lastFailure() {
433
+ return state.lastFailure;
434
+ },
435
+ get pendingCommands() {
436
+ return state.journal.size;
437
+ },
438
+ activity: state.activity,
439
+ observe(binding) {
440
+ active();
441
+ return {
442
+ binding: structuredClone(binding),
443
+ baseRevision: state.snapshot.revision,
444
+ };
445
+ },
446
+ enqueue(command, event) {
447
+ active();
448
+ state.enqueue(command, event);
449
+ },
450
+ beforeDispatch(binding) {
451
+ active();
452
+ return state.beforeDispatch(binding);
453
+ },
454
+ flush() {
455
+ active();
456
+ return state.flush();
457
+ },
458
+ reload() {
459
+ active();
460
+ return state.reload();
461
+ },
462
+ dispose() {
463
+ if (disposed)
464
+ return state.handoff;
465
+ disposed = true;
466
+ state.owners--;
467
+ if (!state.owners) {
468
+ state.handoff = state.handoff
469
+ .then(() => state.stop())
470
+ .finally(() => state.listeners.delete(listener));
471
+ }
472
+ else {
473
+ state.listeners.delete(listener);
474
+ }
475
+ return state.handoff;
476
+ },
477
+ };
478
+ }
@@ -0,0 +1,79 @@
1
+ import type { Scope } from './scope.js';
2
+ import type { AccountKey, LimitKind } from './signal.js';
3
+ export declare function sameAccount(a: AccountKey, b: AccountKey): boolean;
4
+ export interface RequestExclusion {
5
+ readonly account: AccountKey;
6
+ readonly scope: Scope;
7
+ }
8
+ export interface RetainHistory {
9
+ readonly account: AccountKey;
10
+ readonly count: number;
11
+ readonly startedAt: number;
12
+ readonly lastRetainedAt: number;
13
+ }
14
+ export interface RequestHistory {
15
+ /** A request/turn token, not a session id. */
16
+ readonly requestId: string;
17
+ readonly originalUrl: string;
18
+ readonly requestStartedAt: number;
19
+ readonly saw429: boolean;
20
+ readonly sawPaymentBalance?: boolean;
21
+ readonly lastStatus?: number;
22
+ readonly tried: readonly RequestExclusion[];
23
+ readonly excludedForRequest: readonly RequestExclusion[];
24
+ readonly retains: readonly RetainHistory[];
25
+ readonly retainedAttempts: readonly string[];
26
+ readonly excludedAttempts: readonly string[];
27
+ readonly switchedAttempts: readonly string[];
28
+ readonly switches: number;
29
+ readonly blockedSince?: number;
30
+ }
31
+ export declare function createRequestHistory(input: {
32
+ readonly requestId: string;
33
+ readonly originalUrl: string;
34
+ readonly clockNow: number;
35
+ }): RequestHistory;
36
+ export declare function isRequestExcluded(history: RequestHistory, account: AccountKey, scope: Scope): boolean;
37
+ export type RequestHistoryEvent = {
38
+ readonly type: 'response';
39
+ readonly account: AccountKey;
40
+ readonly scope: Scope;
41
+ readonly status?: number;
42
+ readonly kind?: LimitKind;
43
+ } | {
44
+ readonly type: 'retain';
45
+ readonly account: AccountKey;
46
+ readonly attemptId: string;
47
+ readonly clockNow: number;
48
+ readonly cause: 'unconfirmed-limit' | 'credential-recovery';
49
+ } | {
50
+ readonly type: 'exclude';
51
+ readonly account: AccountKey;
52
+ readonly scope: Scope;
53
+ readonly attemptId: string;
54
+ } | {
55
+ readonly type: 'switch';
56
+ readonly attemptId: string;
57
+ } | {
58
+ readonly type: 'blocked';
59
+ readonly clockNow: number;
60
+ } | {
61
+ readonly type: 'selected';
62
+ };
63
+ /** Retain/exclude/switch events are committed by the executor, not by polling. */
64
+ export declare function reduceRequestHistory(history: RequestHistory, event: RequestHistoryEvent): RequestHistory;
65
+ export declare const REQUEST_EXCLUSION_EFFECTS: Readonly<{
66
+ readonly refundHybridToken: true;
67
+ readonly cancelDiscardedBody: true;
68
+ readonly addMark: false;
69
+ readonly addCooldown: false;
70
+ readonly penalizeHealth: false;
71
+ readonly chargeSwitch: false;
72
+ }>;
73
+ /** Run the returned effects once, then reselect with the returned history. */
74
+ export declare function commitRequestExclusion(history: RequestHistory, entry: RequestExclusion & {
75
+ readonly attemptId: string;
76
+ }): {
77
+ readonly history: RequestHistory;
78
+ readonly effects?: typeof REQUEST_EXCLUSION_EFFECTS;
79
+ };
@@ -0,0 +1,120 @@
1
+ export function sameAccount(a, b) {
2
+ return (a.namespace === b.namespace &&
3
+ a.accountId === b.accountId &&
4
+ a.incarnation === b.incarnation);
5
+ }
6
+ function sameScope(a, b) {
7
+ if (a.kind !== b.kind)
8
+ return false;
9
+ if (a.kind === 'model')
10
+ return b.kind === 'model' && a.model === b.model;
11
+ if (a.kind === 'family')
12
+ return b.kind === 'family' && a.family === b.family;
13
+ return true;
14
+ }
15
+ export function createRequestHistory(input) {
16
+ return {
17
+ requestId: input.requestId,
18
+ originalUrl: input.originalUrl,
19
+ requestStartedAt: input.clockNow,
20
+ saw429: false,
21
+ tried: [],
22
+ excludedForRequest: [],
23
+ retains: [],
24
+ retainedAttempts: [],
25
+ excludedAttempts: [],
26
+ switchedAttempts: [],
27
+ switches: 0,
28
+ };
29
+ }
30
+ export function isRequestExcluded(history, account, scope) {
31
+ return history.excludedForRequest.some((entry) => sameAccount(entry.account, account) && sameScope(entry.scope, scope));
32
+ }
33
+ /** Retain/exclude/switch events are committed by the executor, not by polling. */
34
+ export function reduceRequestHistory(history, event) {
35
+ switch (event.type) {
36
+ case 'response': {
37
+ const tried = history.tried.some((entry) => sameAccount(entry.account, event.account) &&
38
+ sameScope(entry.scope, event.scope))
39
+ ? history.tried
40
+ : [
41
+ ...history.tried,
42
+ { account: { ...event.account }, scope: { ...event.scope } },
43
+ ];
44
+ return {
45
+ ...history,
46
+ tried,
47
+ saw429: history.saw429 || event.status === 429,
48
+ ...(event.kind === 'payment-balance'
49
+ ? { sawPaymentBalance: true }
50
+ : {}),
51
+ lastStatus: event.status,
52
+ };
53
+ }
54
+ case 'retain': {
55
+ if (event.cause === 'credential-recovery' ||
56
+ history.retainedAttempts.includes(event.attemptId))
57
+ return history;
58
+ const previous = history.retains.find((entry) => sameAccount(entry.account, event.account));
59
+ return {
60
+ ...history,
61
+ retainedAttempts: [...history.retainedAttempts, event.attemptId],
62
+ retains: [
63
+ ...history.retains.filter((entry) => !sameAccount(entry.account, event.account)),
64
+ {
65
+ account: { ...event.account },
66
+ count: (previous?.count ?? 0) + 1,
67
+ startedAt: previous?.startedAt ?? event.clockNow,
68
+ lastRetainedAt: event.clockNow,
69
+ },
70
+ ],
71
+ };
72
+ }
73
+ case 'exclude':
74
+ if (history.excludedAttempts.includes(event.attemptId))
75
+ return history;
76
+ return {
77
+ ...history,
78
+ excludedAttempts: [...history.excludedAttempts, event.attemptId],
79
+ excludedForRequest: isRequestExcluded(history, event.account, event.scope)
80
+ ? history.excludedForRequest
81
+ : [
82
+ ...history.excludedForRequest,
83
+ { account: { ...event.account }, scope: { ...event.scope } },
84
+ ],
85
+ };
86
+ case 'switch':
87
+ return history.switchedAttempts.includes(event.attemptId)
88
+ ? history
89
+ : {
90
+ ...history,
91
+ switchedAttempts: [...history.switchedAttempts, event.attemptId],
92
+ switches: history.switches + 1,
93
+ };
94
+ case 'blocked':
95
+ return history.blockedSince === undefined
96
+ ? { ...history, blockedSince: event.clockNow }
97
+ : history;
98
+ case 'selected': {
99
+ const { blockedSince: _, ...selected } = history;
100
+ return selected;
101
+ }
102
+ }
103
+ }
104
+ export const REQUEST_EXCLUSION_EFFECTS = Object.freeze({
105
+ refundHybridToken: true,
106
+ cancelDiscardedBody: true,
107
+ addMark: false,
108
+ addCooldown: false,
109
+ penalizeHealth: false,
110
+ chargeSwitch: false,
111
+ });
112
+ /** Run the returned effects once, then reselect with the returned history. */
113
+ export function commitRequestExclusion(history, entry) {
114
+ if (history.excludedAttempts.includes(entry.attemptId))
115
+ return { history };
116
+ return {
117
+ history: reduceRequestHistory(history, { type: 'exclude', ...entry }),
118
+ effects: REQUEST_EXCLUSION_EFFECTS,
119
+ };
120
+ }
@@ -0,0 +1,21 @@
1
+ export interface ResetSource {
2
+ readonly source: string;
3
+ readonly value: number | undefined;
4
+ readonly unit: 'delay-ms' | 'epoch-ms';
5
+ readonly zero: 'accept' | 'skip';
6
+ }
7
+ export interface ResolvedReset {
8
+ readonly resetAt: number;
9
+ readonly source: string;
10
+ }
11
+ /** First usable source wins; a default is just another explicitly ordered source. */
12
+ export declare function resolveReset(sources: readonly ResetSource[], now: number): ResolvedReset | undefined;
13
+ /** Only a window listed in lendable may supply its own cached reset. */
14
+ export declare function resolveNamedWindowReset(input: {
15
+ readonly now: number;
16
+ readonly explicitResetAt?: number;
17
+ readonly window: string;
18
+ readonly lendable: readonly string[];
19
+ readonly cached: Readonly<Record<string, number | undefined>>;
20
+ readonly defaultMs: number;
21
+ }): ResolvedReset | undefined;