@cortexkit/common-auth 0.34.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.
- package/dist/limits/axes.d.ts +7 -1
- package/dist/limits/decide.d.ts +5 -0
- package/dist/limits/decide.js +53 -11
- package/dist/limits/families.d.ts +4 -2
- package/dist/limits/families.js +8 -2
- package/dist/limits/index.d.ts +4 -3
- package/dist/limits/index.js +2 -1
- package/dist/limits/marker.d.ts +5 -0
- package/dist/limits/marker.js +16 -5
- package/dist/limits/merge-laws.d.ts +1 -0
- package/dist/limits/namespace.d.ts +4 -1
- package/dist/limits/namespace.js +9 -1
- package/dist/limits/presets.js +18 -1
- package/dist/limits/registry.d.ts +12 -0
- package/dist/limits/registry.js +7 -0
- package/dist/limits/request-history.d.ts +3 -1
- package/dist/limits/request-history.js +3 -0
- package/dist/limits/unconfirmed-retain-counter.d.ts +13 -0
- package/dist/limits/unconfirmed-retain-counter.js +41 -0
- package/package.json +1 -1
package/dist/limits/axes.d.ts
CHANGED
|
@@ -29,8 +29,10 @@ export interface LimitAxes {
|
|
|
29
29
|
readonly preference: 'same-account-first' | 'ready-alternative-first';
|
|
30
30
|
readonly jitter: 'session-sha256' | 'none';
|
|
31
31
|
};
|
|
32
|
-
/**
|
|
32
|
+
/** Legacy uncounted retention remains unbounded. */
|
|
33
33
|
readonly retainBound: 'none';
|
|
34
|
+
/** Opt-in turn/account budget when the caller supplies unconfirmedRetainCount. */
|
|
35
|
+
readonly unconfirmedRetainLimit?: number;
|
|
34
36
|
readonly poolWaiting: {
|
|
35
37
|
readonly kind: 'off';
|
|
36
38
|
} | {
|
|
@@ -56,6 +58,10 @@ export interface LimitAxes {
|
|
|
56
58
|
readonly terminalStatusHistory?: {
|
|
57
59
|
readonly minRetryMs: number;
|
|
58
60
|
readonly defaultRetryMs: number;
|
|
61
|
+
readonly paymentBalance?: {
|
|
62
|
+
readonly family: RefusalFamily;
|
|
63
|
+
readonly messageKey: string;
|
|
64
|
+
};
|
|
59
65
|
};
|
|
60
66
|
readonly refusals: Readonly<Record<RefusalReason, HostValues<RefusalPolicy>>>;
|
|
61
67
|
}
|
package/dist/limits/decide.d.ts
CHANGED
|
@@ -9,6 +9,7 @@ import type { WakeFacts } from './wake.js';
|
|
|
9
9
|
export interface TimedBlocker {
|
|
10
10
|
readonly kind: 'hard' | 'cooldown' | 'soft';
|
|
11
11
|
readonly until?: number;
|
|
12
|
+
readonly cause?: import('./marker.js').LimitMarkCause;
|
|
12
13
|
}
|
|
13
14
|
/**
|
|
14
15
|
* Admission includes the caller's minimum quota thresholds, access checks,
|
|
@@ -80,6 +81,8 @@ export interface PolicyFacts {
|
|
|
80
81
|
readonly retryMs?: number;
|
|
81
82
|
};
|
|
82
83
|
readonly retryHintsMs?: readonly number[];
|
|
84
|
+
/** Committed unconfirmed retains for the current session, turn and account. */
|
|
85
|
+
readonly unconfirmedRetainCount?: number;
|
|
83
86
|
readonly hold?: HoldFacts;
|
|
84
87
|
readonly wake?: WakeFacts;
|
|
85
88
|
readonly remainingRetries?: number;
|
|
@@ -110,6 +113,8 @@ export type LimitDecision = DecisionBase & ({
|
|
|
110
113
|
readonly action: 'retain';
|
|
111
114
|
readonly account: AccountKey;
|
|
112
115
|
readonly retryMs?: number;
|
|
116
|
+
/** Commit once when executing this retain, never when polling the decision. */
|
|
117
|
+
readonly incrementUnconfirmedRetain?: true;
|
|
113
118
|
/** Exhaustion windows waived for this dispatch only, never persisted. */
|
|
114
119
|
readonly liftedWindows?: readonly string[];
|
|
115
120
|
} | {
|
package/dist/limits/decide.js
CHANGED
|
@@ -147,6 +147,12 @@ export function decideAfterLimit(facts, axes) {
|
|
|
147
147
|
account: facts.attempted,
|
|
148
148
|
scope: facts.requestScope,
|
|
149
149
|
status,
|
|
150
|
+
kind: axes.terminalStatusHistory?.paymentBalance &&
|
|
151
|
+
facts.signalApplicable !== false &&
|
|
152
|
+
facts.signal &&
|
|
153
|
+
sameAccount(facts.signal.account, facts.attempted)
|
|
154
|
+
? facts.signal.kind
|
|
155
|
+
: undefined,
|
|
150
156
|
});
|
|
151
157
|
if (facts.phase === 'after-limit' && !facts.delivery.replayable)
|
|
152
158
|
return pass('unsafe-output', false, 'veto');
|
|
@@ -240,9 +246,20 @@ export function decideAfterLimit(facts, axes) {
|
|
|
240
246
|
history,
|
|
241
247
|
};
|
|
242
248
|
}
|
|
249
|
+
// Supplying the count opts into the turn-scoped rule across all hosts;
|
|
250
|
+
// callers without it keep their existing host-specific unknown-limit policy.
|
|
251
|
+
const retainLimit = axes.unconfirmedRetainLimit;
|
|
252
|
+
const retainCount = facts.unconfirmedRetainCount;
|
|
253
|
+
const counted = status === 429 && retainLimit !== undefined && retainCount !== undefined;
|
|
243
254
|
const advance = axes.advance[facts.host];
|
|
255
|
+
if (facts.phase === 'after-limit' &&
|
|
256
|
+
axes.terminalStatusHistory?.paymentBalance &&
|
|
257
|
+
(signal?.kind === 'payment-cap' ||
|
|
258
|
+
(status === 402 && signal?.kind !== 'payment-balance')))
|
|
259
|
+
return pass('unhandled-failure');
|
|
244
260
|
if (facts.phase === 'after-limit' &&
|
|
245
261
|
!signal &&
|
|
262
|
+
!counted &&
|
|
246
263
|
!facts.terminal &&
|
|
247
264
|
(advance.attributedLimitOnly ||
|
|
248
265
|
status === undefined ||
|
|
@@ -262,11 +279,11 @@ export function decideAfterLimit(facts, axes) {
|
|
|
262
279
|
(!facts.attempted || !sameAccount(selected.account, facts.attempted))
|
|
263
280
|
? selected
|
|
264
281
|
: undefined;
|
|
265
|
-
const reroute = (candidate) => ({
|
|
282
|
+
const reroute = (candidate, reason = 'ready-alternative') => ({
|
|
266
283
|
action: 'reroute',
|
|
267
284
|
account: candidate.account,
|
|
268
285
|
pin: facts.selection?.pin ?? 'preserve',
|
|
269
|
-
reason
|
|
286
|
+
reason,
|
|
270
287
|
retryable: true,
|
|
271
288
|
hostRetry: continuationRetry(facts, axes),
|
|
272
289
|
history: reduceRequestHistory(history, { type: 'selected' }),
|
|
@@ -295,28 +312,39 @@ export function decideAfterLimit(facts, axes) {
|
|
|
295
312
|
signal?.kind === 'rate-limit' ||
|
|
296
313
|
signal?.kind === 'quota-exhausted' ||
|
|
297
314
|
signal?.kind === 'capacity');
|
|
315
|
+
const retainLimitReached = counted && retainCount >= retainLimit;
|
|
298
316
|
if (unconfirmed &&
|
|
299
317
|
current &&
|
|
300
318
|
(unknown.affinity === 'always' || facts.affinity === 'sticky')) {
|
|
301
|
-
if (
|
|
302
|
-
|
|
303
|
-
|
|
319
|
+
if (counted && retainLimitReached) {
|
|
320
|
+
if (alternative)
|
|
321
|
+
return reroute(alternative, 'unconfirmed-retry-limit');
|
|
322
|
+
// With no ready replacement, use the ordinary exhausted-pool outcome.
|
|
323
|
+
}
|
|
324
|
+
else if (counted || unknown.action === 'retain') {
|
|
304
325
|
const hints = [
|
|
305
326
|
...(facts.retryHintsMs ?? []),
|
|
306
327
|
signal?.retryAfterMs,
|
|
307
|
-
].filter((hint) => hint !== undefined && Number.isFinite(hint) && hint >= 0);
|
|
328
|
+
].filter((hint) => hint !== undefined && Number.isFinite(hint) && (counted || hint >= 0));
|
|
308
329
|
return {
|
|
309
330
|
action: 'retain',
|
|
310
331
|
account: current.account,
|
|
311
332
|
reason: 'unconfirmed-limit',
|
|
312
|
-
...(
|
|
313
|
-
? {
|
|
314
|
-
|
|
333
|
+
...(counted
|
|
334
|
+
? {
|
|
335
|
+
retryMs: Math.min(60_000, ...hints.map((hint) => Math.max(0, hint))),
|
|
336
|
+
incrementUnconfirmedRetain: true,
|
|
337
|
+
}
|
|
338
|
+
: unknown.hint === 'minimum'
|
|
339
|
+
? { retryMs: Math.min(unknown.defaultMs, ...hints) }
|
|
340
|
+
: {}),
|
|
315
341
|
retryable: true,
|
|
316
342
|
hostRetry: continuationRetry(facts, axes),
|
|
317
343
|
history,
|
|
318
344
|
};
|
|
319
345
|
}
|
|
346
|
+
else if (unknown.action === 'pass')
|
|
347
|
+
return pass('unconfirmed-limit');
|
|
320
348
|
}
|
|
321
349
|
if (alternative)
|
|
322
350
|
return reroute(alternative);
|
|
@@ -357,13 +385,27 @@ export function decideAfterLimit(facts, axes) {
|
|
|
357
385
|
const allMarked = facts.phase === 'pre-send' &&
|
|
358
386
|
candidates.length > 0 &&
|
|
359
387
|
candidates.every((candidate) => !candidate.ready);
|
|
360
|
-
|
|
361
|
-
|
|
388
|
+
const eligible = candidates.filter((candidate) => candidate.placementEligible);
|
|
389
|
+
const allBalance = facts.phase === 'pre-send' &&
|
|
390
|
+
axes.terminalStatusHistory.paymentBalance &&
|
|
391
|
+
eligible.length > 0 &&
|
|
392
|
+
eligible.every((candidate) => !candidate.ready &&
|
|
393
|
+
candidate.blockers.length > 0 &&
|
|
394
|
+
candidate.blockers.every((blocker) => blocker.cause === 'payment-balance' &&
|
|
395
|
+
finiteFuture(blocker.until, facts.now)));
|
|
396
|
+
if (allBalance ||
|
|
397
|
+
allMarked ||
|
|
398
|
+
(status === 401 && history.saw429) ||
|
|
399
|
+
(axes.terminalStatusHistory.paymentBalance &&
|
|
400
|
+
history.saw429 &&
|
|
401
|
+
history.sawPaymentBalance)) {
|
|
402
|
+
const deadlines = (allBalance ? eligible : candidates)
|
|
362
403
|
.flatMap((candidate) => candidate.blockers.map((blocker) => blocker.until))
|
|
363
404
|
.filter((until) => finiteFuture(until, facts.now));
|
|
364
405
|
return refusal(facts, axes, history, 'quota', {
|
|
365
406
|
source: 'pool',
|
|
366
407
|
reason: 'quota',
|
|
408
|
+
...(allBalance ? axes.terminalStatusHistory.paymentBalance : {}),
|
|
367
409
|
retryAfterMs: deadlines.length
|
|
368
410
|
? Math.max(axes.terminalStatusHistory.minRetryMs, Math.min(...deadlines) - facts.now)
|
|
369
411
|
: axes.terminalStatusHistory.defaultRetryMs,
|
|
@@ -1,9 +1,11 @@
|
|
|
1
1
|
import { type LimitMessages } from './wording.js';
|
|
2
|
-
export type OpenCode1Family = 'openai-429' | 'claude-429' | 'json-412' | 'claustrum-429' | 'claude-econnreset';
|
|
2
|
+
export type OpenCode1Family = 'openai-429' | 'claude-429' | 'json-412' | 'claustrum-429' | 'claustrum-402' | 'claude-econnreset';
|
|
3
3
|
export type RefusalFamily = OpenCode1Family | 'pi-final';
|
|
4
4
|
export type HostRetry = 'leave' | 'veto';
|
|
5
5
|
export interface RefusalInput {
|
|
6
6
|
readonly family: RefusalFamily;
|
|
7
|
+
/** Local responses formatted for OpenCode 2 must not be replayed by the host. */
|
|
8
|
+
readonly host?: 'opencode1' | 'opencode2' | 'pi';
|
|
7
9
|
readonly messageKey: string;
|
|
8
10
|
readonly messages?: LimitMessages;
|
|
9
11
|
readonly parameters?: {
|
|
@@ -31,7 +33,7 @@ interface RefusalAttributes {
|
|
|
31
33
|
}
|
|
32
34
|
export interface HttpRefusal extends RefusalAttributes {
|
|
33
35
|
readonly kind: 'http';
|
|
34
|
-
readonly status: 412 | 429;
|
|
36
|
+
readonly status: 402 | 412 | 429;
|
|
35
37
|
readonly headers: Headers;
|
|
36
38
|
readonly body: string;
|
|
37
39
|
}
|
package/dist/limits/families.js
CHANGED
|
@@ -97,6 +97,8 @@ function bodyFor(family, message) {
|
|
|
97
97
|
});
|
|
98
98
|
case 'claustrum-429':
|
|
99
99
|
return JSON.stringify({ error: 'claustrum-auth: accounts-rate-limited' });
|
|
100
|
+
case 'claustrum-402':
|
|
101
|
+
return JSON.stringify({ error: 'claustrum-auth: insufficient balance' });
|
|
100
102
|
default:
|
|
101
103
|
return message;
|
|
102
104
|
}
|
|
@@ -108,7 +110,7 @@ export function buildRefusal(input) {
|
|
|
108
110
|
family: input.family,
|
|
109
111
|
disposition: 'refuse',
|
|
110
112
|
retryable: !nonRetryable,
|
|
111
|
-
hostRetry: nonRetryable ? 'veto' : 'leave',
|
|
113
|
+
hostRetry: nonRetryable || input.host === 'opencode2' ? 'veto' : 'leave',
|
|
112
114
|
};
|
|
113
115
|
let body = bodyFor(input.family, textFor(input, nonRetryable));
|
|
114
116
|
if (nonRetryable && (hasUnsafeWording(body) || containsEmail(body))) {
|
|
@@ -136,7 +138,11 @@ export function buildRefusal(input) {
|
|
|
136
138
|
return {
|
|
137
139
|
...attributes,
|
|
138
140
|
kind: 'http',
|
|
139
|
-
status: input.family === 'json-412'
|
|
141
|
+
status: input.family === 'json-412'
|
|
142
|
+
? 412
|
|
143
|
+
: input.family === 'claustrum-402'
|
|
144
|
+
? 402
|
|
145
|
+
: 429,
|
|
140
146
|
headers,
|
|
141
147
|
body,
|
|
142
148
|
};
|
package/dist/limits/index.d.ts
CHANGED
|
@@ -16,7 +16,7 @@ export type { AuthorizeCredentialEpoch, IdentityBinding, } from './identity.js';
|
|
|
16
16
|
export { isIdentityCompatible, retainVerifiedIdentity, validateIdentityFence, } from './identity.js';
|
|
17
17
|
export { holdDelayMs } from './jitter.js';
|
|
18
18
|
export { sanitizeRefusalLabel } from './labels.js';
|
|
19
|
-
export type { FailureEvent, FailureHistory, FailureLadderAxes, FailureStreak, LimitMark, MarkerAxes, MarkerHistory, MergeLaw, } from './marker.js';
|
|
19
|
+
export type { FailureEvent, FailureHistory, FailureLadderAxes, FailureStreak, LimitMark, LimitMarkCause, MarkerAxes, MarkerHistory, MergeLaw, } from './marker.js';
|
|
20
20
|
export { ANTIGRAVITY_FAILURE_LADDER, markFromSignal, markIsActive, reduceFailureHistory, } from './marker.js';
|
|
21
21
|
export type { AccessOrder, TimedMarkEntry } from './merge-laws.js';
|
|
22
22
|
export { mergeAccessState, mergeTimedMarkEntries } from './merge-laws.js';
|
|
@@ -28,8 +28,8 @@ export type { PiWaitOptions, PiWaitResult } from './pi-wait.js';
|
|
|
28
28
|
export { waitForPi } from './pi-wait.js';
|
|
29
29
|
export { createPoolLimitsAdapter, type PoolLimitsAdapterOptions, } from './pool-adapter.js';
|
|
30
30
|
export { confirmedAffinity, earliestPoolEngine, limitPresets, statusVaultOrder, windowRouter, } from './presets.js';
|
|
31
|
-
export type { LimitsClock, LimitsDispatchView, LimitsRegistry, LimitsRegistryEvent, LimitsRegistryOptions, } from './registry.js';
|
|
32
|
-
export { acquireLimitsRegistry, LIMITS_REGISTRY_KEY } from './registry.js';
|
|
31
|
+
export type { LimitsClock, LimitsDispatchView, LimitsRegistry, LimitsRegistryEvent, LimitsRegistryOptions, SuccessfulProbeClear, } from './registry.js';
|
|
32
|
+
export { acquireLimitsRegistry, clearLimitsAfterProbe, LIMITS_REGISTRY_KEY, } from './registry.js';
|
|
33
33
|
export type { RequestExclusion, RequestHistory, RequestHistoryEvent, RetainHistory, } from './request-history.js';
|
|
34
34
|
export { commitRequestExclusion, createRequestHistory, isRequestExcluded, REQUEST_EXCLUSION_EFFECTS, reduceRequestHistory, sameAccount, } from './request-history.js';
|
|
35
35
|
export type { ResetSource, ResolvedReset } from './reset.js';
|
|
@@ -40,5 +40,6 @@ export { scopeCovers } from './scope.js';
|
|
|
40
40
|
export type { AccountKey, ClassifierInput, LimitClassifier, LimitKind, LimitSignal, LimitWindow, } from './signal.js';
|
|
41
41
|
export type { TerminalCandidate, TerminalReset, TerminalScanFacts, TerminalWindow, } from './terminal.js';
|
|
42
42
|
export { scanTerminalReset } from './terminal.js';
|
|
43
|
+
export { UnconfirmedRetainCounter } from './unconfirmed-retain-counter.js';
|
|
43
44
|
export type { LimitMessageOptions, LimitMessages, MessageParameters, MessageTemplate, } from './wording.js';
|
|
44
45
|
export { hasUnsafeWording, registerLimitMessages, UnsafeWordingError, } from './wording.js';
|
package/dist/limits/index.js
CHANGED
|
@@ -16,10 +16,11 @@ export { LimitsPersistenceRefusal } from './persistence.js';
|
|
|
16
16
|
export { waitForPi } from './pi-wait.js';
|
|
17
17
|
export { createPoolLimitsAdapter, } from './pool-adapter.js';
|
|
18
18
|
export { confirmedAffinity, earliestPoolEngine, limitPresets, statusVaultOrder, windowRouter, } from './presets.js';
|
|
19
|
-
export { acquireLimitsRegistry, LIMITS_REGISTRY_KEY } from './registry.js';
|
|
19
|
+
export { acquireLimitsRegistry, clearLimitsAfterProbe, LIMITS_REGISTRY_KEY, } from './registry.js';
|
|
20
20
|
export { commitRequestExclusion, createRequestHistory, isRequestExcluded, REQUEST_EXCLUSION_EFFECTS, reduceRequestHistory, sameAccount, } from './request-history.js';
|
|
21
21
|
export { resolveNamedWindowReset, resolveReset } from './reset.js';
|
|
22
22
|
export { holdWaitMaxS } from './routing-hold.js';
|
|
23
23
|
export { scopeCovers } from './scope.js';
|
|
24
24
|
export { scanTerminalReset } from './terminal.js';
|
|
25
|
+
export { UnconfirmedRetainCounter } from './unconfirmed-retain-counter.js';
|
|
25
26
|
export { hasUnsafeWording, registerLimitMessages, UnsafeWordingError, } from './wording.js';
|
package/dist/limits/marker.d.ts
CHANGED
|
@@ -1,10 +1,12 @@
|
|
|
1
1
|
import type { Scope } from './scope.js';
|
|
2
2
|
import type { AccountKey, LimitKind, LimitSignal } from './signal.js';
|
|
3
3
|
export type MergeLaw = 'latest-evidence' | 'max-until' | 'overwrite';
|
|
4
|
+
export type LimitMarkCause = 'rate-limit' | 'payment-balance';
|
|
4
5
|
export interface LimitMark {
|
|
5
6
|
readonly scope: Scope;
|
|
6
7
|
readonly until: number;
|
|
7
8
|
readonly mergeLaw: MergeLaw;
|
|
9
|
+
readonly cause?: LimitMarkCause;
|
|
8
10
|
}
|
|
9
11
|
export interface FailureLadderAxes {
|
|
10
12
|
readonly kind: 'failure-ladder';
|
|
@@ -27,6 +29,9 @@ export type MarkerAxes = {
|
|
|
27
29
|
readonly kind: 'hint';
|
|
28
30
|
readonly mergeLaw: MergeLaw;
|
|
29
31
|
readonly defaultMs: number;
|
|
32
|
+
readonly defaultMsByKind?: Readonly<Partial<Record<LimitSignal['kind'], number>>>;
|
|
33
|
+
readonly causes?: readonly LimitMarkCause[];
|
|
34
|
+
readonly ignoredKinds?: readonly LimitSignal['kind'][];
|
|
30
35
|
readonly minimumMs: number;
|
|
31
36
|
readonly zero: 'accept' | 'skip';
|
|
32
37
|
/** Core absolute dates and host event-relative hints use different samples. */
|
package/dist/limits/marker.js
CHANGED
|
@@ -61,6 +61,8 @@ function ladderMs(signal, axes, history) {
|
|
|
61
61
|
export function markFromSignal(signal, axes, history) {
|
|
62
62
|
if (!signal || axes.kind === 'off')
|
|
63
63
|
return undefined;
|
|
64
|
+
if (axes.kind === 'hint' && axes.ignoredKinds?.includes(signal.kind))
|
|
65
|
+
return undefined;
|
|
64
66
|
let until;
|
|
65
67
|
switch (axes.kind) {
|
|
66
68
|
case 'failure-ladder':
|
|
@@ -68,13 +70,14 @@ export function markFromSignal(signal, axes, history) {
|
|
|
68
70
|
break;
|
|
69
71
|
case 'hint': {
|
|
70
72
|
const hint = signal.retryAfterMs;
|
|
73
|
+
const clock = axes.hintClock === 'signal' ? signal.observedAt : history.now;
|
|
71
74
|
const usable = hint !== undefined &&
|
|
72
75
|
Number.isFinite(hint) &&
|
|
73
|
-
(hint > 0 || (hint === 0 && axes.zero === 'accept'))
|
|
76
|
+
(hint > 0 || (hint === 0 && axes.zero === 'accept')) &&
|
|
77
|
+
Number.isFinite(clock + Math.max(axes.minimumMs, hint));
|
|
74
78
|
until = usable
|
|
75
|
-
? (axes.
|
|
76
|
-
|
|
77
|
-
: history.now + axes.defaultMs;
|
|
79
|
+
? clock + Math.max(axes.minimumMs, hint)
|
|
80
|
+
: history.now + (axes.defaultMsByKind?.[signal.kind] ?? axes.defaultMs);
|
|
78
81
|
break;
|
|
79
82
|
}
|
|
80
83
|
case 'reset': {
|
|
@@ -88,7 +91,15 @@ export function markFromSignal(signal, axes, history) {
|
|
|
88
91
|
}
|
|
89
92
|
}
|
|
90
93
|
return Number.isFinite(until)
|
|
91
|
-
? {
|
|
94
|
+
? {
|
|
95
|
+
scope: signal.scope,
|
|
96
|
+
until,
|
|
97
|
+
mergeLaw: axes.mergeLaw,
|
|
98
|
+
...(axes.kind === 'hint' &&
|
|
99
|
+
axes.causes?.some((cause) => cause === signal.kind)
|
|
100
|
+
? { cause: signal.kind }
|
|
101
|
+
: {}),
|
|
102
|
+
}
|
|
92
103
|
: undefined;
|
|
93
104
|
}
|
|
94
105
|
export function markIsActive(mark, now) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { AuthorizeCredentialEpoch, IdentityBinding } from './identity.js';
|
|
2
|
-
import type { MergeLaw } from './marker.js';
|
|
2
|
+
import type { LimitMarkCause, MergeLaw } from './marker.js';
|
|
3
3
|
import type { AccessOrder, TimedMarkEntry } from './merge-laws.js';
|
|
4
4
|
import type { Scope } from './scope.js';
|
|
5
5
|
import type { AccountKey } from './signal.js';
|
|
@@ -52,11 +52,14 @@ export type LimitsCommand<T = unknown> = CommandBase & (({
|
|
|
52
52
|
readonly until: number;
|
|
53
53
|
readonly evidenceAt: number;
|
|
54
54
|
readonly mergeLaw: MergeLaw;
|
|
55
|
+
readonly cause?: LimitMarkCause;
|
|
55
56
|
} & MarkTarget) | {
|
|
56
57
|
readonly type: 'clear';
|
|
57
58
|
readonly keys: readonly MarkTarget[];
|
|
58
59
|
/** Absent for explicit user clears; automatic clears carry their evidence time. */
|
|
59
60
|
readonly evidenceAt?: number;
|
|
61
|
+
/** A successful probe clears only this cause, but fences absent/expired keys too. */
|
|
62
|
+
readonly cause?: LimitMarkCause;
|
|
60
63
|
} | {
|
|
61
64
|
readonly type: 'access';
|
|
62
65
|
readonly state: T;
|
package/dist/limits/namespace.js
CHANGED
|
@@ -130,6 +130,10 @@ export function applyLimitsCommands(initial, commands, context) {
|
|
|
130
130
|
evidenceAt: command.evidenceAt,
|
|
131
131
|
baseRevision: command.baseRevision,
|
|
132
132
|
committedRevision: revision,
|
|
133
|
+
...(command.cause === 'rate-limit' ||
|
|
134
|
+
command.cause === 'payment-balance'
|
|
135
|
+
? { cause: command.cause }
|
|
136
|
+
: {}),
|
|
133
137
|
},
|
|
134
138
|
], context.now, clear?.revision);
|
|
135
139
|
marks = marks.filter((m) => timedMarkKeyId(m.key) !== id);
|
|
@@ -137,7 +141,11 @@ export function applyLimitsCommands(initial, commands, context) {
|
|
|
137
141
|
marks.push({ key, mergeLaw: command.mergeLaw, entries });
|
|
138
142
|
}
|
|
139
143
|
else if (command.type === 'clear') {
|
|
140
|
-
const keys = command.keys
|
|
144
|
+
const keys = command.keys
|
|
145
|
+
.map((key) => ({ ...key, account }))
|
|
146
|
+
.filter((key) => command.cause === undefined ||
|
|
147
|
+
!marks.some((mark) => timedMarkKeyId(mark.key) === timedMarkKeyId(key) &&
|
|
148
|
+
mark.entries.some((entry) => entry.cause !== command.cause)));
|
|
141
149
|
const ids = new Set(keys.map(timedMarkKeyId));
|
|
142
150
|
const evidenceAt = command.evidenceAt;
|
|
143
151
|
if (evidenceAt !== undefined &&
|
package/dist/limits/presets.js
CHANGED
|
@@ -50,6 +50,7 @@ const engineQuota = {
|
|
|
50
50
|
hostRetry: 'veto',
|
|
51
51
|
};
|
|
52
52
|
export const confirmedAffinity = immutable({
|
|
53
|
+
unconfirmedRetainLimit: 2,
|
|
53
54
|
evidence: 'per-field-overlay',
|
|
54
55
|
markers: hosts({
|
|
55
56
|
kind: 'reset',
|
|
@@ -163,6 +164,9 @@ export const statusVaultOrder = immutable({
|
|
|
163
164
|
kind: 'hint',
|
|
164
165
|
mergeLaw: 'overwrite',
|
|
165
166
|
defaultMs: 60000,
|
|
167
|
+
defaultMsByKind: { 'payment-balance': 300000 },
|
|
168
|
+
causes: ['rate-limit', 'payment-balance'],
|
|
169
|
+
ignoredKinds: ['payment-cap'],
|
|
166
170
|
minimumMs: 0,
|
|
167
171
|
zero: 'accept',
|
|
168
172
|
hintClock: 'signal',
|
|
@@ -171,6 +175,9 @@ export const statusVaultOrder = immutable({
|
|
|
171
175
|
kind: 'hint',
|
|
172
176
|
mergeLaw: 'overwrite',
|
|
173
177
|
defaultMs: 60000,
|
|
178
|
+
defaultMsByKind: { 'payment-balance': 300000 },
|
|
179
|
+
causes: ['rate-limit', 'payment-balance'],
|
|
180
|
+
ignoredKinds: ['payment-cap'],
|
|
174
181
|
minimumMs: 0,
|
|
175
182
|
zero: 'accept',
|
|
176
183
|
hintClock: 'marker',
|
|
@@ -179,6 +186,9 @@ export const statusVaultOrder = immutable({
|
|
|
179
186
|
kind: 'hint',
|
|
180
187
|
mergeLaw: 'overwrite',
|
|
181
188
|
defaultMs: 60000,
|
|
189
|
+
defaultMsByKind: { 'payment-balance': 300000 },
|
|
190
|
+
causes: ['rate-limit', 'payment-balance'],
|
|
191
|
+
ignoredKinds: ['payment-cap'],
|
|
182
192
|
minimumMs: 0,
|
|
183
193
|
zero: 'accept',
|
|
184
194
|
hintClock: 'signal',
|
|
@@ -207,7 +217,14 @@ export const statusVaultOrder = immutable({
|
|
|
207
217
|
},
|
|
208
218
|
terminalMetadata: 'baseline',
|
|
209
219
|
terminalPolicy: 'status-history',
|
|
210
|
-
terminalStatusHistory: {
|
|
220
|
+
terminalStatusHistory: {
|
|
221
|
+
minRetryMs: 1000,
|
|
222
|
+
defaultRetryMs: 60000,
|
|
223
|
+
paymentBalance: {
|
|
224
|
+
family: 'claustrum-402',
|
|
225
|
+
messageKey: 'payment.insufficient-balance',
|
|
226
|
+
},
|
|
227
|
+
},
|
|
211
228
|
refusals: refusals({
|
|
212
229
|
family: 'claustrum-429',
|
|
213
230
|
messageKey: 'quota.accounts-rate-limited',
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import type { SessionActivityStore } from './activity.js';
|
|
2
2
|
import type { IdentityBinding } from './identity.js';
|
|
3
|
+
import type { LimitMarkCause } from './marker.js';
|
|
3
4
|
import type { LimitsCommand, LimitsNamespace } from './namespace.js';
|
|
4
5
|
import type { LimitsPersistenceOutcome, PersistenceAdapter } from './persistence.js';
|
|
5
6
|
export declare const LIMITS_REGISTRY_KEY: unique symbol;
|
|
@@ -45,5 +46,16 @@ export interface LimitsRegistry {
|
|
|
45
46
|
reload(): Promise<void>;
|
|
46
47
|
dispose(): Promise<void>;
|
|
47
48
|
}
|
|
49
|
+
export type SuccessfulProbeClear = Omit<Extract<LimitsCommand, {
|
|
50
|
+
type: 'clear';
|
|
51
|
+
}>, 'type'> & {
|
|
52
|
+
readonly cause: LimitMarkCause;
|
|
53
|
+
readonly evidenceAt: number;
|
|
54
|
+
};
|
|
55
|
+
/** Publish a recovery fence even when expiry already removed the observed timer.
|
|
56
|
+
* Capture binding/baseRevision with observe before the probe; dispatch to that
|
|
57
|
+
* account joins the clear acknowledgment through beforeDispatch, not here.
|
|
58
|
+
*/
|
|
59
|
+
export declare function clearLimitsAfterProbe(registry: LimitsRegistry, input: SuccessfulProbeClear): void;
|
|
48
60
|
/** Shared owners use one journal/listener; a last-owner replacement waits for handoff. */
|
|
49
61
|
export declare function acquireLimitsRegistry(options: LimitsRegistryOptions): Promise<LimitsRegistry>;
|
package/dist/limits/registry.js
CHANGED
|
@@ -20,6 +20,13 @@ const clock = {
|
|
|
20
20
|
},
|
|
21
21
|
clearTimeout: (timer) => clearTimeout(timer),
|
|
22
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
|
+
}
|
|
23
30
|
function schemaRegistry() {
|
|
24
31
|
for (const symbol of Object.getOwnPropertySymbols(globalThis)) {
|
|
25
32
|
const key = Symbol.keyFor(symbol);
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { Scope } from './scope.js';
|
|
2
|
-
import type { AccountKey } from './signal.js';
|
|
2
|
+
import type { AccountKey, LimitKind } from './signal.js';
|
|
3
3
|
export declare function sameAccount(a: AccountKey, b: AccountKey): boolean;
|
|
4
4
|
export interface RequestExclusion {
|
|
5
5
|
readonly account: AccountKey;
|
|
@@ -17,6 +17,7 @@ export interface RequestHistory {
|
|
|
17
17
|
readonly originalUrl: string;
|
|
18
18
|
readonly requestStartedAt: number;
|
|
19
19
|
readonly saw429: boolean;
|
|
20
|
+
readonly sawPaymentBalance?: boolean;
|
|
20
21
|
readonly lastStatus?: number;
|
|
21
22
|
readonly tried: readonly RequestExclusion[];
|
|
22
23
|
readonly excludedForRequest: readonly RequestExclusion[];
|
|
@@ -38,6 +39,7 @@ export type RequestHistoryEvent = {
|
|
|
38
39
|
readonly account: AccountKey;
|
|
39
40
|
readonly scope: Scope;
|
|
40
41
|
readonly status?: number;
|
|
42
|
+
readonly kind?: LimitKind;
|
|
41
43
|
} | {
|
|
42
44
|
readonly type: 'retain';
|
|
43
45
|
readonly account: AccountKey;
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { AccountKey } from './signal.js';
|
|
2
|
+
/** Plugin-owned turn budgets, independent of individual logical request histories. */
|
|
3
|
+
export declare class UnconfirmedRetainCounter {
|
|
4
|
+
private readonly maxSessions;
|
|
5
|
+
private readonly sessions;
|
|
6
|
+
constructor(maxSessions?: number);
|
|
7
|
+
count(sessionId: string, turnId: string, account: AccountKey): number;
|
|
8
|
+
/** Call once after accepting a decision with incrementUnconfirmedRetain. */
|
|
9
|
+
increment(sessionId: string, turnId: string, account: AccountKey): void;
|
|
10
|
+
/** Clear on moves, API fallback and session lifecycle boundaries. */
|
|
11
|
+
clear(sessionId: string): void;
|
|
12
|
+
clearAll(): void;
|
|
13
|
+
}
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { sameAccount } from './request-history.js';
|
|
2
|
+
/** Plugin-owned turn budgets, independent of individual logical request histories. */
|
|
3
|
+
export class UnconfirmedRetainCounter {
|
|
4
|
+
maxSessions;
|
|
5
|
+
sessions = new Map();
|
|
6
|
+
constructor(maxSessions = 4096) {
|
|
7
|
+
this.maxSessions = maxSessions;
|
|
8
|
+
if (!Number.isSafeInteger(maxSessions) || maxSessions < 1)
|
|
9
|
+
throw new RangeError('maxSessions must be a positive safe integer');
|
|
10
|
+
}
|
|
11
|
+
count(sessionId, turnId, account) {
|
|
12
|
+
const entry = this.sessions.get(sessionId);
|
|
13
|
+
return entry?.turnId === turnId && sameAccount(entry.account, account)
|
|
14
|
+
? entry.count
|
|
15
|
+
: 0;
|
|
16
|
+
}
|
|
17
|
+
/** Call once after accepting a decision with incrementUnconfirmedRetain. */
|
|
18
|
+
increment(sessionId, turnId, account) {
|
|
19
|
+
const count = this.count(sessionId, turnId, account);
|
|
20
|
+
if (!count) {
|
|
21
|
+
this.sessions.delete(sessionId);
|
|
22
|
+
if (this.sessions.size >= this.maxSessions) {
|
|
23
|
+
const oldest = this.sessions.keys().next().value;
|
|
24
|
+
if (oldest !== undefined)
|
|
25
|
+
this.sessions.delete(oldest);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
this.sessions.set(sessionId, {
|
|
29
|
+
turnId,
|
|
30
|
+
account: { ...account },
|
|
31
|
+
count: count + 1,
|
|
32
|
+
});
|
|
33
|
+
}
|
|
34
|
+
/** Clear on moves, API fallback and session lifecycle boundaries. */
|
|
35
|
+
clear(sessionId) {
|
|
36
|
+
this.sessions.delete(sessionId);
|
|
37
|
+
}
|
|
38
|
+
clearAll() {
|
|
39
|
+
this.sessions.clear();
|
|
40
|
+
}
|
|
41
|
+
}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cortexkit/common-auth",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.35.0",
|
|
4
4
|
"description": "Shared code for the CortexKit auth plugins: account pool, quota and routing, commands and auth menu, OpenCode 2 hooks, Claustrum custody, and plumbing (loopback RPC, file locks, logger, sidebar state, TUI preferences and build).",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"repository": {
|