@cortexkit/common-auth 0.33.0 → 0.35.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- 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 +69 -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 +146 -0
- package/dist/limits/decide.js +425 -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 +59 -0
- package/dist/limits/families.js +149 -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 +45 -0
- package/dist/limits/index.js +26 -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 +69 -0
- package/dist/limits/marker.js +107 -0
- package/dist/limits/merge-laws.d.ts +15 -0
- package/dist/limits/merge-laws.js +31 -0
- package/dist/limits/namespace.d.ts +92 -0
- package/dist/limits/namespace.js +191 -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 +240 -0
- package/dist/limits/registry.d.ts +61 -0
- package/dist/limits/registry.js +478 -0
- package/dist/limits/request-history.d.ts +79 -0
- package/dist/limits/request-history.js +120 -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/unconfirmed-retain-counter.d.ts +13 -0
- package/dist/limits/unconfirmed-retain-counter.js +41 -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,59 @@
|
|
|
1
|
+
import { type LimitMessages } from './wording.js';
|
|
2
|
+
export type OpenCode1Family = 'openai-429' | 'claude-429' | 'json-412' | 'claustrum-429' | 'claustrum-402' | 'claude-econnreset';
|
|
3
|
+
export type RefusalFamily = OpenCode1Family | 'pi-final';
|
|
4
|
+
export type HostRetry = 'leave' | 'veto';
|
|
5
|
+
export interface RefusalInput {
|
|
6
|
+
readonly family: RefusalFamily;
|
|
7
|
+
/** Local responses formatted for OpenCode 2 must not be replayed by the host. */
|
|
8
|
+
readonly host?: 'opencode1' | 'opencode2' | 'pi';
|
|
9
|
+
readonly messageKey: string;
|
|
10
|
+
readonly messages?: LimitMessages;
|
|
11
|
+
readonly parameters?: {
|
|
12
|
+
readonly labels?: readonly string[];
|
|
13
|
+
};
|
|
14
|
+
/**
|
|
15
|
+
* Set only for re-login guidance, where the user needs to know which account to sign in again.
|
|
16
|
+
* Ordinary refusals omit labels, even when the caller supplies them.
|
|
17
|
+
*/
|
|
18
|
+
readonly labelPolicy?: 'relogin';
|
|
19
|
+
readonly now: number;
|
|
20
|
+
/** A retained reset, already filtered for freshness by the decision layer. */
|
|
21
|
+
readonly resetAt?: number;
|
|
22
|
+
readonly retryAfterMs?: number;
|
|
23
|
+
/** Time already spent presenting a notice, not an instruction to sleep. */
|
|
24
|
+
readonly noticeDelayMs?: number;
|
|
25
|
+
/** Additional provider headers are preserved by the JSON 412 family only. */
|
|
26
|
+
readonly extraHeaders?: ConstructorParameters<typeof Headers>[0];
|
|
27
|
+
}
|
|
28
|
+
interface RefusalAttributes {
|
|
29
|
+
readonly family: RefusalFamily;
|
|
30
|
+
readonly disposition: 'refuse';
|
|
31
|
+
readonly retryable: boolean;
|
|
32
|
+
readonly hostRetry: HostRetry;
|
|
33
|
+
}
|
|
34
|
+
export interface HttpRefusal extends RefusalAttributes {
|
|
35
|
+
readonly kind: 'http';
|
|
36
|
+
readonly status: 402 | 412 | 429;
|
|
37
|
+
readonly headers: Headers;
|
|
38
|
+
readonly body: string;
|
|
39
|
+
}
|
|
40
|
+
export interface TextRefusal extends RefusalAttributes {
|
|
41
|
+
readonly kind: 'text';
|
|
42
|
+
readonly body: string;
|
|
43
|
+
}
|
|
44
|
+
export declare class ClaudeIncompleteError extends Error {
|
|
45
|
+
readonly code = "ECONNRESET";
|
|
46
|
+
readonly syscall = "sticky-routing";
|
|
47
|
+
readonly isRetryable = true;
|
|
48
|
+
constructor(message: string);
|
|
49
|
+
}
|
|
50
|
+
export interface ThrownRefusal extends RefusalAttributes {
|
|
51
|
+
readonly kind: 'throw';
|
|
52
|
+
readonly error: ClaudeIncompleteError;
|
|
53
|
+
}
|
|
54
|
+
export type BuiltRefusal = HttpRefusal | TextRefusal | ThrownRefusal;
|
|
55
|
+
/** Compute metadata at delivery time, after time spent showing a notice. */
|
|
56
|
+
export declare function retryAfterSeconds(retryAfterMs: number | undefined, noticeDelayMs?: number): number | undefined;
|
|
57
|
+
/** Pure wire construction: the caller sends the response, emits text, or throws the error. */
|
|
58
|
+
export declare function buildRefusal(input: RefusalInput): BuiltRefusal;
|
|
59
|
+
export {};
|
|
@@ -0,0 +1,149 @@
|
|
|
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
|
+
case 'claustrum-402':
|
|
101
|
+
return JSON.stringify({ error: 'claustrum-auth: insufficient balance' });
|
|
102
|
+
default:
|
|
103
|
+
return message;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
/** Pure wire construction: the caller sends the response, emits text, or throws the error. */
|
|
107
|
+
export function buildRefusal(input) {
|
|
108
|
+
const nonRetryable = input.family === 'json-412' || input.family === 'pi-final';
|
|
109
|
+
const attributes = {
|
|
110
|
+
family: input.family,
|
|
111
|
+
disposition: 'refuse',
|
|
112
|
+
retryable: !nonRetryable,
|
|
113
|
+
hostRetry: nonRetryable || input.host === 'opencode2' ? 'veto' : 'leave',
|
|
114
|
+
};
|
|
115
|
+
let body = bodyFor(input.family, textFor(input, nonRetryable));
|
|
116
|
+
if (nonRetryable && (hasUnsafeWording(body) || containsEmail(body))) {
|
|
117
|
+
// Rebuild from retained facts, never from plugin text or fact-supplied labels.
|
|
118
|
+
const now = input.now + elapsedNotice(input.noticeDelayMs ?? 0);
|
|
119
|
+
body = bodyFor(input.family, fallbackText(input, now, true));
|
|
120
|
+
}
|
|
121
|
+
if (input.family === 'claude-econnreset') {
|
|
122
|
+
return {
|
|
123
|
+
...attributes,
|
|
124
|
+
kind: 'throw',
|
|
125
|
+
error: new ClaudeIncompleteError(body),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
if (input.family === 'pi-final')
|
|
129
|
+
return { ...attributes, kind: 'text', body };
|
|
130
|
+
const headers = new Headers(input.family === 'json-412' ? input.extraHeaders : undefined);
|
|
131
|
+
headers.set('content-type', 'application/json');
|
|
132
|
+
// Only the library's post-notice estimate may control this header, including
|
|
133
|
+
// when a provider supplied an old Retry-After among the extra headers.
|
|
134
|
+
headers.delete('retry-after');
|
|
135
|
+
const retry = retryAfterSeconds(input.retryAfterMs, input.noticeDelayMs);
|
|
136
|
+
if (retry !== undefined)
|
|
137
|
+
headers.set('retry-after', String(retry));
|
|
138
|
+
return {
|
|
139
|
+
...attributes,
|
|
140
|
+
kind: 'http',
|
|
141
|
+
status: input.family === 'json-412'
|
|
142
|
+
? 412
|
|
143
|
+
: input.family === 'claustrum-402'
|
|
144
|
+
? 402
|
|
145
|
+
: 429,
|
|
146
|
+
headers,
|
|
147
|
+
body,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
@@ -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,45 @@
|
|
|
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, LimitMarkCause, 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, SuccessfulProbeClear, } from './registry.js';
|
|
32
|
+
export { acquireLimitsRegistry, clearLimitsAfterProbe, 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 { UnconfirmedRetainCounter } from './unconfirmed-retain-counter.js';
|
|
44
|
+
export type { LimitMessageOptions, LimitMessages, MessageParameters, MessageTemplate, } from './wording.js';
|
|
45
|
+
export { hasUnsafeWording, registerLimitMessages, UnsafeWordingError, } from './wording.js';
|
|
@@ -0,0 +1,26 @@
|
|
|
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, clearLimitsAfterProbe, 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 { UnconfirmedRetainCounter } from './unconfirmed-retain-counter.js';
|
|
26
|
+
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,69 @@
|
|
|
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 type LimitMarkCause = 'rate-limit' | 'payment-balance';
|
|
5
|
+
export interface LimitMark {
|
|
6
|
+
readonly scope: Scope;
|
|
7
|
+
readonly until: number;
|
|
8
|
+
readonly mergeLaw: MergeLaw;
|
|
9
|
+
readonly cause?: LimitMarkCause;
|
|
10
|
+
}
|
|
11
|
+
export interface FailureLadderAxes {
|
|
12
|
+
readonly kind: 'failure-ladder';
|
|
13
|
+
readonly mergeLaw: MergeLaw;
|
|
14
|
+
readonly hintFloorMs: number;
|
|
15
|
+
readonly quotaSteps: readonly number[];
|
|
16
|
+
readonly byKind: Readonly<Partial<Record<LimitKind, number>>>;
|
|
17
|
+
readonly byReason: Readonly<Record<string, number>>;
|
|
18
|
+
readonly capacity: {
|
|
19
|
+
readonly baseMs: number;
|
|
20
|
+
/** Maximum displacement on either side of baseMs. */
|
|
21
|
+
readonly spreadMs: number;
|
|
22
|
+
};
|
|
23
|
+
readonly defaultMs: number;
|
|
24
|
+
}
|
|
25
|
+
export declare const ANTIGRAVITY_FAILURE_LADDER: FailureLadderAxes;
|
|
26
|
+
export type MarkerAxes = {
|
|
27
|
+
readonly kind: 'off';
|
|
28
|
+
} | {
|
|
29
|
+
readonly kind: 'hint';
|
|
30
|
+
readonly mergeLaw: MergeLaw;
|
|
31
|
+
readonly defaultMs: number;
|
|
32
|
+
readonly defaultMsByKind?: Readonly<Partial<Record<LimitSignal['kind'], number>>>;
|
|
33
|
+
readonly causes?: readonly LimitMarkCause[];
|
|
34
|
+
readonly ignoredKinds?: readonly LimitSignal['kind'][];
|
|
35
|
+
readonly minimumMs: number;
|
|
36
|
+
readonly zero: 'accept' | 'skip';
|
|
37
|
+
/** Core absolute dates and host event-relative hints use different samples. */
|
|
38
|
+
readonly hintClock: 'signal' | 'marker';
|
|
39
|
+
} | {
|
|
40
|
+
readonly kind: 'reset';
|
|
41
|
+
readonly mergeLaw: MergeLaw;
|
|
42
|
+
readonly defaultMs: number;
|
|
43
|
+
} | FailureLadderAxes;
|
|
44
|
+
export interface FailureStreak {
|
|
45
|
+
readonly count: number;
|
|
46
|
+
readonly lastFailureAt: number;
|
|
47
|
+
}
|
|
48
|
+
/** Owned by the process, not a persisted registry snapshot. */
|
|
49
|
+
export type FailureHistory = ReadonlyMap<string, FailureStreak>;
|
|
50
|
+
export type FailureEvent = {
|
|
51
|
+
readonly type: 'failure';
|
|
52
|
+
readonly account: AccountKey;
|
|
53
|
+
readonly at: number;
|
|
54
|
+
} | {
|
|
55
|
+
readonly type: 'success';
|
|
56
|
+
readonly account: AccountKey;
|
|
57
|
+
};
|
|
58
|
+
/** Feed committed marker events, not repeated reducer evaluations, into history. */
|
|
59
|
+
export declare function reduceFailureHistory(history: FailureHistory, event: FailureEvent, ttlMs?: number): FailureHistory;
|
|
60
|
+
export interface MarkerHistory {
|
|
61
|
+
readonly now: number;
|
|
62
|
+
/** Includes the current failure event; success removes only that account's streak. */
|
|
63
|
+
readonly failures?: FailureHistory;
|
|
64
|
+
/** Uniform sample in [0, 1] for the capacity fallback duration; omitted means midpoint. */
|
|
65
|
+
readonly random?: number;
|
|
66
|
+
}
|
|
67
|
+
/** No clocks, random draws, state updates or I/O occur while producing a mark. */
|
|
68
|
+
export declare function markFromSignal(signal: LimitSignal | undefined, axes: MarkerAxes, history: MarkerHistory): LimitMark | undefined;
|
|
69
|
+
export declare function markIsActive(mark: LimitMark, now: number): boolean;
|