@cortexkit/common-auth 0.32.1 → 0.34.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (111) hide show
  1. package/dist/claustrum/consumer.d.ts +12 -0
  2. package/dist/claustrum/consumer.js +36 -0
  3. package/dist/claustrum/custody.d.ts +16 -4
  4. package/dist/claustrum/custody.js +74 -9
  5. package/dist/claustrum/hub.d.ts +3 -2
  6. package/dist/claustrum/hub.js +8 -0
  7. package/dist/claustrum/index.d.ts +1 -0
  8. package/dist/claustrum/roster.d.ts +2 -0
  9. package/dist/claustrum/roster.js +2 -0
  10. package/dist/claustrum/usage.d.ts +41 -0
  11. package/dist/claustrum/usage.js +145 -0
  12. package/dist/commands/builtins.d.ts +5 -0
  13. package/dist/commands/builtins.js +38 -0
  14. package/dist/fs/private-files.d.ts +5 -0
  15. package/dist/fs/private-files.js +7 -0
  16. package/dist/fs/refresh-file-lock.js +144 -49
  17. package/dist/fs/with-lock.js +34 -10
  18. package/dist/limits/activity.d.ts +26 -0
  19. package/dist/limits/activity.js +52 -0
  20. package/dist/limits/axes.d.ts +63 -0
  21. package/dist/limits/axes.js +7 -0
  22. package/dist/limits/bridge.d.ts +4 -0
  23. package/dist/limits/bridge.js +10 -0
  24. package/dist/limits/decide.d.ts +141 -0
  25. package/dist/limits/decide.js +383 -0
  26. package/dist/limits/duration.d.ts +8 -0
  27. package/dist/limits/duration.js +20 -0
  28. package/dist/limits/envelope-loss.d.ts +29 -0
  29. package/dist/limits/envelope-loss.js +150 -0
  30. package/dist/limits/families.d.ts +57 -0
  31. package/dist/limits/families.js +143 -0
  32. package/dist/limits/header-classifier.d.ts +9 -0
  33. package/dist/limits/header-classifier.js +121 -0
  34. package/dist/limits/hold.d.ts +13 -0
  35. package/dist/limits/hold.js +25 -0
  36. package/dist/limits/identity.d.ts +14 -0
  37. package/dist/limits/identity.js +21 -0
  38. package/dist/limits/index.d.ts +44 -0
  39. package/dist/limits/index.js +25 -0
  40. package/dist/limits/jitter.d.ts +2 -0
  41. package/dist/limits/jitter.js +9 -0
  42. package/dist/limits/labels.d.ts +3 -0
  43. package/dist/limits/labels.js +11 -0
  44. package/dist/limits/marker.d.ts +64 -0
  45. package/dist/limits/marker.js +96 -0
  46. package/dist/limits/merge-laws.d.ts +14 -0
  47. package/dist/limits/merge-laws.js +31 -0
  48. package/dist/limits/namespace.d.ts +89 -0
  49. package/dist/limits/namespace.js +183 -0
  50. package/dist/limits/persistence.d.ts +33 -0
  51. package/dist/limits/persistence.js +9 -0
  52. package/dist/limits/pi-wait.d.ts +16 -0
  53. package/dist/limits/pi-wait.js +51 -0
  54. package/dist/limits/pool-adapter.d.ts +16 -0
  55. package/dist/limits/pool-adapter.js +162 -0
  56. package/dist/limits/presets.d.ts +11 -0
  57. package/dist/limits/presets.js +223 -0
  58. package/dist/limits/registry.d.ts +49 -0
  59. package/dist/limits/registry.js +471 -0
  60. package/dist/limits/request-history.d.ts +77 -0
  61. package/dist/limits/request-history.js +117 -0
  62. package/dist/limits/reset.d.ts +21 -0
  63. package/dist/limits/reset.js +44 -0
  64. package/dist/limits/routing-hold.d.ts +16 -0
  65. package/dist/limits/routing-hold.js +23 -0
  66. package/dist/limits/scope.d.ts +12 -0
  67. package/dist/limits/scope.js +10 -0
  68. package/dist/limits/signal.d.ts +41 -0
  69. package/dist/limits/signal.js +1 -0
  70. package/dist/limits/terminal.d.ts +52 -0
  71. package/dist/limits/terminal.js +133 -0
  72. package/dist/limits/vault-adapter.d.ts +16 -0
  73. package/dist/limits/vault-adapter.js +123 -0
  74. package/dist/limits/vault.d.ts +1 -0
  75. package/dist/limits/vault.js +1 -0
  76. package/dist/limits/wake.d.ts +21 -0
  77. package/dist/limits/wake.js +47 -0
  78. package/dist/limits/wording.d.ts +25 -0
  79. package/dist/limits/wording.js +114 -0
  80. package/dist/opencode2/index.d.ts +1 -1
  81. package/dist/opencode2/install.d.ts +2 -2
  82. package/dist/opencode2/install.js +161 -18
  83. package/dist/opencode2/types.d.ts +95 -9
  84. package/dist/quota/format.d.ts +9 -4
  85. package/dist/quota/format.js +45 -26
  86. package/dist/quota-sidebar/index.jsx +27 -19
  87. package/dist/routing/admission.d.ts +7 -2
  88. package/dist/routing/admission.js +17 -7
  89. package/dist/routing-accessor/handle.d.ts +1 -0
  90. package/dist/routing-accessor/handle.js +10 -0
  91. package/dist/routing-accessor/index.d.ts +18 -2
  92. package/dist/routing-accessor/index.js +21 -11
  93. package/dist/rpc/port-file.d.ts +12 -3
  94. package/dist/rpc/port-file.js +46 -4
  95. package/dist/store/attribution.js +3 -2
  96. package/dist/store/errors.d.ts +1 -1
  97. package/dist/store/hooks.d.ts +5 -1
  98. package/dist/store/hooks.js +20 -5
  99. package/dist/store/index.d.ts +1 -0
  100. package/dist/store/limits-namespace.d.ts +7 -0
  101. package/dist/store/limits-namespace.js +34 -0
  102. package/dist/store/pool.d.ts +10 -1
  103. package/dist/store/pool.js +2 -0
  104. package/dist/store/provider-state.js +5 -5
  105. package/dist/store/refresh.js +1 -1
  106. package/dist/store/schema.js +9 -4
  107. package/dist/store/settings.d.ts +2 -0
  108. package/dist/store/settings.js +11 -4
  109. package/package.json +10 -2
  110. package/src/quota/format.ts +56 -26
  111. package/src/quota-sidebar/index.tsx +56 -32
