@mupt-ai/dari-gateway 1.0.353 → 1.0.355
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/README.md +5 -5
- package/dist/link/assets.js +0 -3
- package/dist/link/client.d.ts +2 -2
- package/dist/link/client.js +2 -2
- package/dist/link/endpoints.js +31 -8
- package/dist/link/errors.js +0 -1
- package/dist/link/self_hosted.js +11 -3
- package/dist/link/service.d.ts +3 -1
- package/dist/link/service.js +1 -0
- package/dist/models/catalog.js +0 -1
- package/dist/models/provider_defaults.js +0 -5
- package/dist/models/provider_models.json +0 -182
- package/dist/models/subscriptions.js +0 -1
- package/dist/platform/platform.d.ts +11 -0
- package/dist/providers/codex_usage.d.ts +6 -0
- package/dist/providers/codex_usage.js +2 -1
- package/dist/providers/execution.js +0 -3
- package/dist/providers/provider_call.js +1 -5
- package/dist/providers/subscription_limits.d.ts +1 -1
- package/dist/providers/subscription_limits.js +1 -4
- package/dist/providers/subscription_resets.d.ts +53 -0
- package/dist/providers/subscription_resets.js +184 -0
- package/dist/self_host/connected.d.ts +51 -0
- package/dist/self_host/connected.js +197 -0
- package/dist/self_host/hosted_sync.d.ts +53 -0
- package/dist/self_host/hosted_sync.js +261 -0
- package/dist/self_host/main.d.ts +5 -0
- package/dist/self_host/main.js +58 -10
- package/dist/self_host/platform.js +15 -2
- package/dist/self_host/resolve.js +0 -1
- package/dist/self_host/subscriptions/http.d.ts +4 -1
- package/dist/self_host/subscriptions/http.js +83 -11
- package/dist/self_host/subscriptions/index.d.ts +3 -3
- package/dist/self_host/subscriptions/index.js +3 -3
- package/dist/self_host/subscriptions/oauth.d.ts +3 -4
- package/dist/self_host/subscriptions/oauth.js +9 -76
- package/dist/self_host/subscriptions/resets.d.ts +41 -0
- package/dist/self_host/subscriptions/resets.js +235 -0
- package/dist/self_host/subscriptions/store.d.ts +61 -8
- package/dist/self_host/subscriptions/store.js +151 -26
- package/dist/self_host/subscriptions/usage.d.ts +3 -1
- package/dist/self_host/subscriptions/usage.js +12 -7
- package/dist/types.d.ts +1 -1
- package/package.json +2 -2
- package/src/link/assets.ts +0 -3
- package/src/link/client.ts +5 -3
- package/src/link/endpoints.ts +35 -7
- package/src/link/errors.ts +0 -1
- package/src/link/self_hosted.ts +9 -3
- package/src/link/service.ts +4 -0
- package/src/models/catalog.ts +0 -1
- package/src/models/provider_defaults.ts +0 -5
- package/src/models/provider_models.json +0 -182
- package/src/models/subscriptions.ts +0 -1
- package/src/platform/platform.ts +9 -0
- package/src/providers/codex_usage.ts +2 -1
- package/src/providers/execution.ts +0 -3
- package/src/providers/provider_call.ts +1 -5
- package/src/providers/subscription_limits.ts +1 -3
- package/src/providers/subscription_resets.ts +256 -0
- package/src/self_host/connected.ts +239 -0
- package/src/self_host/hosted_sync.ts +285 -0
- package/src/self_host/main.ts +55 -9
- package/src/self_host/platform.ts +13 -1
- package/src/self_host/resolve.ts +0 -1
- package/src/self_host/subscriptions/http.ts +85 -10
- package/src/self_host/subscriptions/index.ts +5 -2
- package/src/self_host/subscriptions/oauth.ts +8 -91
- package/src/self_host/subscriptions/resets.ts +254 -0
- package/src/self_host/subscriptions/store.ts +185 -27
- package/src/self_host/subscriptions/usage.ts +13 -7
- package/src/types.ts +0 -3
- package/dist/providers/github_copilot.d.ts +0 -8
- package/dist/providers/github_copilot.js +0 -21
- package/src/providers/github_copilot.ts +0 -24
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* Personal subscriptions for a self-hosted, single-tenant gateway: Claude Code,
|
|
3
|
-
* ChatGPT, Muse Code, OpenCode Go,
|
|
3
|
+
* ChatGPT, Muse Code, OpenCode Go, and Grok plans
|
|
4
4
|
* connected over OAuth, and Vercel Token Pass keys, used in place of API keys.
|
|
5
5
|
*
|
|
6
6
|
* - `oauth.ts`: the providers' OAuth protocols (Claude Code PKCE with a
|
|
@@ -26,5 +26,5 @@
|
|
|
26
26
|
*/
|
|
27
27
|
export { freshAccessToken } from "./access.js";
|
|
28
28
|
export { handleSubscriptionRequest } from "./http.js";
|
|
29
|
-
export { CODEX_APPROVAL_PENDING,
|
|
30
|
-
export { SubscriptionStore, activeModelHolds, currentUsage, isHeld, } from "./store.js";
|
|
29
|
+
export { CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, XAI_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, parseAuthorizationResponse, refreshOAuth, startOAuth, } from "./oauth.js";
|
|
30
|
+
export { SubscriptionAccountConnectedError, SubscriptionStore, activeModelHolds, currentUsage, isHeld, sameConnectedAccount, } from "./store.js";
|
|
@@ -4,12 +4,12 @@
|
|
|
4
4
|
* the gateway polls for approval), Muse Code (Meta's device code, then the
|
|
5
5
|
* subscription's Model API key minted from the sign-in token), OpenCode Go
|
|
6
6
|
* (the OpenCode Console device sign-in `opencode auth login` runs, scoped to
|
|
7
|
-
* the workspace that holds the plan),
|
|
8
|
-
*
|
|
7
|
+
* the workspace that holds the plan), Grok (xAI's device sign-in, as its
|
|
8
|
+
* own coding agent runs it), and Vercel
|
|
9
9
|
* Token Pass (no protocol: the plan is a Token Pass key the user pastes).
|
|
10
10
|
* Every network call goes through the injected `fetch`.
|
|
11
11
|
*/
|
|
12
|
-
export type SubscriptionProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse" | "opencode_go" | "
|
|
12
|
+
export type SubscriptionProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse" | "opencode_go" | "xai_grok" | "vercel_token_pass";
|
|
13
13
|
export declare const SUBSCRIPTION_PROVIDERS: readonly SubscriptionProvider[];
|
|
14
14
|
export declare const OPENCODE_CLIENT_ID = "opencode-cli";
|
|
15
15
|
export declare const OPENCODE_APPROVAL_PENDING = "OpenCode approval is still pending. Enter the code in the OpenCode console, finish approval, then try again.";
|
|
@@ -47,7 +47,6 @@ export declare const CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
|
47
47
|
export declare const CODEX_APPROVAL_PENDING = "OpenAI approval is still pending. Enter the code at OpenAI, finish approval, then try again.";
|
|
48
48
|
export declare const MUSE_CODE_CLIENT_ID = "1031625952748946";
|
|
49
49
|
export declare const META_APPROVAL_PENDING = "Meta approval is still pending. Enter the code at Meta, finish approval, then try again.";
|
|
50
|
-
export declare const GITHUB_APPROVAL_PENDING: string;
|
|
51
50
|
export declare const XAI_APPROVAL_PENDING: string;
|
|
52
51
|
export declare function startOAuth(provider: SubscriptionProvider, options: OAuthOptions): Promise<OAuthAuthorization>;
|
|
53
52
|
/**
|
|
@@ -1,11 +1,9 @@
|
|
|
1
1
|
import { createHash, randomBytes } from "node:crypto";
|
|
2
|
-
import { COPILOT_HEADERS } from "../../providers/github_copilot.js";
|
|
3
2
|
export const SUBSCRIPTION_PROVIDERS = [
|
|
4
3
|
"anthropic_claude_code",
|
|
5
4
|
"openai_codex",
|
|
6
5
|
"meta_muse",
|
|
7
6
|
"opencode_go",
|
|
8
|
-
"github_copilot",
|
|
9
7
|
"xai_grok",
|
|
10
8
|
"vercel_token_pass",
|
|
11
9
|
];
|
|
@@ -63,25 +61,9 @@ const MUSE_KEY_LIFETIME_MS = 12 * 60 * 60_000;
|
|
|
63
61
|
// token before each mint. Without it the stored value is the sign-in token.
|
|
64
62
|
const MUSE_SIGN_IN_REFRESH_PREFIX = "refresh:";
|
|
65
63
|
export const META_APPROVAL_PENDING = "Meta approval is still pending. Enter the code at Meta, finish approval, then try again.";
|
|
66
|
-
// GitHub Copilot's sign-in, as VS Code's Copilot Chat runs it, for github.com
|
|
67
|
-
// accounts. The GitHub token it grants is the refresh token: it mints the
|
|
68
|
-
// short-lived Copilot token that serves requests.
|
|
69
|
-
const GITHUB_COPILOT_CLIENT_ID = "Iv1.b507a08c87ecfe98";
|
|
70
|
-
const COPILOT_TOKEN_URL = "https://api.github.com/copilot_internal/v2/token";
|
|
71
|
-
const GITHUB_USER_URL = "https://api.github.com/user";
|
|
72
|
-
// Copilot tokens live about half an hour; mint the next one before then.
|
|
73
|
-
const COPILOT_TOKEN_SKEW_MS = 5 * 60_000;
|
|
74
64
|
// SuperGrok and X Premium sign in as xAI's Grok CLI does.
|
|
75
65
|
const XAI_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
|
|
76
66
|
const DEVICE_SIGN_INS = {
|
|
77
|
-
github_copilot: {
|
|
78
|
-
vendor: "GitHub",
|
|
79
|
-
clientId: GITHUB_COPILOT_CLIENT_ID,
|
|
80
|
-
deviceCodeUrl: "https://github.com/login/device/code",
|
|
81
|
-
tokenUrl: "https://github.com/login/oauth/access_token",
|
|
82
|
-
scope: "read:user",
|
|
83
|
-
headers: { "User-Agent": COPILOT_HEADERS["User-Agent"] },
|
|
84
|
-
},
|
|
85
67
|
xai_grok: {
|
|
86
68
|
vendor: "xAI",
|
|
87
69
|
clientId: XAI_CLIENT_ID,
|
|
@@ -93,7 +75,6 @@ const DEVICE_SIGN_INS = {
|
|
|
93
75
|
function isDeviceProvider(provider) {
|
|
94
76
|
return provider in DEVICE_SIGN_INS;
|
|
95
77
|
}
|
|
96
|
-
export const GITHUB_APPROVAL_PENDING = approvalPending("GitHub");
|
|
97
78
|
export const XAI_APPROVAL_PENDING = approvalPending("xAI");
|
|
98
79
|
function approvalPending(vendor) {
|
|
99
80
|
return `${vendor} approval is still pending. Enter the code at ${vendor}, finish approval, then try again.`;
|
|
@@ -112,7 +93,7 @@ export async function startOAuth(provider, options) {
|
|
|
112
93
|
}
|
|
113
94
|
if (isDeviceProvider(provider)) {
|
|
114
95
|
const signIn = DEVICE_SIGN_INS[provider];
|
|
115
|
-
const device = await postForm(options.fetch, signIn.deviceCodeUrl, { client_id: signIn.clientId, ...(signIn.scope === undefined ? {} : { scope: signIn.scope }) }, `${signIn.vendor} device code request
|
|
96
|
+
const device = await postForm(options.fetch, signIn.deviceCodeUrl, { client_id: signIn.clientId, ...(signIn.scope === undefined ? {} : { scope: signIn.scope }) }, `${signIn.vendor} device code request`);
|
|
116
97
|
const complete = device.verification_uri_complete;
|
|
117
98
|
return {
|
|
118
99
|
authorizationUrl: typeof complete === "string" && complete.startsWith("https://")
|
|
@@ -186,17 +167,6 @@ export async function completeOAuth(provider, flow, authorizationResponse, optio
|
|
|
186
167
|
return vercelTokenPassTokens(authorizationResponse, now);
|
|
187
168
|
if (isDeviceProvider(provider)) {
|
|
188
169
|
const token = await deviceApproval(provider, requiredString(flow, "device_code"), options.fetch);
|
|
189
|
-
if (provider === "github_copilot") {
|
|
190
|
-
const githubToken = requiredString(token, "access_token");
|
|
191
|
-
const tokens = await copilotTokens(githubToken, options.fetch, now).catch((error) => {
|
|
192
|
-
// GitHub mints no Copilot token for an account without a plan.
|
|
193
|
-
if (error instanceof SubscriptionOAuthProviderError && [401, 403, 404].includes(error.status ?? 0)) {
|
|
194
|
-
throw new SubscriptionOAuthInputError("This GitHub account has no active Copilot plan. Subscribe at https://github.com/features/copilot/plans, then connect again.");
|
|
195
|
-
}
|
|
196
|
-
throw error;
|
|
197
|
-
});
|
|
198
|
-
return { ...tokens, accountEmail: await githubAccount(options.fetch, githubToken) };
|
|
199
|
-
}
|
|
200
170
|
return deviceTokens(provider, token, now, null);
|
|
201
171
|
}
|
|
202
172
|
if (provider === "opencode_go") {
|
|
@@ -296,11 +266,9 @@ export async function refreshOAuth(credential, options) {
|
|
|
296
266
|
const now = options.now ?? new Date();
|
|
297
267
|
if (credential.provider === "vercel_token_pass")
|
|
298
268
|
return vercelTokenPassTokens(credential.refreshToken, now);
|
|
299
|
-
if (credential.provider === "github_copilot")
|
|
300
|
-
return await copilotTokens(credential.refreshToken, options.fetch, now);
|
|
301
269
|
if (isDeviceProvider(credential.provider)) {
|
|
302
270
|
const signIn = DEVICE_SIGN_INS[credential.provider];
|
|
303
|
-
const token = await postForm(options.fetch, signIn.tokenUrl, { grant_type: "refresh_token", client_id: signIn.clientId, refresh_token: credential.refreshToken }, `${signIn.vendor} sign-in refresh
|
|
271
|
+
const token = await postForm(options.fetch, signIn.tokenUrl, { grant_type: "refresh_token", client_id: signIn.clientId, refresh_token: credential.refreshToken }, `${signIn.vendor} sign-in refresh`);
|
|
304
272
|
return deviceTokens(credential.provider, token, now, credential.refreshToken);
|
|
305
273
|
}
|
|
306
274
|
if (credential.provider === "opencode_go") {
|
|
@@ -464,22 +432,21 @@ function jwtPayload(token) {
|
|
|
464
432
|
function postJson(fetch, url, payload, operation) {
|
|
465
433
|
return requestJson(fetch, url, JSON.stringify(payload), "application/json", operation);
|
|
466
434
|
}
|
|
467
|
-
function postForm(fetch, url, payload, operation
|
|
468
|
-
return requestJson(fetch, url, new URLSearchParams(payload).toString(), "application/x-www-form-urlencoded", operation
|
|
435
|
+
function postForm(fetch, url, payload, operation) {
|
|
436
|
+
return requestJson(fetch, url, new URLSearchParams(payload).toString(), "application/x-www-form-urlencoded", operation);
|
|
469
437
|
}
|
|
470
|
-
// A null body is a GET.
|
|
471
438
|
async function requestJson(fetch, url, body, contentType, operation, headers = {}) {
|
|
472
439
|
let response;
|
|
473
440
|
try {
|
|
474
441
|
response = await fetch(url, {
|
|
475
|
-
method:
|
|
442
|
+
method: "POST",
|
|
476
443
|
headers: {
|
|
477
444
|
Accept: "application/json",
|
|
478
|
-
|
|
445
|
+
"Content-Type": contentType,
|
|
479
446
|
"User-Agent": "Dari/1.0",
|
|
480
447
|
...headers,
|
|
481
448
|
},
|
|
482
|
-
|
|
449
|
+
body,
|
|
483
450
|
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
484
451
|
});
|
|
485
452
|
}
|
|
@@ -543,8 +510,7 @@ async function opencodeEmail(fetch, accessToken) {
|
|
|
543
510
|
return null;
|
|
544
511
|
}
|
|
545
512
|
}
|
|
546
|
-
// Ask a device sign-in whether the user approved its code.
|
|
547
|
-
// unfinished sign-in with HTTP 200 and an `error`; the others with HTTP 400.
|
|
513
|
+
// Ask a device sign-in whether the user approved its code.
|
|
548
514
|
async function deviceApproval(provider, deviceCode, fetch) {
|
|
549
515
|
const signIn = DEVICE_SIGN_INS[provider];
|
|
550
516
|
let token;
|
|
@@ -554,7 +520,7 @@ async function deviceApproval(provider, deviceCode, fetch) {
|
|
|
554
520
|
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
555
521
|
device_code: deviceCode,
|
|
556
522
|
client_id: signIn.clientId,
|
|
557
|
-
}, `${signIn.vendor} device approval check
|
|
523
|
+
}, `${signIn.vendor} device approval check`);
|
|
558
524
|
errorCode = typeof token.error === "string" ? token.error : undefined;
|
|
559
525
|
}
|
|
560
526
|
catch (error) {
|
|
@@ -591,39 +557,6 @@ function deviceTokens(provider, payload, now, fallbackRefreshToken) {
|
|
|
591
557
|
accountEmail: typeof email === "string" && email ? email : null,
|
|
592
558
|
};
|
|
593
559
|
}
|
|
594
|
-
// Mints the Copilot token that serves requests from the GitHub token.
|
|
595
|
-
async function copilotTokens(githubToken, fetch, now) {
|
|
596
|
-
const minted = await requestJson(fetch, COPILOT_TOKEN_URL, null, "", "GitHub Copilot token request", { ...COPILOT_HEADERS, Authorization: `Bearer ${githubToken}` });
|
|
597
|
-
const expiresAt = minted.expires_at;
|
|
598
|
-
if (typeof expiresAt !== "number" || !Number.isFinite(expiresAt)) {
|
|
599
|
-
throw new SubscriptionOAuthProviderError(INCOMPLETE);
|
|
600
|
-
}
|
|
601
|
-
return {
|
|
602
|
-
provider: "github_copilot",
|
|
603
|
-
accessToken: requiredString(minted, "token"),
|
|
604
|
-
refreshToken: githubToken,
|
|
605
|
-
expiresAt: new Date(Math.max(now.getTime(), expiresAt * 1000 - COPILOT_TOKEN_SKEW_MS)),
|
|
606
|
-
accountId: null,
|
|
607
|
-
accountEmail: null,
|
|
608
|
-
};
|
|
609
|
-
}
|
|
610
|
-
// The signed-in GitHub account's email, else its login; best effort.
|
|
611
|
-
async function githubAccount(fetch, githubToken) {
|
|
612
|
-
try {
|
|
613
|
-
const user = await requestJson(fetch, GITHUB_USER_URL, null, "", "GitHub account lookup", {
|
|
614
|
-
Authorization: `Bearer ${githubToken}`,
|
|
615
|
-
});
|
|
616
|
-
for (const field of ["email", "login"]) {
|
|
617
|
-
const value = user[field];
|
|
618
|
-
if (typeof value === "string" && value)
|
|
619
|
-
return value;
|
|
620
|
-
}
|
|
621
|
-
return null;
|
|
622
|
-
}
|
|
623
|
-
catch {
|
|
624
|
-
return null;
|
|
625
|
-
}
|
|
626
|
-
}
|
|
627
560
|
// The pasted key is both tokens; refreshing hands the same key back.
|
|
628
561
|
function vercelTokenPassTokens(key, now) {
|
|
629
562
|
const apiKey = key.trim();
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { type BankedReset } from "../../providers/subscription_resets.js";
|
|
2
|
+
import type { OAuthFetch } from "./oauth.js";
|
|
3
|
+
import { type SubscriptionCredential, type SubscriptionStore } from "./store.js";
|
|
4
|
+
/**
|
|
5
|
+
* Banked limit resets of the gateway owner's ChatGPT and Claude Code plans, as
|
|
6
|
+
* hosted Dari spends them (dari-routing-backend subscription_recovery.ts and
|
|
7
|
+
* the control plane's subscription_resets.py): listed and spent on request,
|
|
8
|
+
* and, for a plan whose owner turned it on, spent once every plan of its
|
|
9
|
+
* provider is held.
|
|
10
|
+
*/
|
|
11
|
+
/** Where the gateway reaches Claude and ChatGPT: the config's endpoints, or the providers'. */
|
|
12
|
+
export type ProviderBaseUrls = {
|
|
13
|
+
claude?: string;
|
|
14
|
+
codex?: string;
|
|
15
|
+
};
|
|
16
|
+
export declare function providerBaseUrls(providers: Record<string, {
|
|
17
|
+
baseUrl: string;
|
|
18
|
+
}>): ProviderBaseUrls;
|
|
19
|
+
export type ResetDeps = {
|
|
20
|
+
store: SubscriptionStore;
|
|
21
|
+
fetch: OAuthFetch;
|
|
22
|
+
baseUrls?: ProviderBaseUrls;
|
|
23
|
+
now?: Date;
|
|
24
|
+
};
|
|
25
|
+
export declare function hasBankedResets(credential: SubscriptionCredential): boolean;
|
|
26
|
+
/** The plan's banked resets, the soonest to expire first. */
|
|
27
|
+
export declare function listResets(deps: ResetDeps, credential: SubscriptionCredential): Promise<BankedReset[]>;
|
|
28
|
+
/**
|
|
29
|
+
* Spend one reset now: the provider's answer, "reset" when it restored the
|
|
30
|
+
* plan, which is then released. Checked against a fresh list first: one spent
|
|
31
|
+
* or gone answers "unavailable", one not usable yet "not_usable".
|
|
32
|
+
*/
|
|
33
|
+
export declare function useReset(deps: ResetDeps, credential: SubscriptionCredential, resetId: string): Promise<string>;
|
|
34
|
+
/**
|
|
35
|
+
* After a usage-limit hold on one of the owner's plans: correct a ChatGPT
|
|
36
|
+
* plan's hold from Codex's report, and once every plan of the provider is
|
|
37
|
+
* held, release one the provider already serves again or spend one banked
|
|
38
|
+
* reset on the plan that would stay out longest, among those with
|
|
39
|
+
* auto-reset on. Returns whether a plan of the provider serves now.
|
|
40
|
+
*/
|
|
41
|
+
export declare function recoverHeldPlans(deps: ResetDeps, held: SubscriptionCredential): Promise<boolean>;
|
|
@@ -0,0 +1,235 @@
|
|
|
1
|
+
import { claimClaudeReset, claudeOrganizationUuid, claudeResetsFromReport, claudeUsageFromReport, claudeUsageReport, codexResets, codexUsage, consumeCodexReset, nextClaudeGrant, uuidv5, } from "../../providers/subscription_resets.js";
|
|
2
|
+
import { codexUsageFromReport, fetchCodexUsageReport } from "../../providers/codex_usage.js";
|
|
3
|
+
import { refreshedAccessToken } from "./access.js";
|
|
4
|
+
import { isHeld } from "./store.js";
|
|
5
|
+
export function providerBaseUrls(providers) {
|
|
6
|
+
return {
|
|
7
|
+
...(providers.anthropic === undefined ? {} : { claude: providers.anthropic.baseUrl }),
|
|
8
|
+
...(providers["openai-codex"] === undefined ? {} : { codex: providers["openai-codex"].baseUrl }),
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
// Names a spend, so a repeat reuses its request id (the control plane's).
|
|
12
|
+
const USE_NAMESPACE = "0c7d4b2e-8f1a-4c3e-9b6d-5a2e1f0d7c48";
|
|
13
|
+
const CODEX_REDEEM_NAMESPACE = "5f0b3d1e-6a43-4f0e-9a4f-1c2d0b8e7a11";
|
|
14
|
+
const CLAUDE_CLAIM_NAMESPACE = "9b6e2f4a-3c1d-4e8b-a7f0-2d5c8e1b6a93";
|
|
15
|
+
// A window this full is the one blocking the plan.
|
|
16
|
+
const EXHAUSTED_PERCENT = 99;
|
|
17
|
+
const RESETTABLE = ["anthropic_claude_code", "openai_codex"];
|
|
18
|
+
export function hasBankedResets(credential) {
|
|
19
|
+
return RESETTABLE.includes(credential.provider);
|
|
20
|
+
}
|
|
21
|
+
/** The plan's banked resets, the soonest to expire first. */
|
|
22
|
+
export async function listResets(deps, credential) {
|
|
23
|
+
const token = await refreshedAccessToken(deps.store, credential, deps);
|
|
24
|
+
if (credential.provider === "openai_codex")
|
|
25
|
+
return await codexResets(deps.fetch, codexAccess(deps, credential, token));
|
|
26
|
+
return claudeResetsFromReport(await claudeUsageReport(deps.fetch, token, deps.baseUrls?.claude));
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
29
|
+
* Spend one reset now: the provider's answer, "reset" when it restored the
|
|
30
|
+
* plan, which is then released. Checked against a fresh list first: one spent
|
|
31
|
+
* or gone answers "unavailable", one not usable yet "not_usable".
|
|
32
|
+
*/
|
|
33
|
+
export async function useReset(deps, credential, resetId) {
|
|
34
|
+
const now = deps.now ?? new Date();
|
|
35
|
+
const token = await refreshedAccessToken(deps.store, credential, deps);
|
|
36
|
+
const reset = (await listResets(deps, credential)).find((candidate) => candidate.id === resetId);
|
|
37
|
+
if (reset === undefined)
|
|
38
|
+
return "unavailable";
|
|
39
|
+
if (!reset.usable)
|
|
40
|
+
return "not_usable";
|
|
41
|
+
let result;
|
|
42
|
+
if (credential.provider === "openai_codex") {
|
|
43
|
+
// A credit is spent once, so a repeated request names the same spend.
|
|
44
|
+
result = await consumeCodexReset(deps.fetch, codexAccess(deps, credential, token), resetId, uuidv5(`${credential.id}:${resetId}`, USE_NAMESPACE));
|
|
45
|
+
}
|
|
46
|
+
else {
|
|
47
|
+
const organizationUuid = await claudeOrganizationUuid(deps.fetch, token, deps.baseUrls?.claude);
|
|
48
|
+
if (organizationUuid === null)
|
|
49
|
+
throw new Error("Claude did not name the account's organization.");
|
|
50
|
+
result = await claimClaudeReset(deps.fetch, token, {
|
|
51
|
+
organizationUuid,
|
|
52
|
+
grantId: resetId,
|
|
53
|
+
// The grant and how many of its resets were left: a retry is the same
|
|
54
|
+
// request, and the grant's next reset a new one.
|
|
55
|
+
requestId: uuidv5(`${credential.id}:${resetId}:${reset.remaining}`, USE_NAMESPACE),
|
|
56
|
+
}, deps.baseUrls?.claude);
|
|
57
|
+
}
|
|
58
|
+
if (result === "reset")
|
|
59
|
+
await readmit(deps, credential, token, now);
|
|
60
|
+
return result;
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* After a usage-limit hold on one of the owner's plans: correct a ChatGPT
|
|
64
|
+
* plan's hold from Codex's report, and once every plan of the provider is
|
|
65
|
+
* held, release one the provider already serves again or spend one banked
|
|
66
|
+
* reset on the plan that would stay out longest, among those with
|
|
67
|
+
* auto-reset on. Returns whether a plan of the provider serves now.
|
|
68
|
+
*/
|
|
69
|
+
export async function recoverHeldPlans(deps, held) {
|
|
70
|
+
const now = deps.now ?? new Date();
|
|
71
|
+
const serving = () => deps.store.activeCredential(held.provider, now) !== null;
|
|
72
|
+
try {
|
|
73
|
+
if (held.provider === "openai_codex")
|
|
74
|
+
await recoverCodex(deps, held, now, serving);
|
|
75
|
+
else if (held.provider === "anthropic_claude_code" && !serving())
|
|
76
|
+
await recoverClaude(deps, now);
|
|
77
|
+
}
|
|
78
|
+
catch (error) {
|
|
79
|
+
console.error("subscription recovery failed", error instanceof Error ? error.message : String(error));
|
|
80
|
+
}
|
|
81
|
+
return serving();
|
|
82
|
+
}
|
|
83
|
+
async function recoverClaude(deps, now) {
|
|
84
|
+
const candidates = deps.store.list("anthropic_claude_code")
|
|
85
|
+
.filter((plan) => plan.autoRedeemResets && isHeld(plan, now))
|
|
86
|
+
.sort((a, b) => b.unavailableUntil.getTime() - a.unavailableUntil.getTime());
|
|
87
|
+
for (const plan of candidates) {
|
|
88
|
+
const outcome = await claimOnHold(deps, plan, now);
|
|
89
|
+
// At most one reset per outage.
|
|
90
|
+
if (outcome !== "skipped")
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
async function claimOnHold(deps, plan, now) {
|
|
95
|
+
let token;
|
|
96
|
+
let grant = null;
|
|
97
|
+
try {
|
|
98
|
+
token = await refreshedAccessToken(deps.store, plan, deps);
|
|
99
|
+
const grantId = nextClaudeGrant(await claudeUsageReport(deps.fetch, token, deps.baseUrls?.claude));
|
|
100
|
+
const organizationUuid = grantId === null ? null : await claudeOrganizationUuid(deps.fetch, token, deps.baseUrls?.claude);
|
|
101
|
+
if (grantId !== null && organizationUuid !== null)
|
|
102
|
+
grant = { grantId, organizationUuid };
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
console.error("claude reset grant read failed", error instanceof Error ? error.message : String(error));
|
|
106
|
+
return "skipped";
|
|
107
|
+
}
|
|
108
|
+
if (grant === null)
|
|
109
|
+
return "skipped";
|
|
110
|
+
let result;
|
|
111
|
+
try {
|
|
112
|
+
result = await claimClaudeReset(deps.fetch, token, {
|
|
113
|
+
...grant,
|
|
114
|
+
// One outage is one held window, so its end names it.
|
|
115
|
+
requestId: uuidv5(`${plan.id}:${Math.trunc(plan.unavailableUntil.getTime() / 1000)}`, CLAUDE_CLAIM_NAMESPACE),
|
|
116
|
+
}, deps.baseUrls?.claude);
|
|
117
|
+
}
|
|
118
|
+
catch (error) {
|
|
119
|
+
// The reset may have been spent; never risk a second one.
|
|
120
|
+
console.error("claude reset claim failed", error instanceof Error ? error.message : String(error));
|
|
121
|
+
return "spent";
|
|
122
|
+
}
|
|
123
|
+
if (result === "reset") {
|
|
124
|
+
await readmit(deps, plan, token, now);
|
|
125
|
+
return "restored";
|
|
126
|
+
}
|
|
127
|
+
// Claude declined without spending a reset; another plan may claim one.
|
|
128
|
+
return ["not_limited", "ineligible", "cooldown"].includes(result) ? "skipped" : "spent";
|
|
129
|
+
}
|
|
130
|
+
async function recoverCodex(deps, held, now, serving) {
|
|
131
|
+
const usages = new Map();
|
|
132
|
+
const usageOf = async (plan) => {
|
|
133
|
+
if (!usages.has(plan.id)) {
|
|
134
|
+
try {
|
|
135
|
+
usages.set(plan.id, await codexUsage(deps.fetch, codexAccess(deps, plan, await refreshedAccessToken(deps.store, plan, deps))));
|
|
136
|
+
}
|
|
137
|
+
catch (error) {
|
|
138
|
+
// The report only refines a hold that already landed.
|
|
139
|
+
console.error("codex usage read failed", error instanceof Error ? error.message : String(error));
|
|
140
|
+
usages.set(plan.id, null);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
return usages.get(plan.id);
|
|
144
|
+
};
|
|
145
|
+
const heldUsage = await usageOf(held);
|
|
146
|
+
const recovery = heldUsage === null ? null : naturalRecovery(heldUsage, now);
|
|
147
|
+
// Holds only grow.
|
|
148
|
+
if (recovery !== null)
|
|
149
|
+
deps.store.markUnavailable(held.id, recovery, held.unavailableReason ?? "ChatGPT usage limit reached.", now);
|
|
150
|
+
if (serving())
|
|
151
|
+
return;
|
|
152
|
+
const candidates = [];
|
|
153
|
+
for (const plan of deps.store.list("openai_codex")) {
|
|
154
|
+
const usage = await usageOf(plan);
|
|
155
|
+
if (usage === null)
|
|
156
|
+
continue;
|
|
157
|
+
// The just-held plan's report can lag its own refusal.
|
|
158
|
+
if (usage.allowed === true && plan.id !== held.id) {
|
|
159
|
+
deps.store.markAvailable(plan.name, now);
|
|
160
|
+
return;
|
|
161
|
+
}
|
|
162
|
+
const back = naturalRecovery(usage, now);
|
|
163
|
+
if (plan.autoRedeemResets && back !== null && usage.availableResets > 0)
|
|
164
|
+
candidates.push({ plan, recovery: back });
|
|
165
|
+
}
|
|
166
|
+
// The plan that would stay out longest gains the most from a reset.
|
|
167
|
+
candidates.sort((a, b) => b.recovery.getTime() - a.recovery.getTime());
|
|
168
|
+
for (const { plan, recovery: back } of candidates) {
|
|
169
|
+
const outcome = await redeemOnHold(deps, plan, back, now);
|
|
170
|
+
// At most one credit per outage, even when Codex has not caught up.
|
|
171
|
+
if (outcome !== "skipped")
|
|
172
|
+
return;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
async function redeemOnHold(deps, plan, recovery, now) {
|
|
176
|
+
let access;
|
|
177
|
+
let creditId;
|
|
178
|
+
try {
|
|
179
|
+
access = codexAccess(deps, plan, await refreshedAccessToken(deps.store, plan, deps));
|
|
180
|
+
creditId = (await codexResets(deps.fetch, access))[0]?.id;
|
|
181
|
+
}
|
|
182
|
+
catch (error) {
|
|
183
|
+
console.error("codex reset credit read failed", error instanceof Error ? error.message : String(error));
|
|
184
|
+
return "skipped";
|
|
185
|
+
}
|
|
186
|
+
if (creditId === undefined)
|
|
187
|
+
return "skipped";
|
|
188
|
+
let code;
|
|
189
|
+
try {
|
|
190
|
+
// One outage is one exhausted window, so its reset names it.
|
|
191
|
+
code = await consumeCodexReset(deps.fetch, access, creditId, uuidv5(`${plan.id}:${Math.trunc(recovery.getTime() / 1000)}`, CODEX_REDEEM_NAMESPACE));
|
|
192
|
+
}
|
|
193
|
+
catch (error) {
|
|
194
|
+
// The credit may have been spent; never risk a second one.
|
|
195
|
+
console.error("codex reset redemption failed", error instanceof Error ? error.message : String(error));
|
|
196
|
+
return "spent";
|
|
197
|
+
}
|
|
198
|
+
// Codex declined without spending a credit; another plan may redeem one.
|
|
199
|
+
if (code === "no_credit" || code === "nothing_to_reset")
|
|
200
|
+
return "skipped";
|
|
201
|
+
// A repeat for this outage restores only once Codex says the plan serves.
|
|
202
|
+
const restored = code === "reset"
|
|
203
|
+
|| (code === "already_redeemed" && (await codexUsage(deps.fetch, access).catch(() => null))?.allowed === true);
|
|
204
|
+
if (!restored)
|
|
205
|
+
return "spent";
|
|
206
|
+
await readmit(deps, plan, access.accessToken, now);
|
|
207
|
+
return "restored";
|
|
208
|
+
}
|
|
209
|
+
// When a blocked ChatGPT plan returns on its own: the latest exhausted window's reset.
|
|
210
|
+
function naturalRecovery(usage, now) {
|
|
211
|
+
if (usage.allowed !== false && usage.limitReached !== true)
|
|
212
|
+
return null;
|
|
213
|
+
const future = usage.windows
|
|
214
|
+
.filter(([used, resetAt]) => used >= EXHAUSTED_PERCENT && resetAt !== null && resetAt * 1000 > now.getTime())
|
|
215
|
+
.map(([, resetAt]) => resetAt * 1000);
|
|
216
|
+
return future.length > 0 ? new Date(Math.max(...future)) : null;
|
|
217
|
+
}
|
|
218
|
+
// A plan the provider restored: release its holds, and record its usage now
|
|
219
|
+
// when it can be read (a failed read leaves it to the next response).
|
|
220
|
+
async function readmit(deps, plan, token, now) {
|
|
221
|
+
deps.store.markAvailable(plan.name, now);
|
|
222
|
+
try {
|
|
223
|
+
const usage = plan.provider === "openai_codex"
|
|
224
|
+
? codexUsageFromReport(await fetchCodexUsageReport({ accessToken: token, fetch: deps.fetch, ...(deps.baseUrls?.codex ? { baseUrl: deps.baseUrls.codex } : {}) }), now)
|
|
225
|
+
: claudeUsageFromReport(await claudeUsageReport(deps.fetch, token, deps.baseUrls?.claude), now);
|
|
226
|
+
if (usage !== null)
|
|
227
|
+
deps.store.recordUsage(plan.id, usage, now);
|
|
228
|
+
}
|
|
229
|
+
catch (error) {
|
|
230
|
+
console.error("usage read after a reset failed", error instanceof Error ? error.message : String(error));
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
function codexAccess(deps, plan, token) {
|
|
234
|
+
return { accessToken: token, accountId: plan.accountId, ...(deps.baseUrls?.codex ? { baseUrl: deps.baseUrls.codex } : {}) };
|
|
235
|
+
}
|
|
@@ -37,6 +37,8 @@ export type SubscriptionCredential = {
|
|
|
37
37
|
accountEmail: string | null;
|
|
38
38
|
accountId: string | null;
|
|
39
39
|
owner: string | null;
|
|
40
|
+
private: boolean;
|
|
41
|
+
autoRedeemResets: boolean;
|
|
40
42
|
accessToken: string;
|
|
41
43
|
refreshToken: string;
|
|
42
44
|
expiresAt: Date;
|
|
@@ -62,20 +64,63 @@ export type PendingOAuthSession = {
|
|
|
62
64
|
flow: Record<string, string>;
|
|
63
65
|
credentialName: string | null;
|
|
64
66
|
owner: string | null;
|
|
67
|
+
private: boolean;
|
|
65
68
|
expiresAt: Date;
|
|
66
69
|
};
|
|
70
|
+
/** The parts of a plan that say which provider account it is. */
|
|
71
|
+
export type AccountRef = {
|
|
72
|
+
provider: SubscriptionProvider;
|
|
73
|
+
accountId: string | null;
|
|
74
|
+
accountEmail: string | null;
|
|
75
|
+
};
|
|
76
|
+
/**
|
|
77
|
+
* A plan of the same user that already holds an account, wherever it lives.
|
|
78
|
+
* `name` is the plan's handle where it is known; `gatewayName` names the other
|
|
79
|
+
* computer for an `other_computer` plan.
|
|
80
|
+
*/
|
|
81
|
+
export type ConnectedAccount = AccountRef & {
|
|
82
|
+
place: "dari" | "this_computer" | "private" | "other_computer";
|
|
83
|
+
name: string | null;
|
|
84
|
+
gatewayName: string | null;
|
|
85
|
+
};
|
|
86
|
+
/** Connecting an account the same user already has connected; the message says where it lives and how to move it. */
|
|
87
|
+
export declare class SubscriptionAccountConnectedError extends Error {
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Whether two plans are the same provider account: by account id when both
|
|
91
|
+
* carry one, otherwise by email (Claude Code sign-ins carry only an email).
|
|
92
|
+
*/
|
|
93
|
+
export declare function sameConnectedAccount(a: AccountRef, b: AccountRef): boolean;
|
|
67
94
|
export declare class SubscriptionStore {
|
|
68
95
|
private readonly db;
|
|
69
96
|
private readonly box;
|
|
70
|
-
|
|
97
|
+
private readonly options;
|
|
98
|
+
/**
|
|
99
|
+
* Told of each change hosted Dari's copy of the plans would show: `plans`
|
|
100
|
+
* for a plan connected, removed, renamed, moved, held, or released, and
|
|
101
|
+
* `usage` for reported usage or use.
|
|
102
|
+
*/
|
|
103
|
+
onChange: ((change: "plans" | "usage") => void) | undefined;
|
|
104
|
+
/**
|
|
105
|
+
* `privatePlansServe: false` (a gateway connected to hosted Dari) leaves
|
|
106
|
+
* private plans out of routing and `list`; `list(provider, true)` still
|
|
107
|
+
* shows them.
|
|
108
|
+
*/
|
|
109
|
+
constructor(db: Database, box?: SecretBox | null, options?: {
|
|
110
|
+
privatePlansServe?: boolean;
|
|
111
|
+
});
|
|
71
112
|
/** Whether stored tokens are encrypted. */
|
|
72
113
|
get encrypted(): boolean;
|
|
73
114
|
private encryptStored;
|
|
74
115
|
private seal;
|
|
75
116
|
private open;
|
|
76
117
|
private credential;
|
|
77
|
-
/**
|
|
78
|
-
|
|
118
|
+
/**
|
|
119
|
+
* The gateway owner's subscriptions that serve, grouped by provider, in
|
|
120
|
+
* connection order; with `includePrivate`, private ones too even where they
|
|
121
|
+
* do not serve.
|
|
122
|
+
*/
|
|
123
|
+
list(provider?: SubscriptionProvider, includePrivate?: boolean): SubscriptionCredential[];
|
|
79
124
|
/** The subscriptions a Dari Link user connected. */
|
|
80
125
|
owned(owner: string): SubscriptionCredential[];
|
|
81
126
|
/** The subscriptions with these ids, whoever connected them. */
|
|
@@ -107,17 +152,25 @@ export declare class SubscriptionStore {
|
|
|
107
152
|
private pinConversation;
|
|
108
153
|
/**
|
|
109
154
|
* Store tokens from a completed OAuth flow. `reconnectName` replaces that
|
|
110
|
-
* subscription (null when it is not connected)
|
|
111
|
-
*
|
|
112
|
-
*
|
|
113
|
-
*
|
|
155
|
+
* subscription (null when it is not connected) and keeps its place, as long
|
|
156
|
+
* as it is still the same account. Otherwise the sign-in is connected last
|
|
157
|
+
* in order under the first free name. A sign-in refused as a second copy
|
|
158
|
+
* throws `SubscriptionAccountConnectedError`: the same account is already
|
|
159
|
+
* connected for this owner (`owner` is the Dari Link user connecting it;
|
|
160
|
+
* null is the gateway owner), or `elsewhere` (the owner's plans on hosted
|
|
161
|
+
* Dari and other computers) holds it.
|
|
114
162
|
*/
|
|
115
|
-
connect(tokens: OAuthTokens, reconnectName: string | null, now?: Date, owner?: string | null): SubscriptionCredential | null;
|
|
163
|
+
connect(tokens: OAuthTokens, reconnectName: string | null, now?: Date, owner?: string | null, isPrivate?: boolean, elsewhere?: ConnectedAccount[]): SubscriptionCredential | null;
|
|
164
|
+
private refuseSecondCopy;
|
|
116
165
|
/** Persist refreshed tokens. Keeps the stored account id when the refresh carries none. */
|
|
117
166
|
updateTokens(id: string, tokens: OAuthTokens, now?: Date): void;
|
|
118
167
|
touch(id: string, now?: Date): void;
|
|
119
168
|
/** An empty label clears it. Null when the subscription is not connected. */
|
|
120
169
|
rename(name: string, label: string | null, now?: Date): SubscriptionCredential | null;
|
|
170
|
+
/** Make the gateway owner's subscription private, or not. Null when it is not connected. */
|
|
171
|
+
setPrivate(name: string, isPrivate: boolean, now?: Date): SubscriptionCredential | null;
|
|
172
|
+
/** Let routing spend the plan's banked resets, or not. Null when it is not connected. */
|
|
173
|
+
setAutoRedeemResets(name: string, enabled: boolean, now?: Date): SubscriptionCredential | null;
|
|
121
174
|
/** Remove a subscription. Returns what was removed, or null when it was not connected. */
|
|
122
175
|
disconnect(name: string, owner?: string | null): SubscriptionCredential | null;
|
|
123
176
|
/**
|