@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,383 @@
1
+ import { MAX_SAME_ACCOUNT_HOLD_MS } from './hold.js';
2
+ import { holdDelayMs } from './jitter.js';
3
+ import { isRequestExcluded, REQUEST_EXCLUSION_EFFECTS, reduceRequestHistory, sameAccount, } from './request-history.js';
4
+ import { terminalRefusalDecision, terminalWaitDisabled } from './terminal.js';
5
+ import { liftedWindowsForWake, waitCheckpoint } from './wake.js';
6
+ function finiteFuture(value, now) {
7
+ return value !== undefined && Number.isFinite(value) && value > now;
8
+ }
9
+ function continuationRetry(facts, axes) {
10
+ return axes.execution === 'engine' && facts.phase === 'after-limit'
11
+ ? 'veto'
12
+ : 'leave';
13
+ }
14
+ function refusal(facts, axes, history, reason, metadata) {
15
+ const terminal = metadata && terminalRefusalDecision(facts, axes, history, metadata);
16
+ if (terminal)
17
+ return terminal;
18
+ const policy = axes.refusals[reason][facts.host];
19
+ return {
20
+ action: 'refuse',
21
+ reason,
22
+ family: metadata?.family ?? policy.family,
23
+ messageKey: metadata?.messageKey ?? policy.messageKey,
24
+ retryable: metadata?.retryable ?? policy.retryable,
25
+ hostRetry: metadata?.hostRetry ?? policy.hostRetry,
26
+ history,
27
+ ...(metadata?.retryAfterMs === undefined
28
+ ? {}
29
+ : { retryAfterMs: metadata.retryAfterMs }),
30
+ ...(metadata?.resetAt === undefined ? {} : { resetAt: metadata.resetAt }),
31
+ };
32
+ }
33
+ function hold(facts, axes, history, current, windows) {
34
+ const bound = facts.hold;
35
+ if (axes.shortLimit.holdBound === 'disabled' ||
36
+ (facts.host === 'opencode2' &&
37
+ (facts.hostPhase !== 'retry' ||
38
+ facts.remainingRetries === undefined ||
39
+ !(facts.remainingRetries >= 1))) ||
40
+ !current?.admitted ||
41
+ !bound ||
42
+ bound.maxWaitMs <= 0 ||
43
+ Number.isNaN(bound.maxWaitMs) ||
44
+ !Number.isFinite(bound.cacheExpiresAt) ||
45
+ (bound.maxDelayMs !== undefined &&
46
+ (!Number.isFinite(bound.maxDelayMs) || bound.maxDelayMs < 0)) ||
47
+ !windows.length ||
48
+ windows.some((window) => !finiteFuture(window.resetAt, facts.now)))
49
+ return undefined;
50
+ const resetAt = Math.max(...windows.map((window) => window.resetAt));
51
+ const delayMs = axes.shortLimit.jitter === 'session-sha256'
52
+ ? holdDelayMs(facts.sessionId, resetAt - facts.now)
53
+ : resetAt - facts.now;
54
+ const target = facts.now + delayMs;
55
+ if (!Number.isFinite(target) ||
56
+ target > Math.min(bound.cacheExpiresAt, facts.now + bound.maxWaitMs) ||
57
+ (facts.host === 'opencode2' && delayMs > MAX_SAME_ACCOUNT_HOLD_MS) ||
58
+ (bound.maxDelayMs !== undefined && delayMs > bound.maxDelayMs))
59
+ return undefined;
60
+ return {
61
+ action: 'hold',
62
+ account: current.account,
63
+ delayMs,
64
+ retryAfterMs: delayMs,
65
+ target,
66
+ checkpoint: waitCheckpoint(current.account, facts.now, windows),
67
+ reason: 'confirmed-limit',
68
+ retryable: true,
69
+ hostRetry: facts.phase === 'pre-send' ? 'leave' : continuationRetry(facts, axes),
70
+ history,
71
+ };
72
+ }
73
+ function poolWait(facts, axes, history, candidates) {
74
+ const policy = axes.poolWaiting;
75
+ if (policy.kind === 'off' || !candidates.length)
76
+ return undefined;
77
+ history = reduceRequestHistory(history, {
78
+ type: 'blocked',
79
+ clockNow: facts.clockNow,
80
+ });
81
+ const times = candidates
82
+ .map((candidate) => {
83
+ const blockers = candidate.blockers.filter((blocker) => !(blocker.kind === 'soft' &&
84
+ candidates.length === 1 &&
85
+ policy.singleEligibleSoftExemption));
86
+ if (blockers.some((blocker) => !finiteFuture(blocker.until, facts.now)))
87
+ return undefined;
88
+ return blockers.length
89
+ ? {
90
+ candidate,
91
+ time: Math.max(...blockers.map((blocker) => blocker.until)),
92
+ }
93
+ : undefined;
94
+ })
95
+ .filter((entry) => entry !== undefined);
96
+ const earliest = times.reduce((best, entry) => (!best || entry.time < best.time ? entry : best), undefined);
97
+ const proposed = earliest
98
+ ? earliest.time - facts.now
99
+ : candidates.some((candidate) => candidate.blockers.some((blocker) => blocker.kind !== 'soft'))
100
+ ? policy.hardFallbackMs
101
+ : undefined;
102
+ const budget = facts.poolWaitBudgetMs ?? policy.budgetMs;
103
+ const elapsed = facts.clockNow - (history.blockedSince ?? facts.clockNow);
104
+ if (budget > 0 &&
105
+ (elapsed >= budget || (proposed !== undefined && proposed > budget)))
106
+ return refusal(facts, axes, history, 'quota', facts.terminal);
107
+ const remaining = policy.requestDeadlineMs - (facts.clockNow - history.requestStartedAt);
108
+ if (remaining <= 0)
109
+ return refusal(facts, axes, history, 'incomplete');
110
+ if (proposed === undefined)
111
+ return refusal(facts, axes, history, 'quota', facts.terminal);
112
+ const delayMs = Math.min(proposed, remaining, budget > 0 ? budget - elapsed : Number.POSITIVE_INFINITY);
113
+ const waitedAccount = earliest?.candidate ?? candidates[0];
114
+ if (!waitedAccount)
115
+ return undefined;
116
+ return {
117
+ action: 'wait-then-reselect',
118
+ delayMs,
119
+ target: facts.now + delayMs,
120
+ checkpoint: waitCheckpoint(waitedAccount.account, facts.now, waitedAccount.confirmedBlockers ?? []),
121
+ reason: 'pool-blocked',
122
+ retryable: true,
123
+ hostRetry: continuationRetry(facts, axes),
124
+ history,
125
+ };
126
+ }
127
+ /** The caller supplies clocks, admission, delivery ownership and parsed evidence. */
128
+ export function decideAfterLimit(facts, axes) {
129
+ let history = facts.history;
130
+ const pass = (reason, retryable = facts.phase === 'pre-send'
131
+ ? true
132
+ : (facts.failureRetryable ?? true), hostRetry = 'leave') => ({
133
+ action: 'pass',
134
+ reason,
135
+ retryable,
136
+ hostRetry,
137
+ history,
138
+ });
139
+ if (facts.phase === 'after-limit' &&
140
+ facts.host === 'opencode2' &&
141
+ (!facts.delivery.owned || !facts.delivery.attributable))
142
+ return pass('not-owned');
143
+ const status = facts.status ?? facts.signal?.status;
144
+ if (facts.phase === 'after-limit' && facts.attempted)
145
+ history = reduceRequestHistory(history, {
146
+ type: 'response',
147
+ account: facts.attempted,
148
+ scope: facts.requestScope,
149
+ status,
150
+ });
151
+ if (facts.phase === 'after-limit' && !facts.delivery.replayable)
152
+ return pass('unsafe-output', false, 'veto');
153
+ const admitted = facts.candidates.filter((candidate) => candidate.admitted);
154
+ const candidates = admitted.filter((candidate) => !isRequestExcluded(history, candidate.account, facts.requestScope));
155
+ const current = candidates.find((candidate) => facts.attempted && sameAccount(candidate.account, facts.attempted));
156
+ const signal = facts.signalApplicable !== false &&
157
+ facts.signal &&
158
+ facts.attempted &&
159
+ sameAccount(facts.signal.account, facts.attempted)
160
+ ? facts.signal
161
+ : undefined;
162
+ if (axes.requestExclusion === 'on' &&
163
+ signal?.kind === 'model-unavailable' &&
164
+ current) {
165
+ return {
166
+ action: 'exclude-for-request',
167
+ account: current.account,
168
+ scope: facts.requestScope,
169
+ effects: REQUEST_EXCLUSION_EFFECTS,
170
+ reason: 'model-unavailable',
171
+ retryable: true,
172
+ hostRetry: continuationRetry(facts, axes),
173
+ history,
174
+ };
175
+ }
176
+ if (admitted.length && !candidates.length)
177
+ return refusal(facts, axes, history, 'model-unavailable');
178
+ if (facts.host === 'opencode2' &&
179
+ facts.hostPhase === 'retry' &&
180
+ axes.execution === 'host' &&
181
+ facts.remainingRetries !== undefined &&
182
+ facts.remainingRetries < 1) {
183
+ return facts.terminal &&
184
+ (facts.terminal.retryable === false ||
185
+ terminalWaitDisabled(facts.terminal, axes))
186
+ ? refusal(facts, axes, history, facts.terminal.reason, facts.terminal)
187
+ : pass('host-retries-exhausted');
188
+ }
189
+ if (facts.wake && facts.phase === 'pre-send') {
190
+ const wake = facts.wake;
191
+ const held = candidates.find((candidate) => sameAccount(candidate.account, wake.checkpoint.accountKey));
192
+ const windows = held?.confirmedBlockers ??
193
+ (held && signal && sameAccount(signal.account, held.account)
194
+ ? signal.windows
195
+ : []);
196
+ const liftedWindows = held
197
+ ? liftedWindowsForWake(wake, held.account, windows, facts.now)
198
+ : [];
199
+ const bound = facts.hold;
200
+ const cacheValid = wake.kind === 'terminal' ||
201
+ (bound !== undefined &&
202
+ Number.isFinite(bound.cacheExpiresAt) &&
203
+ facts.now <= bound.cacheExpiresAt &&
204
+ wake.target <= bound.cacheExpiresAt &&
205
+ bound.maxWaitMs > 0 &&
206
+ wake.target - wake.checkpoint.decidedAt <= bound.maxWaitMs);
207
+ if (held &&
208
+ Number.isFinite(wake.target) &&
209
+ wake.target >= wake.checkpoint.decidedAt &&
210
+ facts.now >= wake.target &&
211
+ cacheValid &&
212
+ held.blockers.every((blocker) => blocker.until !== undefined &&
213
+ Number.isFinite(blocker.until) &&
214
+ blocker.until <= facts.now) &&
215
+ (held.ready || windows.some((window) => window.confirmed)) &&
216
+ windows
217
+ .filter((window) => window.confirmed)
218
+ .every((window) => liftedWindows.includes(window.window))) {
219
+ return {
220
+ action: 'retain',
221
+ account: held.account,
222
+ liftedWindows,
223
+ reason: 'wait-elapsed',
224
+ retryable: true,
225
+ hostRetry: 'leave',
226
+ history: reduceRequestHistory(history, { type: 'selected' }),
227
+ };
228
+ }
229
+ }
230
+ if (facts.credentialRecovery && current) {
231
+ return {
232
+ action: 'retain',
233
+ account: current.account,
234
+ reason: 'credential-recovery',
235
+ ...(facts.credentialRecovery.retryMs === undefined
236
+ ? {}
237
+ : { retryMs: facts.credentialRecovery.retryMs }),
238
+ retryable: true,
239
+ hostRetry: continuationRetry(facts, axes),
240
+ history,
241
+ };
242
+ }
243
+ const advance = axes.advance[facts.host];
244
+ if (facts.phase === 'after-limit' &&
245
+ !signal &&
246
+ !facts.terminal &&
247
+ (advance.attributedLimitOnly ||
248
+ status === undefined ||
249
+ !advance.statuses.includes(status)))
250
+ return pass('unhandled-failure');
251
+ const selected = candidates.find((candidate) => facts.selection &&
252
+ sameAccount(candidate.account, facts.selection.account) &&
253
+ candidate.placementEligible);
254
+ const selectedReady = selected &&
255
+ (selected.ready ||
256
+ (axes.poolWaiting.kind === 'earliest' &&
257
+ axes.poolWaiting.singleEligibleSoftExemption &&
258
+ candidates.length === 1 &&
259
+ selected.blockers.length > 0 &&
260
+ selected.blockers.every((blocker) => blocker.kind === 'soft')));
261
+ const alternative = selectedReady &&
262
+ (!facts.attempted || !sameAccount(selected.account, facts.attempted))
263
+ ? selected
264
+ : undefined;
265
+ const reroute = (candidate) => ({
266
+ action: 'reroute',
267
+ account: candidate.account,
268
+ pin: facts.selection?.pin ?? 'preserve',
269
+ reason: 'ready-alternative',
270
+ retryable: true,
271
+ hostRetry: continuationRetry(facts, axes),
272
+ history: reduceRequestHistory(history, { type: 'selected' }),
273
+ });
274
+ // Before the first send there is no attempted account or response signal;
275
+ // the retained selection can still have confirmed blockers worth waiting for.
276
+ const holdCandidate = facts.phase === 'pre-send'
277
+ ? (current ??
278
+ candidates.find((candidate) => facts.selection &&
279
+ sameAccount(candidate.account, facts.selection.account)))
280
+ : current;
281
+ const windows = (holdCandidate?.confirmedBlockers ??
282
+ (facts.phase === 'after-limit' ? signal?.windows : undefined) ??
283
+ []).filter((window) => window.confirmed);
284
+ if (windows.length) {
285
+ if (axes.shortLimit.preference === 'ready-alternative-first' && alternative)
286
+ return reroute(alternative);
287
+ const held = hold(facts, axes, history, holdCandidate, windows);
288
+ if (held)
289
+ return held;
290
+ }
291
+ const unknown = axes.unknown[facts.host];
292
+ const unconfirmed = facts.phase === 'after-limit' &&
293
+ !windows.length &&
294
+ (status === 429 ||
295
+ signal?.kind === 'rate-limit' ||
296
+ signal?.kind === 'quota-exhausted' ||
297
+ signal?.kind === 'capacity');
298
+ if (unconfirmed &&
299
+ current &&
300
+ (unknown.affinity === 'always' || facts.affinity === 'sticky')) {
301
+ if (unknown.action === 'pass')
302
+ return pass('unconfirmed-limit');
303
+ if (unknown.action === 'retain') {
304
+ const hints = [
305
+ ...(facts.retryHintsMs ?? []),
306
+ signal?.retryAfterMs,
307
+ ].filter((hint) => hint !== undefined && Number.isFinite(hint) && hint >= 0);
308
+ return {
309
+ action: 'retain',
310
+ account: current.account,
311
+ reason: 'unconfirmed-limit',
312
+ ...(unknown.hint === 'minimum'
313
+ ? { retryMs: Math.min(unknown.defaultMs, ...hints) }
314
+ : {}),
315
+ retryable: true,
316
+ hostRetry: continuationRetry(facts, axes),
317
+ history,
318
+ };
319
+ }
320
+ }
321
+ if (alternative)
322
+ return reroute(alternative);
323
+ if (facts.phase === 'pre-send' && selectedReady)
324
+ return reroute(selected);
325
+ if (facts.host === 'opencode2' &&
326
+ facts.hostPhase === 'request' &&
327
+ axes.markedPool.requestEscape === 'ignore-timed-marks-if-all-marked' &&
328
+ selected &&
329
+ candidates.every((candidate) => !candidate.ready) &&
330
+ candidates.every((candidate) => candidate.blockers.length > 0 &&
331
+ candidate.blockers.every((blocker) => blocker.kind === 'hard')))
332
+ return reroute(selected);
333
+ const waited = poolWait(facts, axes, history, candidates);
334
+ if (waited)
335
+ return waited;
336
+ if (facts.phase === 'pre-send' && !candidates.length)
337
+ return refusal(facts, axes, history, facts.terminal?.reason ?? 'auth', facts.terminal);
338
+ if (facts.host === 'opencode2' &&
339
+ facts.hostPhase === 'retry' &&
340
+ !facts.terminal) {
341
+ if (axes.markedPool.retryExhaustion === 'host-delay')
342
+ return pass('host-delay');
343
+ if (axes.markedPool.retryExhaustion === 'same-host-delay' && current)
344
+ return {
345
+ action: 'retain',
346
+ account: current.account,
347
+ reason: 'host-delay',
348
+ retryable: true,
349
+ hostRetry: 'leave',
350
+ history,
351
+ };
352
+ }
353
+ if (axes.terminalPolicy === 'status-history' &&
354
+ axes.terminalStatusHistory &&
355
+ facts.host !== 'opencode2' &&
356
+ !facts.terminal) {
357
+ const allMarked = facts.phase === 'pre-send' &&
358
+ candidates.length > 0 &&
359
+ candidates.every((candidate) => !candidate.ready);
360
+ if (allMarked || (status === 401 && history.saw429)) {
361
+ const deadlines = candidates
362
+ .flatMap((candidate) => candidate.blockers.map((blocker) => blocker.until))
363
+ .filter((until) => finiteFuture(until, facts.now));
364
+ return refusal(facts, axes, history, 'quota', {
365
+ source: 'pool',
366
+ reason: 'quota',
367
+ retryAfterMs: deadlines.length
368
+ ? Math.max(axes.terminalStatusHistory.minRetryMs, Math.min(...deadlines) - facts.now)
369
+ : axes.terminalStatusHistory.defaultRetryMs,
370
+ });
371
+ }
372
+ return pass('original-response');
373
+ }
374
+ if (facts.terminal)
375
+ return refusal(facts, axes, history, facts.terminal.reason, facts.terminal);
376
+ if (signal?.kind === 'auth' || signal?.kind === 'account-access')
377
+ return refusal(facts, axes, history, 'auth');
378
+ if (signal ||
379
+ status === 429 ||
380
+ candidates.some((candidate) => candidate.blockers.length))
381
+ return refusal(facts, axes, history, 'quota');
382
+ return pass('no-override');
383
+ }
@@ -0,0 +1,8 @@
1
+ /** Compact durations keep every numeric component below the hosts' retry codes. */
2
+ export declare function formatDuration(ms: number): string;
3
+ export interface ResetFormatInput {
4
+ readonly resetAt: number;
5
+ readonly now: number;
6
+ }
7
+ export type ResetFormatter = (input: ResetFormatInput) => string;
8
+ export declare const formatReset: ResetFormatter;
@@ -0,0 +1,20 @@
1
+ /** Compact durations keep every numeric component below the hosts' retry codes. */
2
+ export function formatDuration(ms) {
3
+ if (!Number.isFinite(ms))
4
+ return 'unknown';
5
+ const seconds = Math.ceil(Math.max(0, ms) / 1000);
6
+ if (seconds < 60)
7
+ return `${seconds}s`;
8
+ const minutes = Math.ceil(seconds / 60);
9
+ const days = Math.floor(minutes / (24 * 60));
10
+ if (days >= 100)
11
+ return 'over 99 days';
12
+ const hours = Math.floor(minutes / 60) % 24;
13
+ const remainingMinutes = minutes % 60;
14
+ if (days > 0)
15
+ return `${days}d ${hours}h ${remainingMinutes}m`;
16
+ if (hours > 0)
17
+ return `${hours}h ${remainingMinutes}m`;
18
+ return `${remainingMinutes}m`;
19
+ }
20
+ export const formatReset = ({ resetAt, now }) => formatDuration(resetAt - now);
@@ -0,0 +1,29 @@
1
+ import { type LimitsNamespace } from './namespace.js';
2
+ /**
3
+ * Where a failed detached repair is reported. The limits export takes this from
4
+ * the caller rather than importing the shared logger, whose file sink would pull
5
+ * the Windows private-files module into every limits import.
6
+ */
7
+ export interface LimitsRecoveryLogger {
8
+ warn(message: string, fields?: Record<string, unknown>): void;
9
+ }
10
+ /** Readers never join the write lock; notify them after a detached repair lands. */
11
+ export declare class EnvelopeRepair {
12
+ private readonly logger?;
13
+ private running?;
14
+ private readonly listeners;
15
+ constructor(logger?: LimitsRecoveryLogger | undefined);
16
+ readonly subscribe: (listener: () => void) => (() => void);
17
+ schedule(commit: () => Promise<unknown>): void;
18
+ }
19
+ /** Retain only durable observations; a new, empty namespace is not lost state. */
20
+ export declare class EnvelopeHistory {
21
+ private seen?;
22
+ private missingGeneration?;
23
+ private incorporated?;
24
+ remember(snapshot: LimitsNamespace, previous?: LimitsNamespace): void;
25
+ private retained;
26
+ lost(present: LimitsNamespace | undefined, previous?: LimitsNamespace): boolean;
27
+ /** Preview a restrictive merge, or apply it against the envelope under the write lock. */
28
+ recover(present: LimitsNamespace | undefined, previous: LimitsNamespace | undefined, namespace: string, now: number): LimitsNamespace;
29
+ }
@@ -0,0 +1,150 @@
1
+ import { AsyncResource } from 'node:async_hooks';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { mergeAccessState } from './merge-laws.js';
5
+ import { createLimitsNamespace, pruneLimitsNamespace, timedMarkKeyId, } from './namespace.js';
6
+ const detached = new AsyncResource('common-auth-limits-recovery');
7
+ /** Readers never join the write lock; notify them after a detached repair lands. */
8
+ export class EnvelopeRepair {
9
+ logger;
10
+ running;
11
+ listeners = new Set();
12
+ constructor(logger) {
13
+ this.logger = logger;
14
+ }
15
+ subscribe = (listener) => {
16
+ this.listeners.add(listener);
17
+ return () => this.listeners.delete(listener);
18
+ };
19
+ schedule(commit) {
20
+ if (this.running)
21
+ return;
22
+ this.running = detached.runInAsyncScope(async () => {
23
+ // Defer invocation until the single-flight promise is installed, and keep
24
+ // the write outside any caller context that holds the store lock.
25
+ await Promise.resolve();
26
+ let succeeded = false;
27
+ try {
28
+ await commit();
29
+ succeeded = true;
30
+ }
31
+ catch (error) {
32
+ try {
33
+ this.logger?.warn('limits envelope recovery failed; agreement remains degraded', {
34
+ error: error instanceof Error ? error.message : String(error),
35
+ });
36
+ }
37
+ catch {
38
+ // A failed diagnostic must not turn detached bookkeeping into a rejection.
39
+ }
40
+ }
41
+ finally {
42
+ this.running = undefined;
43
+ if (succeeded) {
44
+ for (const listener of this.listeners) {
45
+ try {
46
+ listener();
47
+ }
48
+ catch {
49
+ // Observers cannot change the result of a durable repair.
50
+ }
51
+ }
52
+ }
53
+ }
54
+ });
55
+ }
56
+ }
57
+ /** Retain only durable observations; a new, empty namespace is not lost state. */
58
+ export class EnvelopeHistory {
59
+ seen;
60
+ missingGeneration;
61
+ incorporated;
62
+ remember(snapshot, previous) {
63
+ if (this.seen && this.seen.revision > snapshot.revision)
64
+ return;
65
+ this.seen = structuredClone(snapshot);
66
+ this.missingGeneration = undefined;
67
+ if (previous)
68
+ this.incorporated = structuredClone(previous);
69
+ }
70
+ retained(previous) {
71
+ // A notification reload still carries the pre-repair registry snapshot.
72
+ // Do not mistake that already-merged generation for another loss.
73
+ const retainedPrevious = isDeepStrictEqual(previous, this.incorporated)
74
+ ? undefined
75
+ : previous;
76
+ return [this.seen, retainedPrevious].filter((snapshot) => snapshot !== undefined &&
77
+ (snapshot === this.seen || snapshot.revision > 0));
78
+ }
79
+ lost(present, previous) {
80
+ return this.retained(previous).some((seen) => !present ||
81
+ seen.generation !== present.generation ||
82
+ present.revision < seen.revision ||
83
+ seen.tombstones.some((clear) => clear.revision > present.lowWatermark &&
84
+ !present.tombstones.some((current) => timedMarkKeyId(current.key) === timedMarkKeyId(clear.key) &&
85
+ current.revision >= clear.revision)));
86
+ }
87
+ /** Preview a restrictive merge, or apply it against the envelope under the write lock. */
88
+ recover(present, previous, namespace, now) {
89
+ if (!present)
90
+ this.missingGeneration ??= randomUUID();
91
+ const current = present ??
92
+ createLimitsNamespace(namespace, this.missingGeneration ?? randomUUID());
93
+ const sources = [...this.retained(previous), current];
94
+ const marks = new Map();
95
+ const tombstones = new Map();
96
+ const operations = new Map();
97
+ const access = new Map();
98
+ let highest = 0;
99
+ for (const source of sources) {
100
+ highest = Math.max(highest, source.revision, source.lowWatermark);
101
+ for (const mark of source.marks) {
102
+ const id = timedMarkKeyId(mark.key);
103
+ const old = marks.get(id);
104
+ if (old && old.mergeLaw !== mark.mergeLaw)
105
+ throw new Error('limits-recovery-merge-law-conflict');
106
+ marks.set(id, {
107
+ ...mark,
108
+ entries: [...(old?.entries ?? []), ...mark.entries],
109
+ });
110
+ for (const entry of mark.entries)
111
+ highest = Math.max(highest, entry.baseRevision, entry.committedRevision);
112
+ }
113
+ for (const clear of source.tombstones) {
114
+ const id = timedMarkKeyId(clear.key);
115
+ const old = tombstones.get(id);
116
+ if (!old || old.revision < clear.revision)
117
+ tombstones.set(id, clear);
118
+ highest = Math.max(highest, clear.revision);
119
+ }
120
+ for (const op of source.operationIds) {
121
+ const id = JSON.stringify([op.producerId, op.operationId]);
122
+ const old = operations.get(id);
123
+ if (!old || old.revision < op.revision)
124
+ operations.set(id, op);
125
+ highest = Math.max(highest, op.revision);
126
+ }
127
+ for (const state of source.access) {
128
+ const { namespace, accountId, incarnation } = state.account;
129
+ const id = JSON.stringify([namespace, accountId, incarnation]);
130
+ const old = access.get(id);
131
+ access.set(id, old ? mergeAccessState(old, state) : state);
132
+ highest = Math.max(highest, state.committedRevision);
133
+ }
134
+ }
135
+ const revision = highest + 1;
136
+ if (!Number.isSafeInteger(revision))
137
+ throw new Error('limits-revision-exhausted');
138
+ // The barrier rejects observations predating even a clear this process never
139
+ // saw. Retain entry base revisions so a later restored clear can remove them.
140
+ return pruneLimitsNamespace({
141
+ ...current,
142
+ revision,
143
+ lowWatermark: revision,
144
+ marks: [...marks.values()],
145
+ tombstones: [...tombstones.values()],
146
+ operationIds: [...operations.values()],
147
+ access: [...access.values()],
148
+ }, now);
149
+ }
150
+ }
@@ -0,0 +1,57 @@
1
+ import { type LimitMessages } from './wording.js';
2
+ export type OpenCode1Family = 'openai-429' | 'claude-429' | 'json-412' | 'claustrum-429' | 'claude-econnreset';
3
+ export type RefusalFamily = OpenCode1Family | 'pi-final';
4
+ export type HostRetry = 'leave' | 'veto';
5
+ export interface RefusalInput {
6
+ readonly family: RefusalFamily;
7
+ readonly messageKey: string;
8
+ readonly messages?: LimitMessages;
9
+ readonly parameters?: {
10
+ readonly labels?: readonly string[];
11
+ };
12
+ /**
13
+ * Set only for re-login guidance, where the user needs to know which account to sign in again.
14
+ * Ordinary refusals omit labels, even when the caller supplies them.
15
+ */
16
+ readonly labelPolicy?: 'relogin';
17
+ readonly now: number;
18
+ /** A retained reset, already filtered for freshness by the decision layer. */
19
+ readonly resetAt?: number;
20
+ readonly retryAfterMs?: number;
21
+ /** Time already spent presenting a notice, not an instruction to sleep. */
22
+ readonly noticeDelayMs?: number;
23
+ /** Additional provider headers are preserved by the JSON 412 family only. */
24
+ readonly extraHeaders?: ConstructorParameters<typeof Headers>[0];
25
+ }
26
+ interface RefusalAttributes {
27
+ readonly family: RefusalFamily;
28
+ readonly disposition: 'refuse';
29
+ readonly retryable: boolean;
30
+ readonly hostRetry: HostRetry;
31
+ }
32
+ export interface HttpRefusal extends RefusalAttributes {
33
+ readonly kind: 'http';
34
+ readonly status: 412 | 429;
35
+ readonly headers: Headers;
36
+ readonly body: string;
37
+ }
38
+ export interface TextRefusal extends RefusalAttributes {
39
+ readonly kind: 'text';
40
+ readonly body: string;
41
+ }
42
+ export declare class ClaudeIncompleteError extends Error {
43
+ readonly code = "ECONNRESET";
44
+ readonly syscall = "sticky-routing";
45
+ readonly isRetryable = true;
46
+ constructor(message: string);
47
+ }
48
+ export interface ThrownRefusal extends RefusalAttributes {
49
+ readonly kind: 'throw';
50
+ readonly error: ClaudeIncompleteError;
51
+ }
52
+ export type BuiltRefusal = HttpRefusal | TextRefusal | ThrownRefusal;
53
+ /** Compute metadata at delivery time, after time spent showing a notice. */
54
+ export declare function retryAfterSeconds(retryAfterMs: number | undefined, noticeDelayMs?: number): number | undefined;
55
+ /** Pure wire construction: the caller sends the response, emits text, or throws the error. */
56
+ export declare function buildRefusal(input: RefusalInput): BuiltRefusal;
57
+ export {};