@cortexkit/common-auth 0.1.2 → 0.2.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 (49) hide show
  1. package/dist/quota/codec.d.ts +11 -0
  2. package/dist/quota/codec.js +12 -0
  3. package/dist/quota/index.d.ts +8 -0
  4. package/dist/quota/index.js +4 -0
  5. package/dist/quota/map.d.ts +63 -0
  6. package/dist/quota/map.js +105 -0
  7. package/dist/quota/merge.d.ts +48 -0
  8. package/dist/quota/merge.js +162 -0
  9. package/dist/quota/projection.d.ts +57 -0
  10. package/dist/quota/projection.js +127 -0
  11. package/dist/routing/admission.d.ts +93 -0
  12. package/dist/routing/admission.js +140 -0
  13. package/dist/routing/index.d.ts +8 -0
  14. package/dist/routing/index.js +4 -0
  15. package/dist/routing/ordered.d.ts +47 -0
  16. package/dist/routing/ordered.js +58 -0
  17. package/dist/routing/pins.d.ts +22 -0
  18. package/dist/routing/pins.js +34 -0
  19. package/dist/routing/sticky.d.ts +118 -0
  20. package/dist/routing/sticky.js +310 -0
  21. package/dist/sidebar-file/sidebar-file.d.ts +4 -3
  22. package/dist/sidebar-file/sidebar-file.js +1 -4
  23. package/dist/store/attribution.d.ts +17 -0
  24. package/dist/store/attribution.js +46 -0
  25. package/dist/store/errors.d.ts +52 -0
  26. package/dist/store/errors.js +38 -0
  27. package/dist/store/hooks.d.ts +12 -0
  28. package/dist/store/hooks.js +34 -0
  29. package/dist/store/identity.d.ts +23 -0
  30. package/dist/store/identity.js +53 -0
  31. package/dist/store/index.d.ts +16 -0
  32. package/dist/store/index.js +5 -0
  33. package/dist/store/mutate.d.ts +111 -0
  34. package/dist/store/mutate.js +294 -0
  35. package/dist/store/pool.d.ts +86 -0
  36. package/dist/store/pool.js +98 -0
  37. package/dist/store/pull.d.ts +36 -0
  38. package/dist/store/pull.js +129 -0
  39. package/dist/store/refresh-lock.d.ts +63 -0
  40. package/dist/store/refresh-lock.js +125 -0
  41. package/dist/store/refresh.d.ts +48 -0
  42. package/dist/store/refresh.js +169 -0
  43. package/dist/store/rows.d.ts +53 -0
  44. package/dist/store/rows.js +250 -0
  45. package/dist/store/runtime.d.ts +28 -0
  46. package/dist/store/runtime.js +45 -0
  47. package/dist/store/schema.d.ts +133 -0
  48. package/dist/store/schema.js +323 -0
  49. package/package.json +13 -1