@@ -0,0 +1,150 @@
1
+ import { AsyncResource } from 'node:async_hooks';
2
+ import { randomUUID } from 'node:crypto';
3
+ import { isDeepStrictEqual } from 'node:util';
4
+ import { mergeAccessState } from './merge-laws.js';
5
+ import { createLimitsNamespace, pruneLimitsNamespace, timedMarkKeyId, } from './namespace.js';
6
+ const detached = new AsyncResource('common-auth-limits-recovery');
7
+ /** Readers never join the write lock; notify them after a detached repair lands. */
8
+ export class EnvelopeRepair {
9
+ logger;
10
+ running;
11
+ listeners = new Set();
12
+ constructor(logger) {
13
+ this.logger = logger;
14
+ }
15
+ subscribe = (listener) => {
16
+ this.listeners.add(listener);
17
+ return () => this.listeners.delete(listener);
18
+ };
19
+ schedule(commit) {
20
+ if (this.running)
21
+ return;
22
+ this.running = detached.runInAsyncScope(async () => {
23
+ // Defer invocation until the single-flight promise is installed, and keep
24
+ // the write outside any caller context that holds the store lock.
25
+ await Promise.resolve();
26
+ let succeeded = false;
27
+ try {
28
+ await commit();
29
+ succeeded = true;
30
+ }
31
+ catch (error) {
32
+ try {
33
+ this.logger?.warn('limits envelope recovery failed; agreement remains degraded', {
34
+ error: error instanceof Error ? error.message : String(error),
35
+ });
36
+ }
37
+ catch {
38
+ // A failed diagnostic must not turn detached bookkeeping into a rejection.
39
+ }
40
+ }
41
+ finally {
42
+ this.running = undefined;
43
+ if (succeeded) {
44
+ for (const listener of this.listeners) {
45
+ try {
46
+ listener();
47
+ }
48
+ catch {
49
+ // Observers cannot change the result of a durable repair.
50
+ }
51
+ }
52
+ }
53
+ }
54
+ });
55
+ }
56
+ }
57
+ /** Retain only durable observations; a new, empty namespace is not lost state. */
58
+ export class EnvelopeHistory {
59
+ seen;
60
+ missingGeneration;
61
+ incorporated;
62
+ remember(snapshot, previous) {
63
+ if (this.seen && this.seen.revision > snapshot.revision)
64
+ return;
65
+ this.seen = structuredClone(snapshot);
66
+ this.missingGeneration = undefined;
67
+ if (previous)
68
+ this.incorporated = structuredClone(previous);
69
+ }
70
+ retained(previous) {
71
+ // A notification reload still carries the pre-repair registry snapshot.
72
+ // Do not mistake that already-merged generation for another loss.
73
+ const retainedPrevious = isDeepStrictEqual(previous, this.incorporated)
74
+ ? undefined
75
+ : previous;
76
+ return [this.seen, retainedPrevious].filter((snapshot) => snapshot !== undefined &&
77
+ (snapshot === this.seen || snapshot.revision > 0));
78
+ }
79
+ lost(present, previous) {
80
+ return this.retained(previous).some((seen) => !present ||
81
+ seen.generation !== present.generation ||
82
+ present.revision < seen.revision ||
83
+ seen.tombstones.some((clear) => clear.revision > present.lowWatermark &&
84
+ !present.tombstones.some((current) => timedMarkKeyId(current.key) === timedMarkKeyId(clear.key) &&
85
+ current.revision >= clear.revision)));
86
+ }
87
+ /** Preview a restrictive merge, or apply it against the envelope under the write lock. */
88
+ recover(present, previous, namespace, now) {
89
+ if (!present)
90
+ this.missingGeneration ??= randomUUID();
91
+ const current = present ??
92
+ createLimitsNamespace(namespace, this.missingGeneration ?? randomUUID());
93
+ const sources = [...this.retained(previous), current];
94
+ const marks = new Map();
95
+ const tombstones = new Map();
96
+ const operations = new Map();
97
+ const access = new Map();
98
+ let highest = 0;
99
+ for (const source of sources) {
100
+ highest = Math.max(highest, source.revision, source.lowWatermark);
101
+ for (const mark of source.marks) {
102
+ const id = timedMarkKeyId(mark.key);
103
+ const old = marks.get(id);
104
+ if (old && old.mergeLaw !== mark.mergeLaw)
105
+ throw new Error('limits-recovery-merge-law-conflict');
106
+ marks.set(id, {
107
+ ...mark,
108
+ entries: [...(old?.entries ?? []), ...mark.entries],
109
+ });
110
+ for (const entry of mark.entries)
111
+ highest = Math.max(highest, entry.baseRevision, entry.committedRevision);
112
+ }
113
+ for (const clear of source.tombstones) {
114
+ const id = timedMarkKeyId(clear.key);
115
+ const old = tombstones.get(id);
116
+ if (!old || old.revision < clear.revision)
117
+ tombstones.set(id, clear);
118
+ highest = Math.max(highest, clear.revision);
119
+ }
120
+ for (const op of source.operationIds) {
121
+ const id = JSON.stringify([op.producerId, op.operationId]);
122
+ const old = operations.get(id);
123
+ if (!old || old.revision < op.revision)
124
+ operations.set(id, op);
125
+ highest = Math.max(highest, op.revision);
126
+ }
127
+ for (const state of source.access) {
128
+ const { namespace, accountId, incarnation } = state.account;
129
+ const id = JSON.stringify([namespace, accountId, incarnation]);
130
+ const old = access.get(id);
131
+ access.set(id, old ? mergeAccessState(old, state) : state);
132
+ highest = Math.max(highest, state.committedRevision);
133
+ }
134
+ }
135
+ const revision = highest + 1;
136
+ if (!Number.isSafeInteger(revision))
137
+ throw new Error('limits-revision-exhausted');
138
+ // The barrier rejects observations predating even a clear this process never
139
+ // saw. Retain entry base revisions so a later restored clear can remove them.
140
+ return pruneLimitsNamespace({
141
+ ...current,
142
+ revision,
143
+ lowWatermark: revision,
144
+ marks: [...marks.values()],
145
+ tombstones: [...tombstones.values()],
146
+ operationIds: [...operations.values()],
147
+ access: [...access.values()],
148
+ }, now);
149
+ }
150
+ }
@@ -0,0 +1,57 @@
1
+ import { type LimitMessages } from './wording.js';
2
+ export type OpenCode1Family = 'openai-429' | 'claude-429' | 'json-412' | 'claustrum-429' | 'claude-econnreset';
3
+ export type RefusalFamily = OpenCode1Family | 'pi-final';
4
+ export type HostRetry = 'leave' | 'veto';
5
+ export interface RefusalInput {
6
+ readonly family: RefusalFamily;
7
+ readonly messageKey: string;
8
+ readonly messages?: LimitMessages;
9
+ readonly parameters?: {
10
+ readonly labels?: readonly string[];
11
+ };
12
+ /**
13
+ * Set only for re-login guidance, where the user needs to know which account to sign in again.
14
+ * Ordinary refusals omit labels, even when the caller supplies them.
15
+ */
16
+ readonly labelPolicy?: 'relogin';
17
+ readonly now: number;
18
+ /** A retained reset, already filtered for freshness by the decision layer. */
19
+ readonly resetAt?: number;
20
+ readonly retryAfterMs?: number;
21
+ /** Time already spent presenting a notice, not an instruction to sleep. */
22
+ readonly noticeDelayMs?: number;
23
+ /** Additional provider headers are preserved by the JSON 412 family only. */
24
+ readonly extraHeaders?: ConstructorParameters<typeof Headers>[0];
25
+ }
26
+ interface RefusalAttributes {
27
+ readonly family: RefusalFamily;
28
+ readonly disposition: 'refuse';
29
+ readonly retryable: boolean;
30
+ readonly hostRetry: HostRetry;
31
+ }
32
+ export interface HttpRefusal extends RefusalAttributes {
33
+ readonly kind: 'http';
34
+ readonly status: 412 | 429;
35
+ readonly headers: Headers;
36
+ readonly body: string;
37
+ }
38
+ export interface TextRefusal extends RefusalAttributes {
39
+ readonly kind: 'text';
40
+ readonly body: string;
41
+ }
42
+ export declare class ClaudeIncompleteError extends Error {
43
+ readonly code = "ECONNRESET";
44
+ readonly syscall = "sticky-routing";
45
+ readonly isRetryable = true;
46
+ constructor(message: string);
47
+ }
48
+ export interface ThrownRefusal extends RefusalAttributes {
49
+ readonly kind: 'throw';
50
+ readonly error: ClaudeIncompleteError;
51
+ }
52
+ export type BuiltRefusal = HttpRefusal | TextRefusal | ThrownRefusal;
53
+ /** Compute metadata at delivery time, after time spent showing a notice. */
54
+ export declare function retryAfterSeconds(retryAfterMs: number | undefined, noticeDelayMs?: number): number | undefined;
55
+ /** Pure wire construction: the caller sends the response, emits text, or throws the error. */
56
+ export declare function buildRefusal(input: RefusalInput): BuiltRefusal;
57
+ export {};
@@ -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,2 @@
1
+ /** One deterministic pad for the whole hold, not one pad per blocker. */
2
+ export declare function holdDelayMs(sessionId: string, delayMs: number): number;
@@ -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,3 @@
1
+ export declare function containsEmail(text: string): boolean;
2
+ /** Re-login guidance may use user labels, but must not expose emails or cause replay. */
3
+ export declare function sanitizeRefusalLabel(label: string): string;
@@ -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
+ }