@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.
- package/dist/claustrum/consumer.d.ts +12 -0
- package/dist/claustrum/consumer.js +36 -0
- package/dist/claustrum/custody.d.ts +16 -4
- package/dist/claustrum/custody.js +74 -9
- package/dist/claustrum/hub.d.ts +3 -2
- package/dist/claustrum/hub.js +8 -0
- package/dist/claustrum/index.d.ts +1 -0
- package/dist/claustrum/roster.d.ts +2 -0
- package/dist/claustrum/roster.js +2 -0
- package/dist/claustrum/usage.d.ts +41 -0
- package/dist/claustrum/usage.js +145 -0
- package/dist/commands/builtins.d.ts +5 -0
- package/dist/commands/builtins.js +38 -0
- package/dist/fs/private-files.d.ts +5 -0
- package/dist/fs/private-files.js +7 -0
- package/dist/fs/refresh-file-lock.js +142 -47
- package/dist/fs/with-lock.js +2 -5
- package/dist/limits/activity.d.ts +26 -0
- package/dist/limits/activity.js +52 -0
- package/dist/limits/axes.d.ts +63 -0
- package/dist/limits/axes.js +7 -0
- package/dist/limits/bridge.d.ts +4 -0
- package/dist/limits/bridge.js +10 -0
- package/dist/limits/decide.d.ts +141 -0
- package/dist/limits/decide.js +383 -0
- package/dist/limits/duration.d.ts +8 -0
- package/dist/limits/duration.js +20 -0
- package/dist/limits/envelope-loss.d.ts +29 -0
- package/dist/limits/envelope-loss.js +150 -0
- package/dist/limits/families.d.ts +57 -0
- package/dist/limits/families.js +143 -0
- package/dist/limits/header-classifier.d.ts +9 -0
- package/dist/limits/header-classifier.js +121 -0
- package/dist/limits/hold.d.ts +13 -0
- package/dist/limits/hold.js +25 -0
- package/dist/limits/identity.d.ts +14 -0
- package/dist/limits/identity.js +21 -0
- package/dist/limits/index.d.ts +44 -0
- package/dist/limits/index.js +25 -0
- package/dist/limits/jitter.d.ts +2 -0
- package/dist/limits/jitter.js +9 -0
- package/dist/limits/labels.d.ts +3 -0
- package/dist/limits/labels.js +11 -0
- package/dist/limits/marker.d.ts +64 -0
- package/dist/limits/marker.js +96 -0
- package/dist/limits/merge-laws.d.ts +14 -0
- package/dist/limits/merge-laws.js +31 -0
- package/dist/limits/namespace.d.ts +89 -0
- package/dist/limits/namespace.js +183 -0
- package/dist/limits/persistence.d.ts +33 -0
- package/dist/limits/persistence.js +9 -0
- package/dist/limits/pi-wait.d.ts +16 -0
- package/dist/limits/pi-wait.js +51 -0
- package/dist/limits/pool-adapter.d.ts +16 -0
- package/dist/limits/pool-adapter.js +162 -0
- package/dist/limits/presets.d.ts +11 -0
- package/dist/limits/presets.js +223 -0
- package/dist/limits/registry.d.ts +49 -0
- package/dist/limits/registry.js +471 -0
- package/dist/limits/request-history.d.ts +77 -0
- package/dist/limits/request-history.js +117 -0
- package/dist/limits/reset.d.ts +21 -0
- package/dist/limits/reset.js +44 -0
- package/dist/limits/routing-hold.d.ts +16 -0
- package/dist/limits/routing-hold.js +23 -0
- package/dist/limits/scope.d.ts +12 -0
- package/dist/limits/scope.js +10 -0
- package/dist/limits/signal.d.ts +41 -0
- package/dist/limits/signal.js +1 -0
- package/dist/limits/terminal.d.ts +52 -0
- package/dist/limits/terminal.js +133 -0
- package/dist/limits/vault-adapter.d.ts +16 -0
- package/dist/limits/vault-adapter.js +123 -0
- package/dist/limits/vault.d.ts +1 -0
- package/dist/limits/vault.js +1 -0
- package/dist/limits/wake.d.ts +21 -0
- package/dist/limits/wake.js +47 -0
- package/dist/limits/wording.d.ts +25 -0
- package/dist/limits/wording.js +114 -0
- package/dist/opencode2/index.d.ts +1 -1
- package/dist/opencode2/install.d.ts +2 -2
- package/dist/opencode2/install.js +161 -18
- package/dist/opencode2/types.d.ts +95 -9
- package/dist/routing/admission.d.ts +7 -2
- package/dist/routing/admission.js +17 -7
- package/dist/routing-accessor/handle.d.ts +1 -0
- package/dist/routing-accessor/handle.js +10 -0
- package/dist/routing-accessor/index.d.ts +13 -3
- package/dist/routing-accessor/index.js +11 -10
- package/dist/rpc/port-file.d.ts +12 -3
- package/dist/rpc/port-file.js +46 -4
- package/dist/store/attribution.js +3 -2
- package/dist/store/errors.d.ts +1 -1
- package/dist/store/hooks.d.ts +5 -1
- package/dist/store/hooks.js +20 -5
- package/dist/store/index.d.ts +1 -0
- package/dist/store/limits-namespace.d.ts +7 -0
- package/dist/store/limits-namespace.js +34 -0
- package/dist/store/pool.d.ts +10 -1
- package/dist/store/pool.js +2 -0
- package/dist/store/provider-state.js +5 -5
- package/dist/store/refresh.js +1 -1
- package/dist/store/schema.js +9 -4
- package/dist/store/settings.d.ts +2 -0
- package/dist/store/settings.js +11 -4
- package/package.json +10 -2
|
@@ -0,0 +1,143 @@
|
|
|
1
|
+
import { formatDuration, formatReset } from './duration.js';
|
|
2
|
+
import { containsEmail, sanitizeRefusalLabel } from './labels.js';
|
|
3
|
+
import { hasUnsafeWording, } from './wording.js';
|
|
4
|
+
export class ClaudeIncompleteError extends Error {
|
|
5
|
+
code = 'ECONNRESET';
|
|
6
|
+
syscall = 'sticky-routing';
|
|
7
|
+
isRetryable = true;
|
|
8
|
+
constructor(message) {
|
|
9
|
+
super(message, { cause: { code: 'ECONNRESET', syscall: 'sticky-routing' } });
|
|
10
|
+
this.name = 'ClaudeIncompleteError';
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
/** Compute metadata at delivery time, after time spent showing a notice. */
|
|
14
|
+
export function retryAfterSeconds(retryAfterMs, noticeDelayMs = 0) {
|
|
15
|
+
if (retryAfterMs === undefined ||
|
|
16
|
+
!Number.isFinite(retryAfterMs) ||
|
|
17
|
+
retryAfterMs < 0) {
|
|
18
|
+
return undefined;
|
|
19
|
+
}
|
|
20
|
+
const remaining = retryAfterMs - elapsedNotice(noticeDelayMs);
|
|
21
|
+
return remaining >= 0 ? Math.ceil(remaining / 1000) : undefined;
|
|
22
|
+
}
|
|
23
|
+
function elapsedNotice(ms) {
|
|
24
|
+
return Number.isFinite(ms) && ms >= 0 ? ms : 0;
|
|
25
|
+
}
|
|
26
|
+
function keptReset(input) {
|
|
27
|
+
return input.resetAt !== undefined && Number.isFinite(input.resetAt)
|
|
28
|
+
? input.resetAt
|
|
29
|
+
: undefined;
|
|
30
|
+
}
|
|
31
|
+
function resetClause(reset) {
|
|
32
|
+
return reset === undefined ? 'The reset is unknown.' : `Reset at ${reset}.`;
|
|
33
|
+
}
|
|
34
|
+
function defaultText(family, reset, retry, nonRetryable) {
|
|
35
|
+
const retryClause = !nonRetryable && retry !== undefined
|
|
36
|
+
? ` Retry in ${formatDuration(retry * 1000)}.`
|
|
37
|
+
: '';
|
|
38
|
+
const start = family === 'pi-final'
|
|
39
|
+
? 'The request cannot continue.'
|
|
40
|
+
: 'No account is available.';
|
|
41
|
+
return `${start}${retryClause} ${resetClause(reset)}`;
|
|
42
|
+
}
|
|
43
|
+
function fallbackText(input, now, nonRetryable) {
|
|
44
|
+
const resetAt = keptReset(input);
|
|
45
|
+
const reset = resetAt === undefined ? undefined : formatReset({ resetAt, now });
|
|
46
|
+
const retry = retryAfterSeconds(input.retryAfterMs, input.noticeDelayMs);
|
|
47
|
+
return defaultText(input.family, reset, retry, nonRetryable);
|
|
48
|
+
}
|
|
49
|
+
function textFor(input, nonRetryable) {
|
|
50
|
+
const now = input.now + elapsedNotice(input.noticeDelayMs ?? 0);
|
|
51
|
+
const fallback = () => fallbackText(input, now, nonRetryable);
|
|
52
|
+
try {
|
|
53
|
+
const resetAt = keptReset(input);
|
|
54
|
+
const reset = resetAt === undefined
|
|
55
|
+
? undefined
|
|
56
|
+
: (input.messages?.formatReset ?? formatReset)({ resetAt, now });
|
|
57
|
+
const retry = retryAfterSeconds(input.retryAfterMs, input.noticeDelayMs);
|
|
58
|
+
// Whitelist text parameters rather than forwarding decision facts, which may
|
|
59
|
+
// contain account or credential identifiers. Labels are an explicit exception.
|
|
60
|
+
const parameters = Object.freeze({
|
|
61
|
+
labels: Object.freeze(input.labelPolicy === 'relogin'
|
|
62
|
+
? (input.parameters?.labels ?? []).map(sanitizeRefusalLabel)
|
|
63
|
+
: []),
|
|
64
|
+
reset,
|
|
65
|
+
retryIn: !nonRetryable && retry !== undefined
|
|
66
|
+
? formatDuration(retry * 1000)
|
|
67
|
+
: undefined,
|
|
68
|
+
});
|
|
69
|
+
const rendered = input.messages?.render(input.messageKey, parameters, nonRetryable);
|
|
70
|
+
return typeof rendered === 'string'
|
|
71
|
+
? rendered
|
|
72
|
+
: defaultText(input.family, reset, retry, nonRetryable);
|
|
73
|
+
}
|
|
74
|
+
catch {
|
|
75
|
+
// A request must still get its refusal if a plugin's text renderer fails.
|
|
76
|
+
return fallback();
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
function bodyFor(family, message) {
|
|
80
|
+
switch (family) {
|
|
81
|
+
case 'openai-429':
|
|
82
|
+
return JSON.stringify({
|
|
83
|
+
error: {
|
|
84
|
+
message,
|
|
85
|
+
type: 'rate_limit_exceeded',
|
|
86
|
+
code: 'rate_limit_exceeded',
|
|
87
|
+
},
|
|
88
|
+
});
|
|
89
|
+
case 'claude-429':
|
|
90
|
+
return JSON.stringify({
|
|
91
|
+
type: 'error',
|
|
92
|
+
error: { type: 'rate_limit_error', message },
|
|
93
|
+
});
|
|
94
|
+
case 'json-412':
|
|
95
|
+
return JSON.stringify({
|
|
96
|
+
error: { code: 412, status: 'FAILED_PRECONDITION', message },
|
|
97
|
+
});
|
|
98
|
+
case 'claustrum-429':
|
|
99
|
+
return JSON.stringify({ error: 'claustrum-auth: accounts-rate-limited' });
|
|
100
|
+
default:
|
|
101
|
+
return message;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
/** Pure wire construction: the caller sends the response, emits text, or throws the error. */
|
|
105
|
+
export function buildRefusal(input) {
|
|
106
|
+
const nonRetryable = input.family === 'json-412' || input.family === 'pi-final';
|
|
107
|
+
const attributes = {
|
|
108
|
+
family: input.family,
|
|
109
|
+
disposition: 'refuse',
|
|
110
|
+
retryable: !nonRetryable,
|
|
111
|
+
hostRetry: nonRetryable ? 'veto' : 'leave',
|
|
112
|
+
};
|
|
113
|
+
let body = bodyFor(input.family, textFor(input, nonRetryable));
|
|
114
|
+
if (nonRetryable && (hasUnsafeWording(body) || containsEmail(body))) {
|
|
115
|
+
// Rebuild from retained facts, never from plugin text or fact-supplied labels.
|
|
116
|
+
const now = input.now + elapsedNotice(input.noticeDelayMs ?? 0);
|
|
117
|
+
body = bodyFor(input.family, fallbackText(input, now, true));
|
|
118
|
+
}
|
|
119
|
+
if (input.family === 'claude-econnreset') {
|
|
120
|
+
return {
|
|
121
|
+
...attributes,
|
|
122
|
+
kind: 'throw',
|
|
123
|
+
error: new ClaudeIncompleteError(body),
|
|
124
|
+
};
|
|
125
|
+
}
|
|
126
|
+
if (input.family === 'pi-final')
|
|
127
|
+
return { ...attributes, kind: 'text', body };
|
|
128
|
+
const headers = new Headers(input.family === 'json-412' ? input.extraHeaders : undefined);
|
|
129
|
+
headers.set('content-type', 'application/json');
|
|
130
|
+
// Only the library's post-notice estimate may control this header, including
|
|
131
|
+
// when a provider supplied an old Retry-After among the extra headers.
|
|
132
|
+
headers.delete('retry-after');
|
|
133
|
+
const retry = retryAfterSeconds(input.retryAfterMs, input.noticeDelayMs);
|
|
134
|
+
if (retry !== undefined)
|
|
135
|
+
headers.set('retry-after', String(retry));
|
|
136
|
+
return {
|
|
137
|
+
...attributes,
|
|
138
|
+
kind: 'http',
|
|
139
|
+
status: input.family === 'json-412' ? 412 : 429,
|
|
140
|
+
headers,
|
|
141
|
+
body,
|
|
142
|
+
};
|
|
143
|
+
}
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type ResolvedReset } from './reset.js';
|
|
2
|
+
import type { ClassifierInput, LimitSignal } from './signal.js';
|
|
3
|
+
export declare function resolveRetryAfter(headers: Headers, now: number): ResolvedReset | undefined;
|
|
4
|
+
/** Importing this module alone does not enable its header reset sources. */
|
|
5
|
+
export declare function resolveHeaderReset(headers: Headers, now: number): ResolvedReset | undefined;
|
|
6
|
+
/** Generic status hints never assert quota exhaustion, even on a 429. */
|
|
7
|
+
export declare function classifyHeaders(input: ClassifierInput): LimitSignal | undefined;
|
|
8
|
+
/** Retry-After-only classification leaves default timers to the marker. */
|
|
9
|
+
export declare function classifyRetryAfter(input: ClassifierInput): LimitSignal | undefined;
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
import { resolveReset } from './reset.js';
|
|
2
|
+
const delta = /^(?:\d+(?:\.\d*)?|\.\d+)$/;
|
|
3
|
+
const httpDate = /^(?:[A-Za-z]{3}, \d{2} [A-Za-z]{3} \d{4} \d{2}:\d{2}:\d{2} GMT|[A-Za-z]+, \d{2}-[A-Za-z]{3}-\d{2} \d{2}:\d{2}:\d{2} GMT|[A-Za-z]{3} [A-Za-z]{3} {1,2}\d{1,2} \d{2}:\d{2}:\d{2} \d{4})$/;
|
|
4
|
+
/** HTTP dates include a month name; Date.parse alone also accepts numbers and junk. */
|
|
5
|
+
function retryAfter(value, now) {
|
|
6
|
+
if (value === null)
|
|
7
|
+
return undefined;
|
|
8
|
+
const text = value.trim();
|
|
9
|
+
if (delta.test(text)) {
|
|
10
|
+
const ms = Number(text) * 1000;
|
|
11
|
+
return Number.isFinite(ms) ? ms : undefined;
|
|
12
|
+
}
|
|
13
|
+
if (!httpDate.test(text))
|
|
14
|
+
return undefined;
|
|
15
|
+
const date = Date.parse(text);
|
|
16
|
+
return Number.isFinite(date) ? Math.max(0, date - now) : undefined;
|
|
17
|
+
}
|
|
18
|
+
function resetDuration(value) {
|
|
19
|
+
const text = value.trim();
|
|
20
|
+
if (delta.test(text)) {
|
|
21
|
+
const ms = Number(text) * 1000;
|
|
22
|
+
return Number.isFinite(ms) ? ms : undefined;
|
|
23
|
+
}
|
|
24
|
+
const parts = text.matchAll(/(\d+(?:\.\d*)?|\.\d+)(ms|s|m|h|d)/g);
|
|
25
|
+
let consumed = '';
|
|
26
|
+
let ms = 0;
|
|
27
|
+
const units = { ms: 1, s: 1000, m: 60000, h: 3600000, d: 86400000 };
|
|
28
|
+
for (const part of parts) {
|
|
29
|
+
consumed += part[0];
|
|
30
|
+
ms += Number(part[1]) * units[part[2]];
|
|
31
|
+
}
|
|
32
|
+
return consumed === text && consumed !== '' && Number.isFinite(ms)
|
|
33
|
+
? ms
|
|
34
|
+
: undefined;
|
|
35
|
+
}
|
|
36
|
+
export function resolveRetryAfter(headers, now) {
|
|
37
|
+
return resolveReset([
|
|
38
|
+
{
|
|
39
|
+
source: 'retry-after',
|
|
40
|
+
value: retryAfter(headers.get('retry-after'), now),
|
|
41
|
+
unit: 'delay-ms',
|
|
42
|
+
zero: 'accept',
|
|
43
|
+
},
|
|
44
|
+
], now);
|
|
45
|
+
}
|
|
46
|
+
/** Importing this module alone does not enable its header reset sources. */
|
|
47
|
+
export function resolveHeaderReset(headers, now) {
|
|
48
|
+
const retry = resolveRetryAfter(headers, now);
|
|
49
|
+
if (retry)
|
|
50
|
+
return retry;
|
|
51
|
+
let earliest;
|
|
52
|
+
for (const [name, value] of headers) {
|
|
53
|
+
if (!name.startsWith('x-ratelimit-reset-'))
|
|
54
|
+
continue;
|
|
55
|
+
const reset = resolveReset([
|
|
56
|
+
{
|
|
57
|
+
source: name,
|
|
58
|
+
value: resetDuration(value),
|
|
59
|
+
unit: 'delay-ms',
|
|
60
|
+
zero: 'skip',
|
|
61
|
+
},
|
|
62
|
+
], now);
|
|
63
|
+
if (reset && (!earliest || reset.resetAt < earliest.resetAt))
|
|
64
|
+
earliest = reset;
|
|
65
|
+
}
|
|
66
|
+
return earliest;
|
|
67
|
+
}
|
|
68
|
+
function hintSignal(input, reset) {
|
|
69
|
+
return {
|
|
70
|
+
account: input.account,
|
|
71
|
+
kind: input.status === 429 ? 'rate-limit' : 'capacity',
|
|
72
|
+
reason: input.status === 429 ? 'rate-limit' : 'capacity',
|
|
73
|
+
status: input.status,
|
|
74
|
+
scope: { kind: 'pool' },
|
|
75
|
+
observedAt: input.now,
|
|
76
|
+
windows: [
|
|
77
|
+
{
|
|
78
|
+
window: 'retry',
|
|
79
|
+
confirmed: false,
|
|
80
|
+
confirmedByReading: false,
|
|
81
|
+
observedAt: input.now,
|
|
82
|
+
provenance: 'http-status',
|
|
83
|
+
...(reset ? { resetAt: reset.resetAt, resetSource: reset.source } : {}),
|
|
84
|
+
},
|
|
85
|
+
],
|
|
86
|
+
...(reset
|
|
87
|
+
? {
|
|
88
|
+
retryAfterMs: reset.resetAt - input.now,
|
|
89
|
+
retryAfterSource: reset.source,
|
|
90
|
+
}
|
|
91
|
+
: {}),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
/** Generic status hints never assert quota exhaustion, even on a 429. */
|
|
95
|
+
export function classifyHeaders(input) {
|
|
96
|
+
if (input.status !== 429 && input.status !== 503)
|
|
97
|
+
return undefined;
|
|
98
|
+
return hintSignal(input, resolveHeaderReset(input.headers, input.now));
|
|
99
|
+
}
|
|
100
|
+
/** Retry-After-only classification leaves default timers to the marker. */
|
|
101
|
+
export function classifyRetryAfter(input) {
|
|
102
|
+
if (input.status !== 429)
|
|
103
|
+
return undefined;
|
|
104
|
+
const raw = input.headers.get('retry-after')?.trim() ?? '';
|
|
105
|
+
const numeric = raw === '' ? Number.NaN : Number(raw);
|
|
106
|
+
const parsed = Number.isFinite(numeric) && numeric >= 0
|
|
107
|
+
? resolveReset([
|
|
108
|
+
{
|
|
109
|
+
source: 'retry-after',
|
|
110
|
+
value: numeric * 1000,
|
|
111
|
+
unit: 'delay-ms',
|
|
112
|
+
zero: 'accept',
|
|
113
|
+
},
|
|
114
|
+
], input.now)
|
|
115
|
+
: resolveRetryAfter(input.headers, input.now);
|
|
116
|
+
const usable = parsed && (Number.isFinite(numeric) || parsed.resetAt > input.now)
|
|
117
|
+
? parsed
|
|
118
|
+
: undefined;
|
|
119
|
+
// The marker supplies its default timer; that timer is not a known reset.
|
|
120
|
+
return hintSignal(input, usable);
|
|
121
|
+
}
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
import type { SessionActivity } from './activity.js';
|
|
2
|
+
import type { HoldFacts } from './decide.js';
|
|
3
|
+
import type { AccountKey } from './signal.js';
|
|
4
|
+
export type MaxSameAccountWait = 0 | 15 | 'max';
|
|
5
|
+
export declare const MAX_SAME_ACCOUNT_HOLD_MS = 3621000;
|
|
6
|
+
/** Pass routing.maxSameAccountWait without coercing persisted values. */
|
|
7
|
+
export declare function readMaxSameAccountWait(value: unknown): MaxSameAccountWait;
|
|
8
|
+
/** Resolve a session snapshot into the pure reducer's same-account bounds. */
|
|
9
|
+
export declare function sameAccountHoldFacts(input: {
|
|
10
|
+
readonly activity?: SessionActivity;
|
|
11
|
+
readonly accountKey: AccountKey;
|
|
12
|
+
readonly maxSameAccountWait?: unknown;
|
|
13
|
+
}): HoldFacts | undefined;
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import { effectiveCacheTtlMs } from './activity.js';
|
|
2
|
+
import { sameAccount } from './request-history.js';
|
|
3
|
+
export const MAX_SAME_ACCOUNT_HOLD_MS = 3_621_000;
|
|
4
|
+
/** Pass routing.maxSameAccountWait without coercing persisted values. */
|
|
5
|
+
export function readMaxSameAccountWait(value) {
|
|
6
|
+
return value === 0 || value === 15 || value === 'max' ? value : 15;
|
|
7
|
+
}
|
|
8
|
+
/** Resolve a session snapshot into the pure reducer's same-account bounds. */
|
|
9
|
+
export function sameAccountHoldFacts(input) {
|
|
10
|
+
const setting = readMaxSameAccountWait(input.maxSameAccountWait);
|
|
11
|
+
const record = input.activity;
|
|
12
|
+
if (setting === 0 ||
|
|
13
|
+
!record ||
|
|
14
|
+
!sameAccount(record.accountKey, input.accountKey) ||
|
|
15
|
+
!Number.isFinite(record.lastAcceptedAt))
|
|
16
|
+
return undefined;
|
|
17
|
+
const ttlMs = effectiveCacheTtlMs(record.ttlMs);
|
|
18
|
+
const cacheExpiresAt = record.lastAcceptedAt + ttlMs;
|
|
19
|
+
if (ttlMs === 0 || !Number.isFinite(cacheExpiresAt))
|
|
20
|
+
return undefined;
|
|
21
|
+
return {
|
|
22
|
+
cacheExpiresAt,
|
|
23
|
+
maxWaitMs: setting === 'max' ? Number.POSITIVE_INFINITY : 900000,
|
|
24
|
+
};
|
|
25
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { AccountKey } from './signal.js';
|
|
2
|
+
/** Binding metadata is not part of the timed-mark lookup key. */
|
|
3
|
+
export interface IdentityBinding {
|
|
4
|
+
readonly account: AccountKey;
|
|
5
|
+
readonly identity?: string;
|
|
6
|
+
readonly credentialEpoch: string;
|
|
7
|
+
}
|
|
8
|
+
/** Compatibility is a wildcard test, not a transitive identity equivalence. */
|
|
9
|
+
export declare function isIdentityCompatible(a: IdentityBinding, b: IdentityBinding): boolean;
|
|
10
|
+
/** An unknown observation must not erase a previously verified identity. */
|
|
11
|
+
export declare function retainVerifiedIdentity(previous: IdentityBinding, current: IdentityBinding): IdentityBinding;
|
|
12
|
+
/** Called with bindings read under the adapter's commit lock, including on refresh. */
|
|
13
|
+
export type AuthorizeCredentialEpoch = (observed: IdentityBinding, authoritative: IdentityBinding) => boolean;
|
|
14
|
+
export declare function validateIdentityFence(observed: IdentityBinding, authoritative: IdentityBinding, authorizeEpoch: AuthorizeCredentialEpoch): 'identity-replaced' | 'credential-epoch' | undefined;
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
import { sameAccount } from './request-history.js';
|
|
2
|
+
/** Compatibility is a wildcard test, not a transitive identity equivalence. */
|
|
3
|
+
export function isIdentityCompatible(a, b) {
|
|
4
|
+
return (sameAccount(a.account, b.account) &&
|
|
5
|
+
(a.identity === undefined ||
|
|
6
|
+
b.identity === undefined ||
|
|
7
|
+
a.identity === b.identity));
|
|
8
|
+
}
|
|
9
|
+
/** An unknown observation must not erase a previously verified identity. */
|
|
10
|
+
export function retainVerifiedIdentity(previous, current) {
|
|
11
|
+
if (!isIdentityCompatible(previous, current))
|
|
12
|
+
return current;
|
|
13
|
+
return { ...current, identity: current.identity ?? previous.identity };
|
|
14
|
+
}
|
|
15
|
+
export function validateIdentityFence(observed, authoritative, authorizeEpoch) {
|
|
16
|
+
if (!isIdentityCompatible(observed, authoritative))
|
|
17
|
+
return 'identity-replaced';
|
|
18
|
+
if (!authorizeEpoch(observed, authoritative))
|
|
19
|
+
return 'credential-epoch';
|
|
20
|
+
return undefined;
|
|
21
|
+
}
|
|
@@ -0,0 +1,44 @@
|
|
|
1
|
+
export type { AcceptedActivity, SessionActivity, SessionActivityStore, } from './activity.js';
|
|
2
|
+
export { createSessionActivityStore, effectiveCacheTtlMs, } from './activity.js';
|
|
3
|
+
export type { DecisionFamily, HostValues, LimitAxes, LimitHost, RefusalPolicy, RefusalReason, UnknownLimitPolicy, } from './axes.js';
|
|
4
|
+
export { marksAfterSuccess } from './axes.js';
|
|
5
|
+
export { toOpenCode2LimitSignal } from './bridge.js';
|
|
6
|
+
export type { HoldFacts, LimitCandidate, LimitDecision, ModeSelection, PolicyFacts, TerminalFacts, TimedBlocker, WaitCheckpoint, } from './decide.js';
|
|
7
|
+
export { decideAfterLimit } from './decide.js';
|
|
8
|
+
export type { ResetFormatInput, ResetFormatter } from './duration.js';
|
|
9
|
+
export { formatDuration, formatReset } from './duration.js';
|
|
10
|
+
export type { BuiltRefusal, HostRetry, HttpRefusal, OpenCode1Family, RefusalFamily, RefusalInput, TextRefusal, ThrownRefusal, } from './families.js';
|
|
11
|
+
export { buildRefusal, ClaudeIncompleteError, retryAfterSeconds, } from './families.js';
|
|
12
|
+
export { classifyHeaders, classifyRetryAfter, resolveHeaderReset, resolveRetryAfter, } from './header-classifier.js';
|
|
13
|
+
export type { MaxSameAccountWait } from './hold.js';
|
|
14
|
+
export { MAX_SAME_ACCOUNT_HOLD_MS, readMaxSameAccountWait, sameAccountHoldFacts, } from './hold.js';
|
|
15
|
+
export type { AuthorizeCredentialEpoch, IdentityBinding, } from './identity.js';
|
|
16
|
+
export { isIdentityCompatible, retainVerifiedIdentity, validateIdentityFence, } from './identity.js';
|
|
17
|
+
export { holdDelayMs } from './jitter.js';
|
|
18
|
+
export { sanitizeRefusalLabel } from './labels.js';
|
|
19
|
+
export type { FailureEvent, FailureHistory, FailureLadderAxes, FailureStreak, LimitMark, MarkerAxes, MarkerHistory, MergeLaw, } from './marker.js';
|
|
20
|
+
export { ANTIGRAVITY_FAILURE_LADDER, markFromSignal, markIsActive, reduceFailureHistory, } from './marker.js';
|
|
21
|
+
export type { AccessOrder, TimedMarkEntry } from './merge-laws.js';
|
|
22
|
+
export { mergeAccessState, mergeTimedMarkEntries } from './merge-laws.js';
|
|
23
|
+
export type { ClearTombstone, CommittedOperation, LimitsCommand, LimitsCommandOutcome, LimitsMergeContext, LimitsMergeResult, LimitsNamespace, LimitsRejection, MarkTarget, NamespaceAccess, NamespaceMark, TimedMarkKey, } from './namespace.js';
|
|
24
|
+
export { applyLimitsCommands, createLimitsNamespace, LIMITS_HISTORY_BOUND, pruneLimitsNamespace, timedMarkKeyId, } from './namespace.js';
|
|
25
|
+
export type { LimitsPersistenceCommit, LimitsPersistenceOutcome, LimitsPersistenceSnapshot, PersistenceAdapter, } from './persistence.js';
|
|
26
|
+
export { LimitsPersistenceRefusal } from './persistence.js';
|
|
27
|
+
export type { PiWaitOptions, PiWaitResult } from './pi-wait.js';
|
|
28
|
+
export { waitForPi } from './pi-wait.js';
|
|
29
|
+
export { createPoolLimitsAdapter, type PoolLimitsAdapterOptions, } from './pool-adapter.js';
|
|
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';
|
|
33
|
+
export type { RequestExclusion, RequestHistory, RequestHistoryEvent, RetainHistory, } from './request-history.js';
|
|
34
|
+
export { commitRequestExclusion, createRequestHistory, isRequestExcluded, REQUEST_EXCLUSION_EFFECTS, reduceRequestHistory, sameAccount, } from './request-history.js';
|
|
35
|
+
export type { ResetSource, ResolvedReset } from './reset.js';
|
|
36
|
+
export { resolveNamedWindowReset, resolveReset } from './reset.js';
|
|
37
|
+
export { holdWaitMaxS } from './routing-hold.js';
|
|
38
|
+
export type { FamilyOf, Scope } from './scope.js';
|
|
39
|
+
export { scopeCovers } from './scope.js';
|
|
40
|
+
export type { AccountKey, ClassifierInput, LimitClassifier, LimitKind, LimitSignal, LimitWindow, } from './signal.js';
|
|
41
|
+
export type { TerminalCandidate, TerminalReset, TerminalScanFacts, TerminalWindow, } from './terminal.js';
|
|
42
|
+
export { scanTerminalReset } from './terminal.js';
|
|
43
|
+
export type { LimitMessageOptions, LimitMessages, MessageParameters, MessageTemplate, } from './wording.js';
|
|
44
|
+
export { hasUnsafeWording, registerLimitMessages, UnsafeWordingError, } from './wording.js';
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
export { createSessionActivityStore, effectiveCacheTtlMs, } from './activity.js';
|
|
2
|
+
export { marksAfterSuccess } from './axes.js';
|
|
3
|
+
export { toOpenCode2LimitSignal } from './bridge.js';
|
|
4
|
+
export { decideAfterLimit } from './decide.js';
|
|
5
|
+
export { formatDuration, formatReset } from './duration.js';
|
|
6
|
+
export { buildRefusal, ClaudeIncompleteError, retryAfterSeconds, } from './families.js';
|
|
7
|
+
export { classifyHeaders, classifyRetryAfter, resolveHeaderReset, resolveRetryAfter, } from './header-classifier.js';
|
|
8
|
+
export { MAX_SAME_ACCOUNT_HOLD_MS, readMaxSameAccountWait, sameAccountHoldFacts, } from './hold.js';
|
|
9
|
+
export { isIdentityCompatible, retainVerifiedIdentity, validateIdentityFence, } from './identity.js';
|
|
10
|
+
export { holdDelayMs } from './jitter.js';
|
|
11
|
+
export { sanitizeRefusalLabel } from './labels.js';
|
|
12
|
+
export { ANTIGRAVITY_FAILURE_LADDER, markFromSignal, markIsActive, reduceFailureHistory, } from './marker.js';
|
|
13
|
+
export { mergeAccessState, mergeTimedMarkEntries } from './merge-laws.js';
|
|
14
|
+
export { applyLimitsCommands, createLimitsNamespace, LIMITS_HISTORY_BOUND, pruneLimitsNamespace, timedMarkKeyId, } from './namespace.js';
|
|
15
|
+
export { LimitsPersistenceRefusal } from './persistence.js';
|
|
16
|
+
export { waitForPi } from './pi-wait.js';
|
|
17
|
+
export { createPoolLimitsAdapter, } from './pool-adapter.js';
|
|
18
|
+
export { confirmedAffinity, earliestPoolEngine, limitPresets, statusVaultOrder, windowRouter, } from './presets.js';
|
|
19
|
+
export { acquireLimitsRegistry, LIMITS_REGISTRY_KEY } from './registry.js';
|
|
20
|
+
export { commitRequestExclusion, createRequestHistory, isRequestExcluded, REQUEST_EXCLUSION_EFFECTS, reduceRequestHistory, sameAccount, } from './request-history.js';
|
|
21
|
+
export { resolveNamedWindowReset, resolveReset } from './reset.js';
|
|
22
|
+
export { holdWaitMaxS } from './routing-hold.js';
|
|
23
|
+
export { scopeCovers } from './scope.js';
|
|
24
|
+
export { scanTerminalReset } from './terminal.js';
|
|
25
|
+
export { hasUnsafeWording, registerLimitMessages, UnsafeWordingError, } from './wording.js';
|
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { createHash } from 'node:crypto';
|
|
2
|
+
/** One deterministic pad for the whole hold, not one pad per blocker. */
|
|
3
|
+
export function holdDelayMs(sessionId, delayMs) {
|
|
4
|
+
const seconds = createHash('sha256')
|
|
5
|
+
.update(sessionId)
|
|
6
|
+
.digest()
|
|
7
|
+
.readUInt32BE(0);
|
|
8
|
+
return 1000 * (Math.max(1, Math.ceil(delayMs / 1000)) + (seconds % 21));
|
|
9
|
+
}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import { hasUnsafeWording } from './wording.js';
|
|
2
|
+
const emailPattern = /[^\s@]+@[^\s@]+\.[^\s@]+/;
|
|
3
|
+
export function containsEmail(text) {
|
|
4
|
+
return emailPattern.test(text);
|
|
5
|
+
}
|
|
6
|
+
/** Re-login guidance may use user labels, but must not expose emails or cause replay. */
|
|
7
|
+
export function sanitizeRefusalLabel(label) {
|
|
8
|
+
return containsEmail(label) || hasUnsafeWording(label)
|
|
9
|
+
? 'this account'
|
|
10
|
+
: label;
|
|
11
|
+
}
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import type { Scope } from './scope.js';
|
|
2
|
+
import type { AccountKey, LimitKind, LimitSignal } from './signal.js';
|
|
3
|
+
export type MergeLaw = 'latest-evidence' | 'max-until' | 'overwrite';
|
|
4
|
+
export interface LimitMark {
|
|
5
|
+
readonly scope: Scope;
|
|
6
|
+
readonly until: number;
|
|
7
|
+
readonly mergeLaw: MergeLaw;
|
|
8
|
+
}
|
|
9
|
+
export interface FailureLadderAxes {
|
|
10
|
+
readonly kind: 'failure-ladder';
|
|
11
|
+
readonly mergeLaw: MergeLaw;
|
|
12
|
+
readonly hintFloorMs: number;
|
|
13
|
+
readonly quotaSteps: readonly number[];
|
|
14
|
+
readonly byKind: Readonly<Partial<Record<LimitKind, number>>>;
|
|
15
|
+
readonly byReason: Readonly<Record<string, number>>;
|
|
16
|
+
readonly capacity: {
|
|
17
|
+
readonly baseMs: number;
|
|
18
|
+
/** Maximum displacement on either side of baseMs. */
|
|
19
|
+
readonly spreadMs: number;
|
|
20
|
+
};
|
|
21
|
+
readonly defaultMs: number;
|
|
22
|
+
}
|
|
23
|
+
export declare const ANTIGRAVITY_FAILURE_LADDER: FailureLadderAxes;
|
|
24
|
+
export type MarkerAxes = {
|
|
25
|
+
readonly kind: 'off';
|
|
26
|
+
} | {
|
|
27
|
+
readonly kind: 'hint';
|
|
28
|
+
readonly mergeLaw: MergeLaw;
|
|
29
|
+
readonly defaultMs: number;
|
|
30
|
+
readonly minimumMs: number;
|
|
31
|
+
readonly zero: 'accept' | 'skip';
|
|
32
|
+
/** Core absolute dates and host event-relative hints use different samples. */
|
|
33
|
+
readonly hintClock: 'signal' | 'marker';
|
|
34
|
+
} | {
|
|
35
|
+
readonly kind: 'reset';
|
|
36
|
+
readonly mergeLaw: MergeLaw;
|
|
37
|
+
readonly defaultMs: number;
|
|
38
|
+
} | FailureLadderAxes;
|
|
39
|
+
export interface FailureStreak {
|
|
40
|
+
readonly count: number;
|
|
41
|
+
readonly lastFailureAt: number;
|
|
42
|
+
}
|
|
43
|
+
/** Owned by the process, not a persisted registry snapshot. */
|
|
44
|
+
export type FailureHistory = ReadonlyMap<string, FailureStreak>;
|
|
45
|
+
export type FailureEvent = {
|
|
46
|
+
readonly type: 'failure';
|
|
47
|
+
readonly account: AccountKey;
|
|
48
|
+
readonly at: number;
|
|
49
|
+
} | {
|
|
50
|
+
readonly type: 'success';
|
|
51
|
+
readonly account: AccountKey;
|
|
52
|
+
};
|
|
53
|
+
/** Feed committed marker events, not repeated reducer evaluations, into history. */
|
|
54
|
+
export declare function reduceFailureHistory(history: FailureHistory, event: FailureEvent, ttlMs?: number): FailureHistory;
|
|
55
|
+
export interface MarkerHistory {
|
|
56
|
+
readonly now: number;
|
|
57
|
+
/** Includes the current failure event; success removes only that account's streak. */
|
|
58
|
+
readonly failures?: FailureHistory;
|
|
59
|
+
/** Uniform sample in [0, 1] for the capacity fallback duration; omitted means midpoint. */
|
|
60
|
+
readonly random?: number;
|
|
61
|
+
}
|
|
62
|
+
/** No clocks, random draws, state updates or I/O occur while producing a mark. */
|
|
63
|
+
export declare function markFromSignal(signal: LimitSignal | undefined, axes: MarkerAxes, history: MarkerHistory): LimitMark | undefined;
|
|
64
|
+
export declare function markIsActive(mark: LimitMark, now: number): boolean;
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
export const ANTIGRAVITY_FAILURE_LADDER = Object.freeze({
|
|
2
|
+
kind: 'failure-ladder',
|
|
3
|
+
mergeLaw: 'max-until',
|
|
4
|
+
hintFloorMs: 2000,
|
|
5
|
+
quotaSteps: Object.freeze([60000, 300000, 1800000, 7200000]),
|
|
6
|
+
byKind: Object.freeze({ 'rate-limit': 30000 }),
|
|
7
|
+
byReason: Object.freeze({ 'server-error': 20000, unknown: 60000 }),
|
|
8
|
+
capacity: Object.freeze({ baseMs: 45000, spreadMs: 15000 }),
|
|
9
|
+
defaultMs: 60000,
|
|
10
|
+
});
|
|
11
|
+
function accountKey(account) {
|
|
12
|
+
return JSON.stringify([
|
|
13
|
+
account.namespace,
|
|
14
|
+
account.accountId,
|
|
15
|
+
account.incarnation,
|
|
16
|
+
]);
|
|
17
|
+
}
|
|
18
|
+
/** Feed committed marker events, not repeated reducer evaluations, into history. */
|
|
19
|
+
export function reduceFailureHistory(history, event, ttlMs = 3600000) {
|
|
20
|
+
const next = new Map(history);
|
|
21
|
+
const key = accountKey(event.account);
|
|
22
|
+
if (event.type === 'success') {
|
|
23
|
+
next.delete(key);
|
|
24
|
+
}
|
|
25
|
+
else {
|
|
26
|
+
const previous = history.get(key);
|
|
27
|
+
const count = !previous || event.at - previous.lastFailureAt > ttlMs
|
|
28
|
+
? 1
|
|
29
|
+
: previous.count + 1;
|
|
30
|
+
next.set(key, { count, lastFailureAt: event.at });
|
|
31
|
+
}
|
|
32
|
+
return next;
|
|
33
|
+
}
|
|
34
|
+
function ladderMs(signal, axes, history) {
|
|
35
|
+
const hint = signal.retryAfterMs;
|
|
36
|
+
if (hint !== undefined && Number.isFinite(hint) && hint > 0) {
|
|
37
|
+
return Math.max(axes.hintFloorMs, hint);
|
|
38
|
+
}
|
|
39
|
+
const reasonDuration = Object.hasOwn(axes.byReason, signal.reason)
|
|
40
|
+
? axes.byReason[signal.reason]
|
|
41
|
+
: undefined;
|
|
42
|
+
if (reasonDuration !== undefined)
|
|
43
|
+
return reasonDuration;
|
|
44
|
+
if (signal.kind === 'quota-exhausted') {
|
|
45
|
+
const count = history.failures?.get(accountKey(signal.account))?.count ?? 1;
|
|
46
|
+
const index = Math.min(axes.quotaSteps.length - 1, Math.max(0, count - 1));
|
|
47
|
+
const step = axes.quotaSteps[index];
|
|
48
|
+
if (step !== undefined)
|
|
49
|
+
return step;
|
|
50
|
+
}
|
|
51
|
+
const duration = axes.byKind[signal.kind];
|
|
52
|
+
if (duration !== undefined)
|
|
53
|
+
return duration;
|
|
54
|
+
if (signal.kind === 'capacity') {
|
|
55
|
+
return (axes.capacity.baseMs +
|
|
56
|
+
(2 * (history.random ?? 0.5) - 1) * axes.capacity.spreadMs);
|
|
57
|
+
}
|
|
58
|
+
return axes.defaultMs;
|
|
59
|
+
}
|
|
60
|
+
/** No clocks, random draws, state updates or I/O occur while producing a mark. */
|
|
61
|
+
export function markFromSignal(signal, axes, history) {
|
|
62
|
+
if (!signal || axes.kind === 'off')
|
|
63
|
+
return undefined;
|
|
64
|
+
let until;
|
|
65
|
+
switch (axes.kind) {
|
|
66
|
+
case 'failure-ladder':
|
|
67
|
+
until = history.now + ladderMs(signal, axes, history);
|
|
68
|
+
break;
|
|
69
|
+
case 'hint': {
|
|
70
|
+
const hint = signal.retryAfterMs;
|
|
71
|
+
const usable = hint !== undefined &&
|
|
72
|
+
Number.isFinite(hint) &&
|
|
73
|
+
(hint > 0 || (hint === 0 && axes.zero === 'accept'));
|
|
74
|
+
until = usable
|
|
75
|
+
? (axes.hintClock === 'signal' ? signal.observedAt : history.now) +
|
|
76
|
+
Math.max(axes.minimumMs, hint)
|
|
77
|
+
: history.now + axes.defaultMs;
|
|
78
|
+
break;
|
|
79
|
+
}
|
|
80
|
+
case 'reset': {
|
|
81
|
+
const resets = signal.windows
|
|
82
|
+
.map((window) => window.resetAt)
|
|
83
|
+
.filter((reset) => reset !== undefined &&
|
|
84
|
+
Number.isFinite(reset) &&
|
|
85
|
+
reset > history.now);
|
|
86
|
+
until = resets.length ? Math.max(...resets) : history.now + axes.defaultMs;
|
|
87
|
+
break;
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
return Number.isFinite(until)
|
|
91
|
+
? { scope: signal.scope, until, mergeLaw: axes.mergeLaw }
|
|
92
|
+
: undefined;
|
|
93
|
+
}
|
|
94
|
+
export function markIsActive(mark, now) {
|
|
95
|
+
return now < mark.until;
|
|
96
|
+
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { MergeLaw } from './marker.js';
|
|
2
|
+
export interface TimedMarkEntry {
|
|
3
|
+
readonly until: number;
|
|
4
|
+
readonly evidenceAt: number;
|
|
5
|
+
readonly baseRevision: number;
|
|
6
|
+
readonly committedRevision: number;
|
|
7
|
+
}
|
|
8
|
+
/** Apply supersession before expiry, so a short or zero overwrite removes a long mark. */
|
|
9
|
+
export declare function mergeTimedMarkEntries(law: MergeLaw, entries: readonly TimedMarkEntry[], now: number, clearRevision?: number): readonly TimedMarkEntry[];
|
|
10
|
+
export interface AccessOrder {
|
|
11
|
+
readonly eligibilityStateUpdatedAt: number;
|
|
12
|
+
readonly committedRevision: number;
|
|
13
|
+
}
|
|
14
|
+
export declare function mergeAccessState<T extends AccessOrder>(a: T, b: T): T;
|