@@ -0,0 +1,93 @@
1
+ import { type QuotaMap } from '../quota/map.js';
2
+ import { type ProjectedQuota } from '../quota/projection.js';
3
+ export type RowKind = 'oauth' | 'api-key';
4
+ export interface RoutingRow {
5
+ id: string;
6
+ kind: RowKind;
7
+ /** The row's stored quota map; absent is the same as an empty map. */
8
+ quota?: QuotaMap;
9
+ }
10
+ export interface WindowRef {
11
+ scope: string;
12
+ label: string;
13
+ }
14
+ export interface ExclusionInputs {
15
+ /** Row id to the time (ms) a rate-limit mark expires. */
16
+ rateLimitMarks?: ReadonlyMap<string, number>;
17
+ /** Row id to the time (ms) a failed refresh may be retried. */
18
+ refreshBackoff?: ReadonlyMap<string, number>;
19
+ }
20
+ export interface AdmissionInput extends ExclusionInputs {
21
+ rows: readonly RoutingRow[];
22
+ /** `all` (the default) or a model family. */
23
+ scope?: string;
24
+ /** Labels the scope requires an entry for; defaults to `['primary']`. */
25
+ requiredLabels?: readonly string[];
26
+ now: number;
27
+ /**
28
+ * Called synchronously, once per refusal at gates 2 to 4, with the row id.
29
+ * Its return value is ignored and never awaited, so a pull the caller
30
+ * starts from here cannot delay the refusal.
31
+ */
32
+ requestPull?: (rowId: string) => void;
33
+ }
34
+ export type AdmissionRefusal = {
35
+ id: string;
36
+ stage: 1;
37
+ gate: 2;
38
+ reason: 'needs-first-reading';
39
+ pullRequested: true;
40
+ } | {
41
+ id: string;
42
+ stage: 1;
43
+ gate: 3;
44
+ reason: 'unknown-window';
45
+ window: WindowRef;
46
+ pullRequested: true;
47
+ } | {
48
+ id: string;
49
+ stage: 1;
50
+ gate: 4;
51
+ reason: 'unknown-reset';
52
+ window: WindowRef;
53
+ pullRequested: true;
54
+ } | {
55
+ id: string;
56
+ stage: 1;
57
+ gate: 5;
58
+ reason: 'exhausted';
59
+ window: WindowRef;
60
+ resetsAt: string;
61
+ resetAtMs: number;
62
+ } | {
63
+ id: string;
64
+ stage: 2;
65
+ reason: 'budget-spent';
66
+ resetsAt: string;
67
+ resetAtMs: number;
68
+ };
69
+ export interface AdmissionExclusion {
70
+ id: string;
71
+ reason: 'rate-limited' | 'refresh-backoff';
72
+ until: number;
73
+ }
74
+ export interface AdmittedRow {
75
+ id: string;
76
+ kind: RowKind;
77
+ /** The projection admission judged; absent for API-key rows. */
78
+ projection?: ProjectedQuota;
79
+ /** Set when a spent budget was kept because no other path survived. */
80
+ lastPath?: true;
81
+ }
82
+ export interface AdmissionResult {
83
+ /** In input order. */
84
+ admitted: AdmittedRow[];
85
+ refused: AdmissionRefusal[];
86
+ excluded: AdmissionExclusion[];
87
+ /** Ids a pull was requested for, in input order. */
88
+ pulls: string[];
89
+ }
90
+ /** The exclusion that applies to `id` at `now`, if any. */
91
+ export declare function exclusionFor(id: string, inputs: ExclusionInputs, now: number): AdmissionExclusion | undefined;
92
+ /** Runs both admission stages over `input.rows`. */
93
+ export declare function admit(input: AdmissionInput): AdmissionResult;
@@ -0,0 +1,140 @@
1
+ // Admission: which candidate rows may be dispatched for one request.
2
+ //
3
+ // Pure: the caller passes the candidate rows with their quota maps, the
4
+ // request's scope, the window labels that scope requires, and the rate-limit
5
+ // marks and refresh backoff it holds. Nothing is read or written here.
6
+ //
7
+ // A marked or backed-off row is excluded before the gates. Stage 1 then
8
+ // judges each remaining row alone, in gate order:
9
+ // 1. an API-key row is admitted without consulting quota;
10
+ // 2. an OAuth row whose projection resolves no entry for the scope needs a
11
+ // first reading: refused, pull requested;
12
+ // 3. a required label with no entry is unknown: refused, pull requested;
13
+ // 4. a reading at or beyond 100% whose reset is missing, unparsable or not
14
+ // after `now` cannot confirm the exhaustion, so the window is unknown:
15
+ // refused, pull requested;
16
+ // 5. a reading at or beyond 100% with a future reset is exhausted: refused.
17
+ // Gates 4 and 5 look at every projected limit, not only the required labels.
18
+ // Stage 2 judges the credit budget across the stage-1 survivors: a row whose
19
+ // budget is known spent (reached, with a parsable future reset) is refused
20
+ // unless every survivor's budget is spent, in which case all of them stay
21
+ // admitted as the last path. Every missing, malformed or passed budget reset
22
+ // fails open. Stage-1 refusals have no last-path exception.
23
+ import { ALL_SCOPE, DEFAULT_REQUIRED_LABELS, } from '../quota/map.js';
24
+ import { budgetExhaustedResetAt, futureResetAt, projectQuota, readsExhausted, } from '../quota/projection.js';
25
+ /** The exclusion that applies to `id` at `now`, if any. */
26
+ export function exclusionFor(id, inputs, now) {
27
+ const markedUntil = inputs.rateLimitMarks?.get(id);
28
+ if (markedUntil !== undefined && now < markedUntil) {
29
+ return { id, reason: 'rate-limited', until: markedUntil };
30
+ }
31
+ const backoffUntil = inputs.refreshBackoff?.get(id);
32
+ if (backoffUntil !== undefined && now < backoffUntil) {
33
+ return { id, reason: 'refresh-backoff', until: backoffUntil };
34
+ }
35
+ return undefined;
36
+ }
37
+ function judgeStageOne(id, projection, requiredLabels, now) {
38
+ if (projection.limits.length === 0) {
39
+ return {
40
+ id,
41
+ stage: 1,
42
+ gate: 2,
43
+ reason: 'needs-first-reading',
44
+ pullRequested: true,
45
+ };
46
+ }
47
+ for (const label of requiredLabels) {
48
+ if (!projection.limits.some((limit) => limit.label === label)) {
49
+ return {
50
+ id,
51
+ stage: 1,
52
+ gate: 3,
53
+ reason: 'unknown-window',
54
+ window: { scope: projection.scope, label },
55
+ pullRequested: true,
56
+ };
57
+ }
58
+ }
59
+ const exhausted = projection.limits.filter(readsExhausted);
60
+ for (const limit of exhausted) {
61
+ if (futureResetAt(limit, now) === undefined) {
62
+ return {
63
+ id,
64
+ stage: 1,
65
+ gate: 4,
66
+ reason: 'unknown-reset',
67
+ window: { scope: limit.scope, label: limit.label },
68
+ pullRequested: true,
69
+ };
70
+ }
71
+ }
72
+ for (const limit of exhausted) {
73
+ const resetAtMs = futureResetAt(limit, now);
74
+ if (resetAtMs !== undefined && typeof limit.resetsAt === 'string') {
75
+ return {
76
+ id,
77
+ stage: 1,
78
+ gate: 5,
79
+ reason: 'exhausted',
80
+ window: { scope: limit.scope, label: limit.label },
81
+ resetsAt: limit.resetsAt,
82
+ resetAtMs,
83
+ };
84
+ }
85
+ }
86
+ return undefined;
87
+ }
88
+ /** Runs both admission stages over `input.rows`. */
89
+ export function admit(input) {
90
+ const scope = input.scope ?? ALL_SCOPE;
91
+ const requiredLabels = input.requiredLabels ?? DEFAULT_REQUIRED_LABELS;
92
+ const excluded = [];
93
+ const refused = [];
94
+ const survivors = [];
95
+ for (const row of input.rows) {
96
+ const exclusion = exclusionFor(row.id, input, input.now);
97
+ if (exclusion) {
98
+ excluded.push(exclusion);
99
+ continue;
100
+ }
101
+ if (row.kind === 'api-key') {
102
+ survivors.push({ id: row.id, kind: row.kind });
103
+ continue;
104
+ }
105
+ const projection = projectQuota(row.quota, scope);
106
+ const refusal = judgeStageOne(row.id, projection, requiredLabels, input.now);
107
+ if (refusal) {
108
+ refused.push(refusal);
109
+ continue;
110
+ }
111
+ survivors.push({ id: row.id, kind: row.kind, projection });
112
+ }
113
+ const spent = new Map(survivors.flatMap((row) => {
114
+ const reset = budgetExhaustedResetAt(row.projection, input.now);
115
+ return reset ? [[row.id, reset]] : [];
116
+ }));
117
+ const lastPath = spent.size > 0 && spent.size === survivors.length;
118
+ const admitted = [];
119
+ for (const row of survivors) {
120
+ const reset = spent.get(row.id);
121
+ if (reset === undefined) {
122
+ admitted.push(row);
123
+ }
124
+ else if (lastPath) {
125
+ admitted.push({ ...row, lastPath: true });
126
+ }
127
+ else {
128
+ refused.push({ id: row.id, stage: 2, reason: 'budget-spent', ...reset });
129
+ }
130
+ }
131
+ const order = new Map(input.rows.map((row, index) => [row.id, index]));
132
+ const byInput = (left, right) => (order.get(left.id) ?? 0) - (order.get(right.id) ?? 0);
133
+ refused.sort(byInput);
134
+ const pulls = refused
135
+ .filter((refusal) => 'pullRequested' in refusal)
136
+ .map((refusal) => refusal.id);
137
+ for (const id of pulls)
138
+ input.requestPull?.(id);
139
+ return { admitted, refused, excluded, pulls };
140
+ }
@@ -0,0 +1,8 @@
1
+ export type { AdmissionExclusion, AdmissionInput, AdmissionRefusal, AdmissionResult, AdmittedRow, ExclusionInputs, RoutingRow, RowKind, WindowRef, } from './admission.js';
2
+ export { admit, exclusionFor } from './admission.js';
3
+ export type { OrderedAttempt, OrderedPlacement, OrderedRoute, OrderedRouteInput, ResolvedRoutingMode, RoutingMode, } from './ordered.js';
4
+ export { DEFAULT_FORMER_MAIN_ID, nextOrderedAttempt, orderForPlacement, resolveRoutingMode, routeOrdered, } from './ordered.js';
5
+ export type { StickyPin } from './pins.js';
6
+ export { isPinValid, pendingBytesForPins } from './pins.js';
7
+ export type { PinAction, StickyBreakDecision, StickyRoute, StickyRouteInput, StickySelection, StickySelectionCandidate, StickySelectionInput, } from './sticky.js';
8
+ export { decideStickyBreak, MIN_RESET_HOURS, MIN_WEIGHT, QUOTA_STALENESS_MS, routeSticky, STICKY_WINDOW_SLOTS, selectStickyCandidate, snapshotCheckedAt, sustainableWindowWeight, } from './sticky.js';
@@ -0,0 +1,4 @@
1
+ export { admit, exclusionFor } from './admission.js';
2
+ export { DEFAULT_FORMER_MAIN_ID, nextOrderedAttempt, orderForPlacement, resolveRoutingMode, routeOrdered, } from './ordered.js';
3
+ export { isPinValid, pendingBytesForPins } from './pins.js';
4
+ export { decideStickyBreak, MIN_RESET_HOURS, MIN_WEIGHT, QUOTA_STALENESS_MS, routeSticky, STICKY_WINDOW_SLOTS, selectStickyCandidate, snapshotCheckedAt, sustainableWindowWeight, } from './sticky.js';
@@ -0,0 +1,47 @@
1
+ import { type AdmissionInput, type AdmissionResult } from './admission.js';
2
+ export type RoutingMode = 'ordered' | 'sticky-balanced';
3
+ /** Where `ordered` routing places the former main row. */
4
+ export type OrderedPlacement = 'roster' | 'main-first' | 'fallback-first';
5
+ export interface ResolvedRoutingMode {
6
+ mode: RoutingMode;
7
+ placement: OrderedPlacement;
8
+ }
9
+ /** The former main row's id when the caller supplies none. */
10
+ export declare const DEFAULT_FORMER_MAIN_ID = "main";
11
+ /**
12
+ * Resolves a persisted `routing.mode` value. `main-first` and
13
+ * `fallback-first` are aliases of `ordered` that move the former main row;
14
+ * an absent or unrecognised value is `ordered` in roster order. The
15
+ * persisted value is only read here, never rewritten.
16
+ */
17
+ export declare function resolveRoutingMode(value: unknown): ResolvedRoutingMode;
18
+ /**
19
+ * Orders `ids` (in roster order) for a placement: `main-first` moves the row
20
+ * named `formerMainId` to the front, `fallback-first` to the back, and
21
+ * `roster` (or a missing former main row) keeps roster order.
22
+ */
23
+ export declare function orderForPlacement(ids: readonly string[], placement: OrderedPlacement, formerMainId?: string): string[];
24
+ export interface OrderedRouteInput extends AdmissionInput {
25
+ placement?: OrderedPlacement;
26
+ formerMainId?: string;
27
+ /** Killswitch verdict per row; `false` drops the row, a missing row passes. */
28
+ killswitch?: ReadonlyMap<string, boolean>;
29
+ }
30
+ export interface OrderedRoute {
31
+ /** Admitted, non-killed row ids in the order they are to be tried. */
32
+ order: string[];
33
+ admission: AdmissionResult;
34
+ }
35
+ export declare function routeOrdered(input: OrderedRouteInput): OrderedRoute;
36
+ export interface OrderedAttempt {
37
+ id: string;
38
+ /** The response status; undefined when no response arrived. */
39
+ status?: number;
40
+ }
41
+ /**
42
+ * The next row to try, given the attempts so far: the first row when none
43
+ * has been tried, the next untried row when the last attempt's status is one
44
+ * of `retryStatuses`, and undefined otherwise (the last response stands) or
45
+ * when every row has been tried.
46
+ */
47
+ export declare function nextOrderedAttempt(order: readonly string[], attempts: readonly OrderedAttempt[], retryStatuses: readonly number[]): string | undefined;
@@ -0,0 +1,58 @@
1
+ // `ordered` routing: admitted rows tried in a fixed order, moving to the next
2
+ // row only when a response carries one of the caller's retry statuses.
3
+ import { admit, } from './admission.js';
4
+ /** The former main row's id when the caller supplies none. */
5
+ export const DEFAULT_FORMER_MAIN_ID = 'main';
6
+ /**
7
+ * Resolves a persisted `routing.mode` value. `main-first` and
8
+ * `fallback-first` are aliases of `ordered` that move the former main row;
9
+ * an absent or unrecognised value is `ordered` in roster order. The
10
+ * persisted value is only read here, never rewritten.
11
+ */
12
+ export function resolveRoutingMode(value) {
13
+ switch (value) {
14
+ case 'sticky-balanced':
15
+ return { mode: 'sticky-balanced', placement: 'roster' };
16
+ case 'main-first':
17
+ return { mode: 'ordered', placement: 'main-first' };
18
+ case 'fallback-first':
19
+ return { mode: 'ordered', placement: 'fallback-first' };
20
+ default:
21
+ return { mode: 'ordered', placement: 'roster' };
22
+ }
23
+ }
24
+ /**
25
+ * Orders `ids` (in roster order) for a placement: `main-first` moves the row
26
+ * named `formerMainId` to the front, `fallback-first` to the back, and
27
+ * `roster` (or a missing former main row) keeps roster order.
28
+ */
29
+ export function orderForPlacement(ids, placement, formerMainId = DEFAULT_FORMER_MAIN_ID) {
30
+ if (placement === 'roster' || !ids.includes(formerMainId))
31
+ return [...ids];
32
+ const rest = ids.filter((id) => id !== formerMainId);
33
+ return placement === 'main-first'
34
+ ? [formerMainId, ...rest]
35
+ : [...rest, formerMainId];
36
+ }
37
+ export function routeOrdered(input) {
38
+ const admission = admit(input);
39
+ const admitted = new Set(admission.admitted.map((row) => row.id));
40
+ const order = orderForPlacement(input.rows.map((row) => row.id), input.placement ?? 'roster', input.formerMainId).filter((id) => admitted.has(id) && input.killswitch?.get(id) !== false);
41
+ return { order, admission };
42
+ }
43
+ /**
44
+ * The next row to try, given the attempts so far: the first row when none
45
+ * has been tried, the next untried row when the last attempt's status is one
46
+ * of `retryStatuses`, and undefined otherwise (the last response stands) or
47
+ * when every row has been tried.
48
+ */
49
+ export function nextOrderedAttempt(order, attempts, retryStatuses) {
50
+ const last = attempts.at(-1);
51
+ if (last !== undefined) {
52
+ if (last.status === undefined || !retryStatuses.includes(last.status)) {
53
+ return undefined;
54
+ }
55
+ }
56
+ const tried = new Set(attempts.map((attempt) => attempt.id));
57
+ return order.find((id) => !tried.has(id));
58
+ }
@@ -0,0 +1,22 @@
1
+ export interface StickyPin {
2
+ accountId: string;
3
+ /** The row's recorded wire identity when the pin was made, if known. */
4
+ wireIdentity?: string;
5
+ /** The request size recorded with the pin; weighs pending bytes. */
6
+ inputBytes?: number;
7
+ /** The projection time the placement was judged on. */
8
+ quotaCheckedAt?: number;
9
+ }
10
+ /**
11
+ * A pin survives while its row id is in `validIds` and the row still holds
12
+ * the account it was placed on. Only two known, differing identities prove
13
+ * the account changed: an unknown identity on either side keeps the pin,
14
+ * because re-placing a session on missing evidence throws its cache away.
15
+ */
16
+ export declare function isPinValid(pin: StickyPin, validIds: ReadonlySet<string>, currentIdentity: string | undefined): boolean;
17
+ /**
18
+ * Sums the request bytes of every other session's pin per row, as openai-auth
19
+ * does. A pin counts only while it was judged on the row's current
20
+ * projection time, so a fresh reading resets the row's pending load.
21
+ */
22
+ export declare function pendingBytesForPins(pins: Iterable<readonly [sessionKey: string, pin: StickyPin]>, quotaCheckedAtById: ReadonlyMap<string, number | undefined>, excludedSessionKey?: string): Map<string, number>;
@@ -0,0 +1,34 @@
1
+ // Session pins for `sticky-balanced` routing.
2
+ //
3
+ // A pin records which row a session was placed on so its prompt cache stays
4
+ // warm. The library persists no pin: the caller holds pins (in memory, or in
5
+ // a cross-process file it owns) and passes the relevant ones in per call.
6
+ /**
7
+ * A pin survives while its row id is in `validIds` and the row still holds
8
+ * the account it was placed on. Only two known, differing identities prove
9
+ * the account changed: an unknown identity on either side keeps the pin,
10
+ * because re-placing a session on missing evidence throws its cache away.
11
+ */
12
+ export function isPinValid(pin, validIds, currentIdentity) {
13
+ if (!validIds.has(pin.accountId))
14
+ return false;
15
+ return !(typeof pin.wireIdentity === 'string' &&
16
+ typeof currentIdentity === 'string' &&
17
+ pin.wireIdentity !== currentIdentity);
18
+ }
19
+ /**
20
+ * Sums the request bytes of every other session's pin per row, as openai-auth
21
+ * does. A pin counts only while it was judged on the row's current
22
+ * projection time, so a fresh reading resets the row's pending load.
23
+ */
24
+ export function pendingBytesForPins(pins, quotaCheckedAtById, excludedSessionKey) {
25
+ const pending = new Map();
26
+ for (const [sessionKey, pin] of pins) {
27
+ if (sessionKey === excludedSessionKey)
28
+ continue;
29
+ if (pin.quotaCheckedAt !== quotaCheckedAtById.get(pin.accountId))
30
+ continue;
31
+ pending.set(pin.accountId, (pending.get(pin.accountId) ?? 0) + (pin.inputBytes ?? 0));
32
+ }
33
+ return pending;
34
+ }
@@ -0,0 +1,118 @@
1
+ import { type ProjectedQuota } from '../quota/projection.js';
2
+ import { type AdmissionInput, type AdmissionRefusal, type AdmissionResult, type WindowRef } from './admission.js';
3
+ import { type StickyPin } from './pins.js';
4
+ export declare const QUOTA_STALENESS_MS: number;
5
+ export declare const MIN_RESET_HOURS: number;
6
+ export declare const MIN_WEIGHT = 0.000001;
7
+ /**
8
+ * How many window readings the selection primitives judge, as openai-auth's
9
+ * primary and secondary slots did. The projection's first readings in its
10
+ * order fill the slots; any further window is judged by admission only.
11
+ */
12
+ export declare const STICKY_WINDOW_SLOTS = 2;
13
+ /** The projection's time, else the caller's cache-entry time. */
14
+ export declare function snapshotCheckedAt(quota: ProjectedQuota | null | undefined, entryCheckedAt?: number): number | undefined;
15
+ export type StickyBreakDecision = {
16
+ action: 'retain';
17
+ reason: 'unknown' | 'stale' | 'healthy' | 'transient';
18
+ } | {
19
+ action: 'migrate';
20
+ reason: 'exhausted' | 'permanent' | 'killswitch';
21
+ /** The exhausted limit, named by its (scope, label), not its position. */
22
+ window?: WindowRef;
23
+ resetsAt?: string;
24
+ };
25
+ /** Classifies whether a pinned session should leave its row after a failure. */
26
+ export declare function decideStickyBreak(input: {
27
+ quota: ProjectedQuota | null | undefined;
28
+ quotaCheckedAt?: number;
29
+ status?: number;
30
+ now: number;
31
+ killswitchPasses?: boolean;
32
+ }): StickyBreakDecision;
33
+ export declare function sustainableWindowWeight(window: {
34
+ remainingPercent: number;
35
+ resetsAt?: string;
36
+ }, reservePercent: number, now: number): number;
37
+ export interface StickySelectionCandidate {
38
+ accountId: string;
39
+ quota: ProjectedQuota | null | undefined;
40
+ quotaCheckedAt?: number;
41
+ /** Reserve percent per window label; a missing label reserves nothing. */
42
+ reservePercent: Readonly<Record<string, number>>;
43
+ configuredOrder: number;
44
+ resetCreditsApplicable?: number;
45
+ /** `false` excludes the candidate from weighted and fallback placement. */
46
+ killswitchPasses?: boolean;
47
+ }
48
+ export interface StickySelectionInput {
49
+ candidates: readonly StickySelectionCandidate[];
50
+ pendingBytes: ReadonlyMap<string, number>;
51
+ requestBytes: number;
52
+ now: number;
53
+ onEmptyWeightedSet?: () => void;
54
+ }
55
+ export interface StickySelection {
56
+ accountId: string;
57
+ quotaCheckedAt?: number;
58
+ source: 'weighted' | 'mode-fallback';
59
+ }
60
+ /**
61
+ * Places a session: the lowest projected pressure among candidates with a
62
+ * fresh positive weight, else (`mode-fallback`) the first candidate in
63
+ * configured order, preferring one with an applicable reset credit.
64
+ */
65
+ export declare function selectStickyCandidate(input: StickySelectionInput): StickySelection | undefined;
66
+ export interface StickyRouteInput extends AdmissionInput {
67
+ requestBytes: number;
68
+ /** Bytes already committed per row, for example from other sessions' pins. */
69
+ pendingBytes?: ReadonlyMap<string, number>;
70
+ /** Killswitch verdict per row; a missing row passes. */
71
+ killswitch?: ReadonlyMap<string, boolean>;
72
+ /** Reserve percent per window label, applied to every row. */
73
+ reservePercent?: Readonly<Record<string, number>>;
74
+ resetCreditsApplicable?: ReadonlyMap<string, number>;
75
+ /** The session's current pin, if it has one. */
76
+ pin?: StickyPin;
77
+ /** Each row's recorded wire identity; missing means unknown. */
78
+ identities?: ReadonlyMap<string, string | undefined>;
79
+ onEmptyWeightedSet?: () => void;
80
+ }
81
+ /**
82
+ * What the caller does with the session's pin: keep it, replace it with
83
+ * `pin`, or drop it. A valid pin is always kept, even when this request was
84
+ * routed elsewhere because its row was refused or excluded.
85
+ */
86
+ export type PinAction = {
87
+ action: 'retain';
88
+ } | {
89
+ action: 'assign';
90
+ pin: StickyPin;
91
+ } | {
92
+ action: 'clear';
93
+ } | {
94
+ action: 'none';
95
+ };
96
+ export type StickyRoute = {
97
+ outcome: 'dispatch';
98
+ accountId: string;
99
+ source: 'pin' | 'weighted' | 'mode-fallback';
100
+ quotaCheckedAt?: number;
101
+ pin: PinAction;
102
+ /** Rows that selection chose and admission then refused, in selection order. */
103
+ refusedSelections: AdmissionRefusal[];
104
+ admission: AdmissionResult;
105
+ } | {
106
+ outcome: 'no-admissible-account';
107
+ pin: PinAction;
108
+ refusedSelections: AdmissionRefusal[];
109
+ admission: AdmissionResult;
110
+ };
111
+ /**
112
+ * Routes one request in `sticky-balanced` mode. A valid pin whose row is
113
+ * admitted, not excluded and not killed is dispatched as is. Otherwise
114
+ * selection runs over the non-excluded rows; each selected row admission
115
+ * refused is removed and selection re-runs, so the loop ends either on an
116
+ * admitted row or with no admissible account.
117
+ */
118
+ export declare function routeSticky(input: StickyRouteInput): StickyRoute;