@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,44 @@
1
+ /** First usable source wins; a default is just another explicitly ordered source. */
2
+ export function resolveReset(sources, now) {
3
+ for (const candidate of sources) {
4
+ const { value } = candidate;
5
+ if (value === undefined ||
6
+ !Number.isFinite(value) ||
7
+ value < 0 ||
8
+ (value === 0 && candidate.zero === 'skip')) {
9
+ continue;
10
+ }
11
+ const resetAt = candidate.unit === 'delay-ms' ? now + value : value;
12
+ if (Number.isFinite(resetAt))
13
+ return { resetAt, source: candidate.source };
14
+ }
15
+ return undefined;
16
+ }
17
+ /** Only a window listed in lendable may supply its own cached reset. */
18
+ export function resolveNamedWindowReset(input) {
19
+ const future = (value) => value !== undefined && Number.isFinite(value) && value > input.now
20
+ ? value
21
+ : undefined;
22
+ return resolveReset([
23
+ {
24
+ source: 'explicit',
25
+ value: future(input.explicitResetAt),
26
+ unit: 'epoch-ms',
27
+ zero: 'skip',
28
+ },
29
+ {
30
+ source: 'cached',
31
+ value: input.lendable.includes(input.window)
32
+ ? future(input.cached[input.window])
33
+ : undefined,
34
+ unit: 'epoch-ms',
35
+ zero: 'skip',
36
+ },
37
+ {
38
+ source: 'default',
39
+ value: input.defaultMs,
40
+ unit: 'delay-ms',
41
+ zero: 'accept',
42
+ },
43
+ ], input.now);
44
+ }
@@ -0,0 +1,16 @@
1
+ import type { SessionActivity } from './activity.js';
2
+ import type { AccountKey } from './signal.js';
3
+ /**
4
+ * Cap routing advice by the current account's accepted prompt-cache activity.
5
+ * Pass the authoritative account key so a replacement cannot reuse an old cache.
6
+ * Without a usable routing handle, leave the optional advice cap unset.
7
+ */
8
+ export declare function holdWaitMaxS(input: {
9
+ readonly sessionId: string;
10
+ /** Snapshot from the activity store's get(sessionId). */
11
+ readonly activity?: SessionActivity;
12
+ readonly accountKey: AccountKey;
13
+ /** Pass routing.maxSameAccountWait without coercing persisted values. */
14
+ readonly maxSameAccountWait?: unknown;
15
+ readonly now: number;
16
+ }): number | undefined;
@@ -0,0 +1,23 @@
1
+ import { routingHandle } from '../routing-accessor/handle.js';
2
+ import { sameAccountHoldFacts } from './hold.js';
3
+ /**
4
+ * Cap routing advice by the current account's accepted prompt-cache activity.
5
+ * Pass the authoritative account key so a replacement cannot reuse an old cache.
6
+ * Without a usable routing handle, leave the optional advice cap unset.
7
+ */
8
+ export function holdWaitMaxS(input) {
9
+ try {
10
+ const handle = routingHandle(input.sessionId);
11
+ if (!handle || typeof handle.accountFor !== 'function')
12
+ return undefined;
13
+ }
14
+ catch {
15
+ // An optional bridge failure must not break authentication.
16
+ return undefined;
17
+ }
18
+ const hold = sameAccountHoldFacts(input);
19
+ if (!hold || !Number.isFinite(input.now))
20
+ return 0;
21
+ return Math.floor(Math.max(0, Math.min(hold.maxWaitMs, hold.cacheExpiresAt - input.now)) /
22
+ 1000);
23
+ }
@@ -0,0 +1,12 @@
1
+ /** Applicability is a plugin fact, never a substring match on a model id. */
2
+ export type Scope = {
3
+ readonly kind: 'pool';
4
+ } | {
5
+ readonly kind: 'family';
6
+ readonly family: string;
7
+ } | {
8
+ readonly kind: 'model';
9
+ readonly model: string;
10
+ };
11
+ export type FamilyOf = (model: string) => string | undefined;
12
+ export declare function scopeCovers(scope: Scope, model: string, familyOf: FamilyOf): boolean;
@@ -0,0 +1,10 @@
1
+ export function scopeCovers(scope, model, familyOf) {
2
+ switch (scope.kind) {
3
+ case 'pool':
4
+ return true;
5
+ case 'family':
6
+ return familyOf(model) === scope.family;
7
+ case 'model':
8
+ return scope.model === model;
9
+ }
10
+ }
@@ -0,0 +1,41 @@
1
+ import type { Scope } from './scope.js';
2
+ /** Refreshing credentials preserves this key; replacing an identity does not. */
3
+ export interface AccountKey {
4
+ readonly namespace: string;
5
+ readonly accountId: string;
6
+ readonly incarnation: string;
7
+ }
8
+ export type LimitKind = 'quota-exhausted' | 'rate-limit' | 'capacity' | 'payment-balance' | 'payment-cap' | 'auth' | 'account-access' | 'model-unavailable';
9
+ export interface LimitWindow {
10
+ readonly window: string;
11
+ readonly confirmed: boolean;
12
+ readonly confirmedByReading: boolean;
13
+ readonly resetAt?: number;
14
+ readonly resetSource?: string;
15
+ readonly observedAt: number;
16
+ readonly provenance: string;
17
+ }
18
+ /** A retry hint does not by itself confirm any exhausted window. */
19
+ export interface LimitSignal {
20
+ readonly account: AccountKey;
21
+ readonly kind: LimitKind;
22
+ readonly reason: string;
23
+ readonly status?: number;
24
+ readonly scope: Scope;
25
+ readonly windows: readonly LimitWindow[];
26
+ readonly observedAt: number;
27
+ readonly retryAfterMs?: number;
28
+ readonly retryAfterSource?: string;
29
+ }
30
+ export interface ClassifierInput {
31
+ readonly account: AccountKey;
32
+ readonly status: number;
33
+ readonly headers: Headers;
34
+ readonly body?: unknown;
35
+ readonly firstEvent?: unknown;
36
+ readonly effectiveModel: string;
37
+ readonly readings: readonly LimitWindow[];
38
+ readonly now: number;
39
+ }
40
+ /** Returning nothing must not manufacture an exhaustion mark. */
41
+ export type LimitClassifier = (input: ClassifierInput) => LimitSignal | undefined;
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,52 @@
1
+ import type { SessionActivity } from './activity.js';
2
+ import type { LimitAxes } from './axes.js';
3
+ import type { LimitDecision, PolicyFacts, TerminalFacts, WaitCheckpoint } from './decide.js';
4
+ import type { RequestHistory } from './request-history.js';
5
+ import type { FamilyOf, Scope } from './scope.js';
6
+ import type { AccountKey } from './signal.js';
7
+ export interface TerminalWindow {
8
+ readonly window: string;
9
+ readonly scope: Scope;
10
+ /** The caller evaluates quota thresholds, not just provider exhaustion. */
11
+ readonly blockedBy?: 'exhausted' | 'floor' | 'killswitch-floor';
12
+ readonly reset?: {
13
+ readonly at: number;
14
+ /** Provenance of this reset field, never the enclosing row's update time. */
15
+ readonly observedAt?: number;
16
+ readonly checkedAt?: number;
17
+ };
18
+ }
19
+ export interface TerminalCandidate {
20
+ readonly account: AccountKey;
21
+ readonly readingAccount: AccountKey;
22
+ readonly identity?: string;
23
+ readonly readingIdentity?: string;
24
+ readonly windows: readonly TerminalWindow[];
25
+ }
26
+ export interface TerminalScanFacts {
27
+ /** Candidate keys come from the caller's scoped/general terminal scan. */
28
+ readonly candidates: readonly TerminalCandidate[];
29
+ readonly effectiveModel: string;
30
+ readonly familyOf: FamilyOf;
31
+ readonly maxAgeMs: number;
32
+ readonly maxSameAccountWait?: unknown;
33
+ readonly activity?: SessionActivity;
34
+ /** Current session account, used to reject another account's cache record. */
35
+ readonly accountKey?: AccountKey;
36
+ }
37
+ export interface TerminalReset {
38
+ readonly account: AccountKey;
39
+ readonly resetAt: number;
40
+ readonly checkpoint: WaitCheckpoint;
41
+ }
42
+ /**
43
+ * Take each account's latest blocking reset, then the earliest across accounts.
44
+ * A missing identity is compatible, but readings from before re-login are not.
45
+ */
46
+ export declare function scanTerminalReset(input: TerminalScanFacts, now: number): TerminalReset | undefined;
47
+ export declare function terminalWaitDisabled(metadata: TerminalFacts, axes: LimitAxes): boolean;
48
+ /**
49
+ * When no account is ready, cap the wait by the setting rather than cache expiry.
50
+ * Unlike a same-account hold, this wait may proceed without a cache activity record.
51
+ */
52
+ export declare function terminalRefusalDecision(facts: PolicyFacts, axes: LimitAxes, history: RequestHistory, metadata: TerminalFacts): LimitDecision | undefined;
@@ -0,0 +1,133 @@
1
+ import { effectiveCacheTtlMs } from './activity.js';
2
+ import { MAX_SAME_ACCOUNT_HOLD_MS, readMaxSameAccountWait } from './hold.js';
3
+ import { sameAccount } from './request-history.js';
4
+ import { scopeCovers } from './scope.js';
5
+ /**
6
+ * Take each account's latest blocking reset, then the earliest across accounts.
7
+ * A missing identity is compatible, but readings from before re-login are not.
8
+ */
9
+ export function scanTerminalReset(input, now) {
10
+ if (!Number.isFinite(input.maxAgeMs) || input.maxAgeMs < 0)
11
+ return undefined;
12
+ let best;
13
+ for (const candidate of input.candidates) {
14
+ if (!sameAccount(candidate.account, candidate.readingAccount) ||
15
+ (candidate.identity !== undefined &&
16
+ candidate.readingIdentity !== undefined &&
17
+ candidate.identity !== candidate.readingIdentity))
18
+ continue;
19
+ const blockers = candidate.windows.filter((window) => window.blockedBy &&
20
+ scopeCovers(window.scope, input.effectiveModel, input.familyOf));
21
+ if (!blockers.length)
22
+ continue;
23
+ const resets = blockers.map((window) => {
24
+ const reset = window.reset;
25
+ const capturedAt = reset?.observedAt ?? reset?.checkedAt;
26
+ return reset &&
27
+ capturedAt !== undefined &&
28
+ Number.isFinite(capturedAt) &&
29
+ now - capturedAt <= input.maxAgeMs &&
30
+ Number.isFinite(reset.at) &&
31
+ reset.at > now
32
+ ? reset.at
33
+ : undefined;
34
+ });
35
+ // One unknown blocking window means this account has no known release time.
36
+ if (resets.some((reset) => reset === undefined))
37
+ continue;
38
+ const resetAt = Math.max(...resets);
39
+ if (best && best.resetAt <= resetAt)
40
+ continue;
41
+ const floorDefined = blockers.some((window) => window.blockedBy !== 'exhausted' && window.reset?.at === resetAt);
42
+ best = {
43
+ account: candidate.account,
44
+ resetAt,
45
+ checkpoint: {
46
+ accountKey: { ...candidate.account },
47
+ decidedAt: now,
48
+ blockers: floorDefined
49
+ ? []
50
+ : blockers.flatMap((window) => window.blockedBy === 'exhausted' && window.reset
51
+ ? [
52
+ {
53
+ window: window.window,
54
+ resetAt: window.reset.at,
55
+ },
56
+ ]
57
+ : []),
58
+ },
59
+ };
60
+ }
61
+ return best;
62
+ }
63
+ function applies(metadata, axes) {
64
+ return (metadata.source === 'pool' &&
65
+ metadata.reason === 'quota' &&
66
+ axes.terminalMetadata === 'setting-capped-fresh');
67
+ }
68
+ export function terminalWaitDisabled(metadata, axes) {
69
+ return (applies(metadata, axes) &&
70
+ readMaxSameAccountWait(metadata.scan?.maxSameAccountWait) === 0);
71
+ }
72
+ /**
73
+ * When no account is ready, cap the wait by the setting rather than cache expiry.
74
+ * Unlike a same-account hold, this wait may proceed without a cache activity record.
75
+ */
76
+ export function terminalRefusalDecision(facts, axes, history, metadata) {
77
+ if (!applies(metadata, axes))
78
+ return undefined;
79
+ const scan = metadata.scan;
80
+ const setting = readMaxSameAccountWait(scan?.maxSameAccountWait);
81
+ const kept = scan && scanTerminalReset(scan, facts.now);
82
+ const base = kept ? kept.resetAt - facts.now : 300000;
83
+ const record = scan?.activity;
84
+ const account = scan?.accountKey ?? facts.attempted;
85
+ const ttl = record && account && sameAccount(record.accountKey, account)
86
+ ? effectiveCacheTtlMs(record.ttlMs) || 300000
87
+ : 300000;
88
+ const delayMs = Math.min(base, setting === 'max' ? ttl : 900000);
89
+ const final = setting === 0 || (facts.host === 'pi' && facts.wake?.kind === 'terminal');
90
+ const retryAfterMs = final ? (kept ? base : undefined) : delayMs;
91
+ const policy = axes.refusals.quota[facts.host];
92
+ const refuse = {
93
+ action: 'refuse',
94
+ reason: 'quota',
95
+ family: facts.host === 'pi' ? 'pi-final' : final ? 'json-412' : policy.family,
96
+ messageKey: metadata.messageKey ?? policy.messageKey,
97
+ retryable: facts.host !== 'pi' && !final,
98
+ hostRetry: facts.host === 'pi' || final ? 'veto' : 'leave',
99
+ history,
100
+ ...(retryAfterMs === undefined ? {} : { retryAfterMs }),
101
+ ...(kept ? { resetAt: kept.resetAt } : {}),
102
+ };
103
+ if (!kept || final || facts.host === 'opencode1')
104
+ return refuse;
105
+ const wait = {
106
+ delayMs,
107
+ retryAfterMs: delayMs,
108
+ resetAt: kept.resetAt,
109
+ target: facts.now + delayMs,
110
+ checkpoint: kept.checkpoint,
111
+ waitKind: 'terminal',
112
+ reason: 'terminal-quota',
113
+ retryable: true,
114
+ hostRetry: 'leave',
115
+ history,
116
+ };
117
+ if (facts.host === 'pi')
118
+ return { ...wait, action: 'wait-then-reselect' };
119
+ if (facts.hostPhase !== 'retry')
120
+ return refuse;
121
+ if (facts.remainingRetries !== undefined && facts.remainingRetries < 1)
122
+ return {
123
+ action: 'pass',
124
+ reason: 'host-retries-exhausted',
125
+ retryable: true,
126
+ hostRetry: 'leave',
127
+ history,
128
+ };
129
+ if (facts.remainingRetries === undefined ||
130
+ delayMs > MAX_SAME_ACCOUNT_HOLD_MS)
131
+ return refuse;
132
+ return { ...wait, action: 'hold', account: kept.account };
133
+ }
@@ -0,0 +1,16 @@
1
+ import { type LimitsRecoveryLogger } from './envelope-loss.js';
2
+ import type { PersistenceAdapter } from './persistence.js';
3
+ export interface VaultLimitsAdapterOptions {
4
+ /** Canonical provider and roster namespace, shared by every process using this roster. */
5
+ readonly namespace: string;
6
+ readonly path: string;
7
+ readonly now?: () => number;
8
+ /** Receives a warning when a detached envelope repair fails. */
9
+ readonly logger?: LimitsRecoveryLogger;
10
+ }
11
+ /**
12
+ * Reads use one atomic roster snapshot. Commits re-read both limits and row
13
+ * bindings under the roster's existing write lock, without accessing local
14
+ * account-pool files.
15
+ */
16
+ export declare function createVaultLimitsAdapter(options: VaultLimitsAdapterOptions): Promise<PersistenceAdapter>;
@@ -0,0 +1,123 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { mutateVaultRoster, readVaultRoster, } from '../claustrum/roster.js';
3
+ import { EnvelopeHistory, EnvelopeRepair, } from './envelope-loss.js';
4
+ import { applyLimitsCommands, createLimitsNamespace, } from './namespace.js';
5
+ function bindingsOf(namespace, roster) {
6
+ return (roster?.rows ?? []).map((row) => ({
7
+ account: {
8
+ namespace,
9
+ accountId: row.routeId,
10
+ // Credential ids can change within the same provider account; addedAt
11
+ // survives those changes but changes when a removed route returns.
12
+ incarnation: String(row.addedAt),
13
+ },
14
+ credentialEpoch: String(row.addedAt),
15
+ ...(row.accountIdentity === undefined
16
+ ? {}
17
+ : { identity: row.accountIdentity }),
18
+ }));
19
+ }
20
+ function decodeEnvelope(value, namespace, generation) {
21
+ if (value === undefined)
22
+ return createLimitsNamespace(namespace, generation);
23
+ if (value === null ||
24
+ typeof value !== 'object' ||
25
+ !('schemaVersion' in value) ||
26
+ value.schemaVersion !== 1 ||
27
+ !('namespace' in value) ||
28
+ value.namespace !== namespace ||
29
+ !('generation' in value) ||
30
+ typeof value.generation !== 'string' ||
31
+ !('revision' in value) ||
32
+ !Number.isSafeInteger(value.revision) ||
33
+ value.revision < 0 ||
34
+ !('lowWatermark' in value) ||
35
+ !Number.isSafeInteger(value.lowWatermark) ||
36
+ value.lowWatermark < 0 ||
37
+ !('marks' in value) ||
38
+ !Array.isArray(value.marks) ||
39
+ !('tombstones' in value) ||
40
+ !Array.isArray(value.tombstones) ||
41
+ !('operationIds' in value) ||
42
+ !Array.isArray(value.operationIds) ||
43
+ !('access' in value) ||
44
+ !Array.isArray(value.access))
45
+ throw new TypeError('Invalid or unsupported vault limits namespace');
46
+ return value;
47
+ }
48
+ /**
49
+ * Reads use one atomic roster snapshot. Commits re-read both limits and row
50
+ * bindings under the roster's existing write lock, without accessing local
51
+ * account-pool files.
52
+ */
53
+ export async function createVaultLimitsAdapter(options) {
54
+ const { namespace, path } = options;
55
+ const generation = randomUUID();
56
+ const history = new EnvelopeHistory();
57
+ const repair = new EnvelopeRepair(options.logger);
58
+ const now = options.now ?? Date.now;
59
+ const read = async (previous) => {
60
+ const roster = await readVaultRoster(path);
61
+ const present = roster?.limits === undefined
62
+ ? undefined
63
+ : decodeEnvelope(roster.limits, namespace, generation);
64
+ if (history.lost(present, previous)) {
65
+ repair.schedule(() => adapter.commit([], previous));
66
+ return {
67
+ snapshot: history.recover(present, previous, namespace, now()),
68
+ bindings: bindingsOf(namespace, roster),
69
+ authoritative: false,
70
+ degradedAgreement: true,
71
+ };
72
+ }
73
+ if (present)
74
+ history.remember(present);
75
+ return {
76
+ snapshot: present ?? createLimitsNamespace(namespace, generation),
77
+ bindings: bindingsOf(namespace, roster),
78
+ authoritative: true,
79
+ };
80
+ };
81
+ const adapter = {
82
+ namespace,
83
+ read,
84
+ subscribe: repair.subscribe,
85
+ commit: async (commands, previous) => {
86
+ const committed = await mutateVaultRoster(path, (current) => {
87
+ const bindings = bindingsOf(namespace, current);
88
+ const present = current?.limits === undefined
89
+ ? undefined
90
+ : decodeEnvelope(current.limits, namespace, generation);
91
+ const degradedAgreement = history.lost(present, previous);
92
+ const result = applyLimitsCommands(degradedAgreement
93
+ ? history.recover(present, previous, namespace, now())
94
+ : (present ?? createLimitsNamespace(namespace, generation)), commands, {
95
+ now: now(),
96
+ bindings,
97
+ authorizeEpoch: (observed, authoritative) => observed.credentialEpoch === authoritative.credentialEpoch,
98
+ });
99
+ return {
100
+ next: {
101
+ ...(current ?? {
102
+ version: 1,
103
+ complete: true,
104
+ rows: [],
105
+ declined: [],
106
+ }),
107
+ limits: result.snapshot,
108
+ },
109
+ result: {
110
+ ...result,
111
+ bindings,
112
+ authoritative: true,
113
+ degradedAgreement,
114
+ },
115
+ };
116
+ });
117
+ history.remember(committed.snapshot, previous);
118
+ return committed;
119
+ },
120
+ };
121
+ await read();
122
+ return adapter;
123
+ }
@@ -0,0 +1 @@
1
+ export { createVaultLimitsAdapter, type VaultLimitsAdapterOptions, } from './vault-adapter.js';
@@ -0,0 +1 @@
1
+ export { createVaultLimitsAdapter, } from './vault-adapter.js';
@@ -0,0 +1,21 @@
1
+ import type { WaitCheckpoint } from './decide.js';
2
+ import type { AccountKey, LimitWindow } from './signal.js';
3
+ export interface WakeFacts {
4
+ readonly checkpoint: WaitCheckpoint;
5
+ readonly target: number;
6
+ /**
7
+ * Ordinary holds require this session/account's provider prompt cache to
8
+ * remain valid; terminal waits instead wait for pool quota, without a cache.
9
+ */
10
+ readonly kind?: 'hold' | 'terminal';
11
+ }
12
+ /**
13
+ * Snapshot exhaustion blockers only. A wait caused by a minimum-remaining quota
14
+ * threshold supplies no windows: elapsed time cannot prove renewed headroom.
15
+ */
16
+ export declare function waitCheckpoint(accountKey: AccountKey, decidedAt: number, windows: readonly LimitWindow[]): WaitCheckpoint;
17
+ /**
18
+ * Match exhaustion evidence for one wake dispatch, without refreshing quota.
19
+ * The caller must still check admission, other blockers and any cache bound.
20
+ */
21
+ export declare function liftedWindowsForWake(wake: WakeFacts, account: AccountKey, windows: readonly LimitWindow[], now: number): readonly string[];
@@ -0,0 +1,47 @@
1
+ import { sameAccount } from './request-history.js';
2
+ /**
3
+ * Snapshot exhaustion blockers only. A wait caused by a minimum-remaining quota
4
+ * threshold supplies no windows: elapsed time cannot prove renewed headroom.
5
+ */
6
+ export function waitCheckpoint(accountKey, decidedAt, windows) {
7
+ return {
8
+ accountKey: { ...accountKey },
9
+ decidedAt,
10
+ blockers: windows
11
+ .filter((window) => window.confirmed && Number.isFinite(window.resetAt))
12
+ .map((window) => ({
13
+ window: window.window,
14
+ resetAt: window.resetAt,
15
+ })),
16
+ };
17
+ }
18
+ /**
19
+ * Match exhaustion evidence for one wake dispatch, without refreshing quota.
20
+ * The caller must still check admission, other blockers and any cache bound.
21
+ */
22
+ export function liftedWindowsForWake(wake, account, windows, now) {
23
+ const { checkpoint, target } = wake;
24
+ if (!sameAccount(account, checkpoint.accountKey) ||
25
+ !Number.isFinite(target) ||
26
+ !Number.isFinite(checkpoint.decidedAt) ||
27
+ target < checkpoint.decidedAt ||
28
+ !Number.isFinite(now) ||
29
+ now < target)
30
+ return [];
31
+ const canLift = (window) => {
32
+ const resetAt = window.resetAt;
33
+ return (window.confirmed &&
34
+ resetAt !== undefined &&
35
+ Number.isFinite(resetAt) &&
36
+ resetAt <= target &&
37
+ checkpoint.blockers.some((blocker) => blocker.window === window.window &&
38
+ Number.isFinite(blocker.resetAt) &&
39
+ resetAt <= blocker.resetAt));
40
+ };
41
+ return windows
42
+ .filter((window) => canLift(window) &&
43
+ windows
44
+ .filter((other) => other.confirmed && other.window === window.window)
45
+ .every(canLift))
46
+ .map((window) => window.window);
47
+ }
@@ -0,0 +1,25 @@
1
+ import type { ResetFormatter } from './duration.js';
2
+ export declare function hasUnsafeWording(text: string): boolean;
3
+ export interface MessageParameters {
4
+ readonly labels: readonly string[];
5
+ readonly retryIn?: string;
6
+ readonly reset?: string;
7
+ }
8
+ /** Templates return text only; they cannot replace a family's wire envelope. */
9
+ export type MessageTemplate = (parameters: MessageParameters) => string;
10
+ export declare class UnsafeWordingError extends Error {
11
+ readonly messageKey: string;
12
+ readonly code = "unsafe-wording";
13
+ constructor(messageKey: string);
14
+ }
15
+ export interface LimitMessageOptions {
16
+ readonly refusals?: Readonly<Record<string, MessageTemplate>>;
17
+ readonly retryable?: Readonly<Record<string, MessageTemplate>>;
18
+ readonly formatReset?: ResetFormatter;
19
+ }
20
+ export interface LimitMessages {
21
+ readonly formatReset?: ResetFormatter;
22
+ readonly render: (messageKey: string, parameters: MessageParameters, nonRetryable: boolean) => string | undefined;
23
+ }
24
+ /** Registration rejects unsafe fixed text; actual substitutions are checked again. */
25
+ export declare function registerLimitMessages(options: LimitMessageOptions): LimitMessages;