@opengeni/config 1.2.2 → 1.3.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/claude-subscription-capacity.d.ts +9 -0
- package/dist/claude-subscription-oauth.d.ts +17 -0
- package/dist/claude-subscription-usage.d.ts +13 -0
- package/dist/credit-promotions.d.ts +25 -0
- package/dist/index.d.ts +783 -12
- package/dist/index.js +2368 -595
- package/dist/index.js.map +1 -1
- package/dist/managed-user-admission.d.ts +2 -0
- package/dist/subscription-account-selection.d.ts +17 -0
- package/package.json +4 -4
- package/src/claude-subscription-capacity.ts +129 -0
- package/src/claude-subscription-oauth.ts +33 -0
- package/src/claude-subscription-usage.ts +328 -0
- package/src/credit-promotions.ts +68 -0
- package/src/index.ts +2248 -278
- package/src/managed-user-admission.ts +11 -0
- package/src/subscription-account-selection.ts +36 -0
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
/** Stable account affinity shared by subscription providers. Candidate order is durable creation order. */
|
|
2
|
+
export declare function subscriptionAccountShardIndex(sessionId: string, candidateCount: number): number;
|
|
3
|
+
/**
|
|
4
|
+
* Manual pins are binding even when unavailable. Policy homes remain sticky only
|
|
5
|
+
* while rotation is on; an exhausted home re-shards over the eligible survivors.
|
|
6
|
+
* Selection never changes the pool's active pointer.
|
|
7
|
+
*/
|
|
8
|
+
export declare function selectSubscriptionAccount<T extends {
|
|
9
|
+
id: string;
|
|
10
|
+
}>(input: {
|
|
11
|
+
sessionId: string;
|
|
12
|
+
eligible: readonly T[];
|
|
13
|
+
rotationEnabled: boolean;
|
|
14
|
+
activeCredentialId: string | null;
|
|
15
|
+
pinnedCredentialId: string | null;
|
|
16
|
+
pinSource: "manual" | "policy" | null;
|
|
17
|
+
}): T | null;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@opengeni/config",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.3.0",
|
|
4
4
|
"description": "OpenGeni runtime configuration: settings resolution, deployment knobs, and config validation shared across the server packages.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -33,9 +33,9 @@
|
|
|
33
33
|
"prepublishOnly": "bash ../../scripts/prepublish-guard"
|
|
34
34
|
},
|
|
35
35
|
"dependencies": {
|
|
36
|
-
"@opengeni/codex": "
|
|
37
|
-
"@opengeni/contracts": "
|
|
38
|
-
"@opengeni/xai-subscription": "
|
|
36
|
+
"@opengeni/codex": "1.3.0",
|
|
37
|
+
"@opengeni/contracts": "1.3.0",
|
|
38
|
+
"@opengeni/xai-subscription": "1.3.0",
|
|
39
39
|
"zod": "^4.2.1"
|
|
40
40
|
},
|
|
41
41
|
"engines": {
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import type { ClaudeSubscriptionUsage, ClaudeUsageWindow } from "@opengeni/contracts";
|
|
2
|
+
|
|
3
|
+
const UNKNOWN_RESET_RECHECK_MS = 60_000;
|
|
4
|
+
const allowed = (status: ClaudeUsageWindow["status"]) =>
|
|
5
|
+
status === "allowed" || status === "allowed_warning";
|
|
6
|
+
|
|
7
|
+
/** Evaluate provider-reported plan capacity and its explicitly allowed paid fallback. */
|
|
8
|
+
export function claudeSubscriptionCapacity(
|
|
9
|
+
usage: ClaudeSubscriptionUsage,
|
|
10
|
+
upstreamModelId: string,
|
|
11
|
+
now: Date,
|
|
12
|
+
options: { allowOverage?: boolean } = {},
|
|
13
|
+
): { available: boolean; nextCheckAt: Date | null; blockingWindows: ClaudeUsageWindow["id"][] } {
|
|
14
|
+
const available = { available: true, nextCheckAt: null, blockingWindows: [] };
|
|
15
|
+
if (!usage.connected || usage.refreshStatus === "reconnect")
|
|
16
|
+
return { ...available, available: false };
|
|
17
|
+
const relevant = (id: ClaudeUsageWindow["id"]): boolean => {
|
|
18
|
+
if (id === "seven_day_opus") return /^claude-opus-/.test(upstreamModelId);
|
|
19
|
+
if (id === "seven_day_sonnet") return /^claude-sonnet-/.test(upstreamModelId);
|
|
20
|
+
return id === "five_hour" || id === "seven_day";
|
|
21
|
+
};
|
|
22
|
+
const applicable = usage.windows.filter((window) => relevant(window.id));
|
|
23
|
+
const relevantClaim = (id: ClaudeUsageWindow["id"] | null) =>
|
|
24
|
+
id === "seven_day_opus" || id === "seven_day_sonnet" ? relevant(id) : true;
|
|
25
|
+
const restrictions = (usage.requestRestrictions ?? []).filter(
|
|
26
|
+
(item) =>
|
|
27
|
+
item.status === "rejected" &&
|
|
28
|
+
(item.upstreamModelId === upstreamModelId ||
|
|
29
|
+
(item.upstreamModelId === null && relevantClaim(item.representativeClaim))) &&
|
|
30
|
+
!applicable.some(
|
|
31
|
+
(window) =>
|
|
32
|
+
window.source === "provider" &&
|
|
33
|
+
window.usedPercent !== null &&
|
|
34
|
+
window.usedPercent < 100 &&
|
|
35
|
+
window.id === item.representativeClaim &&
|
|
36
|
+
window.observedAt > item.observedAt,
|
|
37
|
+
) &&
|
|
38
|
+
(item.resetsAt
|
|
39
|
+
? Date.parse(item.resetsAt)
|
|
40
|
+
: Date.parse(item.observedAt) + UNKNOWN_RESET_RECHECK_MS) > now.getTime(),
|
|
41
|
+
);
|
|
42
|
+
const blocking = applicable.filter((window) => {
|
|
43
|
+
if (
|
|
44
|
+
(window.resetsAt
|
|
45
|
+
? Date.parse(window.resetsAt)
|
|
46
|
+
: Date.parse(window.observedAt) + UNKNOWN_RESET_RECHECK_MS) <= now.getTime()
|
|
47
|
+
)
|
|
48
|
+
return false;
|
|
49
|
+
return (
|
|
50
|
+
window.status === "rejected" || (window.status === null && (window.usedPercent ?? 0) >= 100)
|
|
51
|
+
);
|
|
52
|
+
});
|
|
53
|
+
const request = usage.requestStatus;
|
|
54
|
+
const exactModel = request?.upstreamModelId === upstreamModelId;
|
|
55
|
+
const relevantRequest =
|
|
56
|
+
request &&
|
|
57
|
+
(exactModel ||
|
|
58
|
+
(request.upstreamModelId === null && relevantClaim(request.representativeClaim)));
|
|
59
|
+
const freshRequest =
|
|
60
|
+
relevantRequest &&
|
|
61
|
+
applicable.every((window) => window.observedAt <= request.observedAt) &&
|
|
62
|
+
restrictions.every((item) => item.observedAt <= request.observedAt);
|
|
63
|
+
const planResetElapsed =
|
|
64
|
+
request &&
|
|
65
|
+
(request.resetsAt
|
|
66
|
+
? Date.parse(request.resetsAt)
|
|
67
|
+
: Date.parse(request.observedAt) + UNKNOWN_RESET_RECHECK_MS) <= now.getTime();
|
|
68
|
+
const exactAllowance = (usage.requestRestrictions ?? []).find(
|
|
69
|
+
(item) =>
|
|
70
|
+
item.upstreamModelId === upstreamModelId &&
|
|
71
|
+
allowed(item.status) &&
|
|
72
|
+
blocking.every((window) => window.observedAt < item.observedAt) &&
|
|
73
|
+
restrictions.every((restriction) => restriction.observedAt < item.observedAt),
|
|
74
|
+
);
|
|
75
|
+
if (exactAllowance) return available;
|
|
76
|
+
// An allowed response for Sonnet never overrides an independently observed
|
|
77
|
+
// Opus cap. Only the exact model's fresh response proves overall dispatch.
|
|
78
|
+
if (freshRequest && exactModel && allowed(request.status) && !planResetElapsed) return available;
|
|
79
|
+
const mayUseOverage = options.allowOverage !== false;
|
|
80
|
+
const overageResetElapsed =
|
|
81
|
+
request?.overageResetsAt && Date.parse(request.overageResetsAt) <= now.getTime();
|
|
82
|
+
if (
|
|
83
|
+
freshRequest &&
|
|
84
|
+
request.status === "rejected" &&
|
|
85
|
+
mayUseOverage &&
|
|
86
|
+
allowed(request.overageStatus) &&
|
|
87
|
+
!overageResetElapsed
|
|
88
|
+
)
|
|
89
|
+
return available;
|
|
90
|
+
const rejectedRequest = freshRequest && request.status === "rejected" && !planResetElapsed;
|
|
91
|
+
if (blocking.length === 0 && !rejectedRequest && restrictions.length === 0) return available;
|
|
92
|
+
// An extra-usage balance is a separate fallback. Its rejection does not block
|
|
93
|
+
// an available base plan or delay the next base-plan reset to a monthly date.
|
|
94
|
+
const resets = blocking.map((window) =>
|
|
95
|
+
window.resetsAt
|
|
96
|
+
? Date.parse(window.resetsAt)
|
|
97
|
+
: Date.parse(window.observedAt) + UNKNOWN_RESET_RECHECK_MS,
|
|
98
|
+
);
|
|
99
|
+
if (rejectedRequest)
|
|
100
|
+
resets.push(
|
|
101
|
+
request.resetsAt
|
|
102
|
+
? Date.parse(request.resetsAt)
|
|
103
|
+
: Date.parse(request.observedAt) + UNKNOWN_RESET_RECHECK_MS,
|
|
104
|
+
);
|
|
105
|
+
resets.push(
|
|
106
|
+
...restrictions.map((item) =>
|
|
107
|
+
item.resetsAt
|
|
108
|
+
? Date.parse(item.resetsAt)
|
|
109
|
+
: Date.parse(item.observedAt) + UNKNOWN_RESET_RECHECK_MS,
|
|
110
|
+
),
|
|
111
|
+
);
|
|
112
|
+
let nextCheckAt = Math.max(...resets);
|
|
113
|
+
if (
|
|
114
|
+
rejectedRequest &&
|
|
115
|
+
mayUseOverage &&
|
|
116
|
+
request.overageStatus === "rejected" &&
|
|
117
|
+
request.overageResetsAt
|
|
118
|
+
) {
|
|
119
|
+
const overageReset = Date.parse(request.overageResetsAt);
|
|
120
|
+
// A known reset permits a new authoritative probe, never invents a reading.
|
|
121
|
+
if (overageReset <= now.getTime()) return available;
|
|
122
|
+
nextCheckAt = Math.min(nextCheckAt, overageReset);
|
|
123
|
+
}
|
|
124
|
+
return {
|
|
125
|
+
available: false,
|
|
126
|
+
nextCheckAt: new Date(nextCheckAt),
|
|
127
|
+
blockingWindows: blocking.map((window) => window.id),
|
|
128
|
+
};
|
|
129
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
import { z } from "zod";
|
|
2
|
+
|
|
3
|
+
/** Claude Code 2.1.285's installed OAuth flow; model calls and profile reads only. */
|
|
4
|
+
export const CLAUDE_OAUTH_CLIENT_ID = "9d1c250a-e61b-44d9-88ed-5944d1962f5e";
|
|
5
|
+
export const CLAUDE_OAUTH_AUTHORIZE_URL = "https://claude.com/cai/oauth/authorize";
|
|
6
|
+
export const CLAUDE_OAUTH_TOKEN_URL = "https://platform.claude.com/v1/oauth/token";
|
|
7
|
+
export const CLAUDE_OAUTH_REDIRECT_URL = "https://platform.claude.com/oauth/code/callback";
|
|
8
|
+
export const CLAUDE_OAUTH_SCOPES = ["user:inference", "user:profile"] as const;
|
|
9
|
+
|
|
10
|
+
export const ClaudeOAuthTokenResponse = z
|
|
11
|
+
.object({
|
|
12
|
+
access_token: z
|
|
13
|
+
.string()
|
|
14
|
+
.max(16384)
|
|
15
|
+
.regex(/^sk-ant-oat[0-9]+-\S+$/),
|
|
16
|
+
refresh_token: z.string().min(1).max(16384).optional(),
|
|
17
|
+
expires_in: z.number().int().positive().max(31536000),
|
|
18
|
+
scope: z.string().min(1).max(8192),
|
|
19
|
+
})
|
|
20
|
+
.passthrough();
|
|
21
|
+
|
|
22
|
+
export function claudeAuthorizationUrl(input: { challenge: string; state: string }) {
|
|
23
|
+
const url = new URL(CLAUDE_OAUTH_AUTHORIZE_URL);
|
|
24
|
+
url.searchParams.set("code", "true");
|
|
25
|
+
url.searchParams.set("client_id", CLAUDE_OAUTH_CLIENT_ID);
|
|
26
|
+
url.searchParams.set("response_type", "code");
|
|
27
|
+
url.searchParams.set("redirect_uri", CLAUDE_OAUTH_REDIRECT_URL);
|
|
28
|
+
url.searchParams.set("scope", CLAUDE_OAUTH_SCOPES.join(" "));
|
|
29
|
+
url.searchParams.set("code_challenge", input.challenge);
|
|
30
|
+
url.searchParams.set("code_challenge_method", "S256");
|
|
31
|
+
url.searchParams.set("state", input.state);
|
|
32
|
+
return url.toString();
|
|
33
|
+
}
|
|
@@ -0,0 +1,328 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ClaudeUsageWindowId,
|
|
3
|
+
type ClaudeSubscriptionUsage,
|
|
4
|
+
type ClaudeUsageWindow,
|
|
5
|
+
type ClaudeUsageRequestStatus,
|
|
6
|
+
} from "@opengeni/contracts";
|
|
7
|
+
|
|
8
|
+
export type ClaudeUsageObservation = {
|
|
9
|
+
windows: ClaudeUsageWindow[];
|
|
10
|
+
observedAt: string;
|
|
11
|
+
source: "response_headers" | "provider";
|
|
12
|
+
requestStatus?: ClaudeUsageRequestStatus | null;
|
|
13
|
+
requestRestrictions?: ClaudeUsageRequestStatus[];
|
|
14
|
+
};
|
|
15
|
+
const prefixes: Record<string, string[]> = {
|
|
16
|
+
five_hour: ["5h"],
|
|
17
|
+
seven_day: ["7d"],
|
|
18
|
+
seven_day_opus: ["7d-opus"],
|
|
19
|
+
seven_day_sonnet: ["7d-sonnet"],
|
|
20
|
+
seven_day_overage_included: ["7d_oi", "7d-overage-included"],
|
|
21
|
+
overage: ["overage"],
|
|
22
|
+
};
|
|
23
|
+
function percent(value: unknown, scale: number): number | null {
|
|
24
|
+
if (typeof value !== "number" && (typeof value !== "string" || !value.trim())) return null;
|
|
25
|
+
const number = Number(value) * scale;
|
|
26
|
+
return Number.isFinite(number) && number >= 0 ? number : null;
|
|
27
|
+
}
|
|
28
|
+
function epoch(value: string | null): string | null {
|
|
29
|
+
if (!value || !/^\d+(?:\.\d+)?$/.test(value)) return null;
|
|
30
|
+
const time = Number(value) * 1000;
|
|
31
|
+
return Number.isFinite(time) && time > 0 && time < 8.64e15 ? new Date(time).toISOString() : null;
|
|
32
|
+
}
|
|
33
|
+
function status(value: unknown): ClaudeUsageWindow["status"] {
|
|
34
|
+
return value === "allowed" || value === "allowed_warning" || value === "rejected" ? value : null;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function latestReset(left: string | null, right: string | null, observedAt: string): string {
|
|
38
|
+
return new Date(
|
|
39
|
+
Math.max(
|
|
40
|
+
left ? Date.parse(left) : Date.parse(observedAt) + 60_000,
|
|
41
|
+
right ? Date.parse(right) : Date.parse(observedAt) + 60_000,
|
|
42
|
+
),
|
|
43
|
+
).toISOString();
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function evidenceKey(item: ClaudeUsageRequestStatus): string {
|
|
47
|
+
// A legacy Sonnet claim does not prove an account-wide restriction cleared.
|
|
48
|
+
return JSON.stringify([
|
|
49
|
+
item.upstreamModelId,
|
|
50
|
+
item.upstreamModelId ? null : item.representativeClaim,
|
|
51
|
+
item.source === "provider",
|
|
52
|
+
]);
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function tiedRequest(
|
|
56
|
+
left: ClaudeUsageRequestStatus,
|
|
57
|
+
right: ClaudeUsageRequestStatus,
|
|
58
|
+
): ClaudeUsageRequestStatus {
|
|
59
|
+
const denied = left.status === "rejected" ? left : right.status === "rejected" ? right : null;
|
|
60
|
+
return {
|
|
61
|
+
...(denied ?? left),
|
|
62
|
+
resetsAt: denied
|
|
63
|
+
? latestReset(
|
|
64
|
+
left.status === "rejected" ? left.resetsAt : denied.resetsAt,
|
|
65
|
+
right.status === "rejected" ? right.resetsAt : denied.resetsAt,
|
|
66
|
+
left.observedAt,
|
|
67
|
+
)
|
|
68
|
+
: null,
|
|
69
|
+
representativeClaim:
|
|
70
|
+
left.representativeClaim === right.representativeClaim ? left.representativeClaim : null,
|
|
71
|
+
status: denied ? "rejected" : null,
|
|
72
|
+
overageStatus: null,
|
|
73
|
+
overageResetsAt: null,
|
|
74
|
+
};
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function parseClaudeUsageHeaders(
|
|
78
|
+
headers: Headers,
|
|
79
|
+
now = new Date(),
|
|
80
|
+
upstreamModelId?: string,
|
|
81
|
+
): ClaudeUsageObservation | null {
|
|
82
|
+
const observedAt = now.toISOString();
|
|
83
|
+
const claim = ClaudeUsageWindowId.safeParse(
|
|
84
|
+
headers.get("anthropic-ratelimit-unified-representative-claim"),
|
|
85
|
+
);
|
|
86
|
+
const claimedStatus = status(headers.get("anthropic-ratelimit-unified-status"));
|
|
87
|
+
const claimedReset = epoch(headers.get("anthropic-ratelimit-unified-reset"));
|
|
88
|
+
const overageStatus = status(headers.get("anthropic-ratelimit-unified-overage-status"));
|
|
89
|
+
const overageResetsAt = epoch(headers.get("anthropic-ratelimit-unified-overage-reset"));
|
|
90
|
+
const windows = ClaudeUsageWindowId.options.flatMap((id) => {
|
|
91
|
+
const header = (suffix: string) =>
|
|
92
|
+
prefixes[id]!.map((prefix) =>
|
|
93
|
+
headers.get(`anthropic-ratelimit-unified-${prefix}-${suffix}`),
|
|
94
|
+
).find((value) => value !== null) ?? null;
|
|
95
|
+
const representative = claim.success && claim.data === id;
|
|
96
|
+
const usedPercent = percent(header("utilization"), 100);
|
|
97
|
+
const resetsAt = epoch(header("reset")) ?? (representative ? claimedReset : null);
|
|
98
|
+
const windowStatus = status(header("status")) ?? (representative ? claimedStatus : null);
|
|
99
|
+
if (usedPercent === null && resetsAt === null && windowStatus === null) return [];
|
|
100
|
+
return [{ id, usedPercent, resetsAt, status: windowStatus, observedAt }];
|
|
101
|
+
});
|
|
102
|
+
return windows.length || claimedStatus || overageStatus
|
|
103
|
+
? {
|
|
104
|
+
windows,
|
|
105
|
+
observedAt,
|
|
106
|
+
source: "response_headers",
|
|
107
|
+
requestStatus: {
|
|
108
|
+
status: claimedStatus,
|
|
109
|
+
resetsAt: claimedReset,
|
|
110
|
+
representativeClaim: claim.success ? claim.data : null,
|
|
111
|
+
overageStatus,
|
|
112
|
+
overageResetsAt,
|
|
113
|
+
upstreamModelId: upstreamModelId ?? null,
|
|
114
|
+
observedAt,
|
|
115
|
+
},
|
|
116
|
+
}
|
|
117
|
+
: null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
export function parseClaudeUsageResponse(
|
|
121
|
+
value: unknown,
|
|
122
|
+
now = new Date(),
|
|
123
|
+
): ClaudeUsageObservation | null {
|
|
124
|
+
if (!value || typeof value !== "object" || Array.isArray(value)) return null;
|
|
125
|
+
const observedAt = now.toISOString();
|
|
126
|
+
const windows = ClaudeUsageWindowId.options.flatMap((id) => {
|
|
127
|
+
const window = (value as Record<string, unknown>)[id];
|
|
128
|
+
if (!window || typeof window !== "object" || Array.isArray(window)) return [];
|
|
129
|
+
const fields = window as Record<string, unknown>;
|
|
130
|
+
const usedPercent = percent(fields.utilization, 1);
|
|
131
|
+
const time = typeof fields.resets_at === "string" ? Date.parse(fields.resets_at) : NaN;
|
|
132
|
+
const resetsAt = Number.isFinite(time) ? new Date(time).toISOString() : null;
|
|
133
|
+
if (usedPercent === null && resetsAt === null) return [];
|
|
134
|
+
return [{ id, usedPercent, resetsAt, status: null, observedAt }];
|
|
135
|
+
});
|
|
136
|
+
return windows.length ? { windows, observedAt, source: "provider" } : null;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
export function emptyClaudeUsage(credentialVersion: number | null): ClaudeSubscriptionUsage {
|
|
140
|
+
return {
|
|
141
|
+
connected: credentialVersion !== null,
|
|
142
|
+
credentialVersion,
|
|
143
|
+
windows: [],
|
|
144
|
+
observedAt: null,
|
|
145
|
+
source: null,
|
|
146
|
+
refreshStatus: "not_checked",
|
|
147
|
+
refreshCheckedAt: null,
|
|
148
|
+
};
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
/** Preserve omitted windows and reject observations older than their individual window. */
|
|
152
|
+
export function mergeClaudeUsage(
|
|
153
|
+
current: ClaudeSubscriptionUsage,
|
|
154
|
+
observation: ClaudeUsageObservation,
|
|
155
|
+
): ClaudeSubscriptionUsage {
|
|
156
|
+
const windows = new Map(current.windows.map((window) => [window.id, window]));
|
|
157
|
+
for (const incomingWindow of observation.windows) {
|
|
158
|
+
const window = { ...incomingWindow, source: incomingWindow.source ?? observation.source };
|
|
159
|
+
const previous = windows.get(window.id);
|
|
160
|
+
if (!previous || previous.observedAt < window.observedAt) windows.set(window.id, window);
|
|
161
|
+
else if (
|
|
162
|
+
previous.observedAt === window.observedAt &&
|
|
163
|
+
JSON.stringify(previous) !== JSON.stringify(window)
|
|
164
|
+
) {
|
|
165
|
+
const rejected = previous.status === "rejected" || window.status === "rejected";
|
|
166
|
+
const full = (previous.usedPercent ?? 0) >= 100 || (window.usedPercent ?? 0) >= 100;
|
|
167
|
+
windows.set(window.id, {
|
|
168
|
+
...previous,
|
|
169
|
+
usedPercent:
|
|
170
|
+
previous.usedPercent === null
|
|
171
|
+
? window.usedPercent
|
|
172
|
+
: window.usedPercent === null
|
|
173
|
+
? previous.usedPercent
|
|
174
|
+
: Math.max(previous.usedPercent, window.usedPercent),
|
|
175
|
+
status: rejected ? "rejected" : previous.status === window.status ? previous.status : null,
|
|
176
|
+
resetsAt:
|
|
177
|
+
rejected || full
|
|
178
|
+
? latestReset(previous.resetsAt, window.resetsAt, window.observedAt)
|
|
179
|
+
: previous.resetsAt === window.resetsAt
|
|
180
|
+
? previous.resetsAt
|
|
181
|
+
: null,
|
|
182
|
+
source:
|
|
183
|
+
previous.source === "response_headers" || window.source === "response_headers"
|
|
184
|
+
? "response_headers"
|
|
185
|
+
: "provider",
|
|
186
|
+
});
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
const incoming = observation.requestStatus;
|
|
190
|
+
const restrictions = new Map(
|
|
191
|
+
(current.requestRestrictions ?? []).map((item) => [evidenceKey(item), item]),
|
|
192
|
+
);
|
|
193
|
+
// Legacy snapshots also contribute their denial; a different model's success
|
|
194
|
+
// must not erase a restriction with an unknown representative claim.
|
|
195
|
+
for (const item of [
|
|
196
|
+
current.requestStatus?.status ? current.requestStatus : null,
|
|
197
|
+
...(observation.requestRestrictions ?? []),
|
|
198
|
+
incoming?.status ? incoming : null,
|
|
199
|
+
]) {
|
|
200
|
+
if (!item) continue;
|
|
201
|
+
const key = evidenceKey(item);
|
|
202
|
+
const previous = restrictions.get(key);
|
|
203
|
+
const sanitized = {
|
|
204
|
+
...item,
|
|
205
|
+
overageStatus: null,
|
|
206
|
+
overageResetsAt: null,
|
|
207
|
+
};
|
|
208
|
+
if (!previous || item.observedAt > previous.observedAt) restrictions.set(key, sanitized);
|
|
209
|
+
else if (
|
|
210
|
+
item.observedAt === previous.observedAt &&
|
|
211
|
+
JSON.stringify(previous) !== JSON.stringify(sanitized)
|
|
212
|
+
)
|
|
213
|
+
restrictions.set(key, tiedRequest(previous, sanitized));
|
|
214
|
+
}
|
|
215
|
+
// Direct refreshes can precede late turn finalizers. Retain each direct
|
|
216
|
+
// window's watermark even when no model restriction is present yet.
|
|
217
|
+
const directWindows = [
|
|
218
|
+
...current.windows.filter(
|
|
219
|
+
(window) =>
|
|
220
|
+
window.source === "provider" ||
|
|
221
|
+
(!window.source &&
|
|
222
|
+
current.source === "provider" &&
|
|
223
|
+
current.observedAt === window.observedAt),
|
|
224
|
+
),
|
|
225
|
+
...observation.windows.filter((window) => (window.source ?? observation.source) === "provider"),
|
|
226
|
+
];
|
|
227
|
+
for (const window of directWindows) {
|
|
228
|
+
if (window.usedPercent === null || window.usedPercent >= 100) continue;
|
|
229
|
+
const proof: ClaudeUsageRequestStatus = {
|
|
230
|
+
status: null,
|
|
231
|
+
resetsAt: null,
|
|
232
|
+
representativeClaim: window.id,
|
|
233
|
+
upstreamModelId: null,
|
|
234
|
+
overageStatus: null,
|
|
235
|
+
overageResetsAt: null,
|
|
236
|
+
observedAt: window.observedAt,
|
|
237
|
+
source: "provider",
|
|
238
|
+
};
|
|
239
|
+
const key = evidenceKey(proof);
|
|
240
|
+
if (!restrictions.has(key) || restrictions.get(key)!.observedAt < proof.observedAt)
|
|
241
|
+
restrictions.set(key, proof);
|
|
242
|
+
}
|
|
243
|
+
for (const [key, item] of restrictions) {
|
|
244
|
+
if (item.status !== "rejected") continue;
|
|
245
|
+
const proof = [...restrictions.values()].find(
|
|
246
|
+
(candidate) =>
|
|
247
|
+
candidate.source === "provider" &&
|
|
248
|
+
candidate.representativeClaim === item.representativeClaim &&
|
|
249
|
+
candidate.observedAt > item.observedAt &&
|
|
250
|
+
candidate.representativeClaim !== "overage" &&
|
|
251
|
+
candidate.representativeClaim !== "seven_day_overage_included",
|
|
252
|
+
);
|
|
253
|
+
if (proof)
|
|
254
|
+
restrictions.set(key, {
|
|
255
|
+
...item,
|
|
256
|
+
status: null,
|
|
257
|
+
resetsAt: null,
|
|
258
|
+
observedAt: proof.observedAt,
|
|
259
|
+
});
|
|
260
|
+
}
|
|
261
|
+
// Bound persisted state without dropping denials: overflow collapses to a
|
|
262
|
+
// conservative account-wide restriction until the latest known reset.
|
|
263
|
+
let requestRestrictions = [...restrictions.values()];
|
|
264
|
+
const evidenceTime = requestRestrictions.reduce(
|
|
265
|
+
(value, item) => (item.observedAt > value ? item.observedAt : value),
|
|
266
|
+
observation.observedAt,
|
|
267
|
+
);
|
|
268
|
+
const liveDenials = requestRestrictions.filter(
|
|
269
|
+
(item) =>
|
|
270
|
+
item.status === "rejected" &&
|
|
271
|
+
(item.resetsAt ? Date.parse(item.resetsAt) : Date.parse(item.observedAt) + 60_000) >
|
|
272
|
+
Date.parse(evidenceTime),
|
|
273
|
+
);
|
|
274
|
+
if (requestRestrictions.length > 64 && liveDenials.length === 0) {
|
|
275
|
+
requestRestrictions = requestRestrictions
|
|
276
|
+
.sort((left, right) => right.observedAt.localeCompare(left.observedAt))
|
|
277
|
+
.slice(0, 64);
|
|
278
|
+
} else if (requestRestrictions.length > 64) {
|
|
279
|
+
const observedAt = evidenceTime;
|
|
280
|
+
const resetsAt = new Date(
|
|
281
|
+
Math.max(
|
|
282
|
+
...liveDenials.map((item) =>
|
|
283
|
+
item.resetsAt ? Date.parse(item.resetsAt) : Date.parse(item.observedAt) + 60_000,
|
|
284
|
+
),
|
|
285
|
+
Date.parse(observedAt) + 60_000,
|
|
286
|
+
),
|
|
287
|
+
).toISOString();
|
|
288
|
+
requestRestrictions = [
|
|
289
|
+
{
|
|
290
|
+
status: "rejected",
|
|
291
|
+
resetsAt,
|
|
292
|
+
representativeClaim: null,
|
|
293
|
+
overageStatus: null,
|
|
294
|
+
overageResetsAt: null,
|
|
295
|
+
upstreamModelId: null,
|
|
296
|
+
observedAt,
|
|
297
|
+
},
|
|
298
|
+
];
|
|
299
|
+
}
|
|
300
|
+
const newest = !current.observedAt || current.observedAt < observation.observedAt;
|
|
301
|
+
const tied = current.observedAt === observation.observedAt;
|
|
302
|
+
let requestStatus = current.requestStatus ?? null;
|
|
303
|
+
if (newest) requestStatus = incoming ?? null;
|
|
304
|
+
else if (tied && JSON.stringify(requestStatus) !== JSON.stringify(incoming ?? null)) {
|
|
305
|
+
// Millisecond timestamps do not order concurrent responses. Never restore
|
|
306
|
+
// paid authority or erase a denial on an ambiguous tie.
|
|
307
|
+
requestStatus =
|
|
308
|
+
incoming && requestStatus && evidenceKey(incoming) === evidenceKey(requestStatus)
|
|
309
|
+
? tiedRequest(requestStatus, incoming)
|
|
310
|
+
: null;
|
|
311
|
+
}
|
|
312
|
+
return {
|
|
313
|
+
...current,
|
|
314
|
+
requestRestrictions,
|
|
315
|
+
requestStatus,
|
|
316
|
+
windows: ClaudeUsageWindowId.options.flatMap((id) =>
|
|
317
|
+
windows.has(id) ? [windows.get(id)!] : [],
|
|
318
|
+
),
|
|
319
|
+
...(newest
|
|
320
|
+
? {
|
|
321
|
+
observedAt: observation.observedAt,
|
|
322
|
+
source: observation.source,
|
|
323
|
+
// A newer direct or partial observation cannot retain an older paid
|
|
324
|
+
// fallback authorization. Window readings remain independently merged.
|
|
325
|
+
}
|
|
326
|
+
: {}),
|
|
327
|
+
};
|
|
328
|
+
}
|
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { PromotionalCreditScope } from "@opengeni/contracts";
|
|
2
|
+
import { z } from "zod";
|
|
3
|
+
|
|
4
|
+
const ModelIds = PromotionalCreditScope.shape.eligibleModelIds.transform((ids) => [
|
|
5
|
+
...new Set(ids),
|
|
6
|
+
]);
|
|
7
|
+
|
|
8
|
+
/** Operator configuration only. Keys are Stripe coupon IDs, never customer account IDs. */
|
|
9
|
+
export const CreditPromotionPolicy = z
|
|
10
|
+
.object({
|
|
11
|
+
defaultModelIds: ModelIds.optional(),
|
|
12
|
+
signupModelIds: ModelIds.optional(),
|
|
13
|
+
offers: z
|
|
14
|
+
.record(
|
|
15
|
+
z.string().min(1),
|
|
16
|
+
z
|
|
17
|
+
.object({
|
|
18
|
+
label: PromotionalCreditScope.shape.label,
|
|
19
|
+
eligibleModelIds: ModelIds.optional(),
|
|
20
|
+
})
|
|
21
|
+
.strict(),
|
|
22
|
+
)
|
|
23
|
+
.default({}),
|
|
24
|
+
})
|
|
25
|
+
.strict()
|
|
26
|
+
.superRefine((policy, ctx) => {
|
|
27
|
+
for (const [id, offer] of Object.entries(policy.offers)) {
|
|
28
|
+
if (!offer.eligibleModelIds && !policy.defaultModelIds) {
|
|
29
|
+
ctx.addIssue({
|
|
30
|
+
code: "custom",
|
|
31
|
+
path: ["offers", id],
|
|
32
|
+
message: "Offer requires eligibleModelIds or defaultModelIds",
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
});
|
|
37
|
+
|
|
38
|
+
export const EnvCreditPromotionPolicy = z.preprocess(
|
|
39
|
+
(value) => {
|
|
40
|
+
if (typeof value !== "string") return value;
|
|
41
|
+
try {
|
|
42
|
+
return JSON.parse(value);
|
|
43
|
+
} catch {
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
CreditPromotionPolicy.default({ offers: {} }),
|
|
48
|
+
);
|
|
49
|
+
|
|
50
|
+
export function signupCreditModelIds(settings: {
|
|
51
|
+
creditPromotionPolicy: z.infer<typeof CreditPromotionPolicy>;
|
|
52
|
+
}) {
|
|
53
|
+
return (
|
|
54
|
+
settings.creditPromotionPolicy.signupModelIds ?? settings.creditPromotionPolicy.defaultModelIds
|
|
55
|
+
);
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
export function promotionalCreditScope(
|
|
59
|
+
settings: { creditPromotionPolicy: z.infer<typeof CreditPromotionPolicy> },
|
|
60
|
+
couponId: string,
|
|
61
|
+
): PromotionalCreditScope | undefined {
|
|
62
|
+
const policy = settings.creditPromotionPolicy;
|
|
63
|
+
const offer = policy.offers[couponId];
|
|
64
|
+
const eligibleModelIds = offer?.eligibleModelIds ?? policy.defaultModelIds;
|
|
65
|
+
return eligibleModelIds
|
|
66
|
+
? { label: offer?.label ?? "Promotional credits", eligibleModelIds }
|
|
67
|
+
: undefined;
|
|
68
|
+
}
|