@mupt-ai/dari-gateway 1.0.354 → 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
|
@@ -7,7 +7,6 @@ import { providerAuthForSelectedModel } from "../strategies/routing.js";
|
|
|
7
7
|
import { scrubSecretValues } from "../telemetry/scrub.js";
|
|
8
8
|
import { usageContextFor, } from "../telemetry/usage.js";
|
|
9
9
|
import { awsRoleCredentials } from "./aws_assume_role.js";
|
|
10
|
-
import { copilotEndpoint } from "./github_copilot.js";
|
|
11
10
|
import { attachProviderResponseCapture, createProviderResponseCapture, } from "./response_capture.js";
|
|
12
11
|
import { subscriptionOAuthProviderFor } from "./subscription_limits.js";
|
|
13
12
|
import { completeInteractionModel, streamInteractionModel, } from "./pi.js";
|
|
@@ -51,10 +50,7 @@ export function prepareProviderExecution(args) {
|
|
|
51
50
|
...(args.systemPromptSuffix ? { systemPromptSuffix: args.systemPromptSuffix } : {}),
|
|
52
51
|
...(supplied?.baseUrl || supplied?.headers
|
|
53
52
|
? { endpoint: { baseUrl: supplied.baseUrl, headers: supplied.headers } }
|
|
54
|
-
|
|
55
|
-
: provider === "github-copilot" && auth.type === "bearer"
|
|
56
|
-
? { endpoint: copilotEndpoint(auth.apiKey) }
|
|
57
|
-
: {}),
|
|
53
|
+
: {}),
|
|
58
54
|
provider,
|
|
59
55
|
providerKeySource,
|
|
60
56
|
// Only resolved personal subscriptions are held at their usage limit;
|
|
@@ -66,7 +66,7 @@ export declare function subscriptionOAuthProviderFor(provider: string, keySource
|
|
|
66
66
|
/**
|
|
67
67
|
* Recognize a personal subscription that has run out of quota. Claude Code
|
|
68
68
|
* answers 429 with the unified rate-limit headers; the ChatGPT backend answers
|
|
69
|
-
* 429 with a structured `error.code` and `resets_at`. Meta,
|
|
69
|
+
* 429 with a structured `error.code` and `resets_at`. Meta,
|
|
70
70
|
* xAI, Kimi, and Vercel Token Pass document no usage-limit signature for their
|
|
71
71
|
* plans, so any 429 on one holds it until the reset it gives, if any. OpenCode
|
|
72
72
|
* Go names its refusal
|
|
@@ -119,7 +119,6 @@ const SUBSCRIPTION_LABEL = {
|
|
|
119
119
|
openai_codex: "ChatGPT",
|
|
120
120
|
meta_muse: "Muse Code",
|
|
121
121
|
opencode_go: "OpenCode Go",
|
|
122
|
-
github_copilot: "GitHub Copilot",
|
|
123
122
|
xai_grok: "Grok",
|
|
124
123
|
vercel_token_pass: "Vercel Token Pass",
|
|
125
124
|
};
|
|
@@ -136,8 +135,6 @@ export function subscriptionOAuthProviderFor(provider, keySource) {
|
|
|
136
135
|
return "meta_muse";
|
|
137
136
|
if (provider === "opencode-go")
|
|
138
137
|
return "opencode_go";
|
|
139
|
-
if (provider === "github-copilot")
|
|
140
|
-
return "github_copilot";
|
|
141
138
|
if (provider === "xai")
|
|
142
139
|
return "xai_grok";
|
|
143
140
|
if (provider === "vercel-token-pass")
|
|
@@ -147,7 +144,7 @@ export function subscriptionOAuthProviderFor(provider, keySource) {
|
|
|
147
144
|
/**
|
|
148
145
|
* Recognize a personal subscription that has run out of quota. Claude Code
|
|
149
146
|
* answers 429 with the unified rate-limit headers; the ChatGPT backend answers
|
|
150
|
-
* 429 with a structured `error.code` and `resets_at`. Meta,
|
|
147
|
+
* 429 with a structured `error.code` and `resets_at`. Meta,
|
|
151
148
|
* xAI, Kimi, and Vercel Token Pass document no usage-limit signature for their
|
|
152
149
|
* plans, so any 429 on one holds it until the reset it gives, if any. OpenCode
|
|
153
150
|
* Go names its refusal
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import { type SubscriptionUsage } from "./subscription_limits.js";
|
|
2
|
+
/**
|
|
3
|
+
* The provider endpoints behind banked limit resets and Claude Code's plan
|
|
4
|
+
* usage report: the ChatGPT backend the Codex CLI uses and the claude.ai
|
|
5
|
+
* OAuth endpoints Claude Code's `/limit-reset` uses. Hosted Dari and the
|
|
6
|
+
* self-hosted gateway both spend resets through these.
|
|
7
|
+
*/
|
|
8
|
+
export declare const CODEX_BACKEND_URL = "https://chatgpt.com/backend-api";
|
|
9
|
+
export declare const CLAUDE_BASE_URL = "https://api.anthropic.com";
|
|
10
|
+
type Fetch = (input: string, init: RequestInit) => Promise<Response>;
|
|
11
|
+
/** A banked limit reset of a ChatGPT or Claude Code plan. */
|
|
12
|
+
export type BankedReset = {
|
|
13
|
+
id: string;
|
|
14
|
+
label: string;
|
|
15
|
+
expiresAt: Date | null;
|
|
16
|
+
usable: boolean;
|
|
17
|
+
remaining: number | null;
|
|
18
|
+
};
|
|
19
|
+
export type CodexAccess = {
|
|
20
|
+
accessToken: string;
|
|
21
|
+
accountId: string | null;
|
|
22
|
+
baseUrl?: string;
|
|
23
|
+
};
|
|
24
|
+
export type CodexUsage = {
|
|
25
|
+
allowed: boolean | null;
|
|
26
|
+
limitReached: boolean | null;
|
|
27
|
+
windows: Array<[number, number | null]>;
|
|
28
|
+
availableResets: number;
|
|
29
|
+
};
|
|
30
|
+
export declare function codexUsage(fetch: Fetch, access: CodexAccess): Promise<CodexUsage>;
|
|
31
|
+
/** Every banked reset the ChatGPT plan can still spend, the soonest to expire first. */
|
|
32
|
+
export declare function codexResets(fetch: Fetch, access: CodexAccess): Promise<BankedReset[]>;
|
|
33
|
+
/** Spend a ChatGPT credit; Codex's answer, "reset" when it restored the plan. */
|
|
34
|
+
export declare function consumeCodexReset(fetch: Fetch, access: CodexAccess, creditId: string, requestId: string): Promise<string>;
|
|
35
|
+
/** Claude Code's usage report: the plan's windows and its banked resets. */
|
|
36
|
+
export declare function claudeUsageReport(fetch: Fetch, token: string, baseUrl?: string): Promise<Record<string, unknown>>;
|
|
37
|
+
/** The plan's 5 hour and weekly windows from a usage report. */
|
|
38
|
+
export declare function claudeUsageFromReport(report: Record<string, unknown>, now: Date): SubscriptionUsage | null;
|
|
39
|
+
/** Every limit reset a usage report says the account has left, the soonest to expire first. */
|
|
40
|
+
export declare function claudeResetsFromReport(report: Record<string, unknown>): BankedReset[];
|
|
41
|
+
/** The grant Claude would spend next, when it can be spent now. */
|
|
42
|
+
export declare function nextClaudeGrant(report: Record<string, unknown>): string | null;
|
|
43
|
+
/** The claude.ai organization the account's resets are claimed in. */
|
|
44
|
+
export declare function claudeOrganizationUuid(fetch: Fetch, token: string, baseUrl?: string): Promise<string | null>;
|
|
45
|
+
/** Claim one reset of a grant; Claude's answer, "reset" when it restored the plan. */
|
|
46
|
+
export declare function claimClaudeReset(fetch: Fetch, token: string, claim: {
|
|
47
|
+
organizationUuid: string;
|
|
48
|
+
grantId: string;
|
|
49
|
+
requestId: string;
|
|
50
|
+
}, baseUrl?: string): Promise<string>;
|
|
51
|
+
/** RFC 4122 name-based UUID (version 5), as Python's `uuid.uuid5`. */
|
|
52
|
+
export declare function uuidv5(name: string, namespace: string): string;
|
|
53
|
+
export {};
|
|
@@ -0,0 +1,184 @@
|
|
|
1
|
+
import { createHash } from "node:crypto";
|
|
2
|
+
import { isRecord } from "@mupt-ai/dari-router/policy-engine";
|
|
3
|
+
import { subscriptionUsageFromWindows } from "./subscription_limits.js";
|
|
4
|
+
/**
|
|
5
|
+
* The provider endpoints behind banked limit resets and Claude Code's plan
|
|
6
|
+
* usage report: the ChatGPT backend the Codex CLI uses and the claude.ai
|
|
7
|
+
* OAuth endpoints Claude Code's `/limit-reset` uses. Hosted Dari and the
|
|
8
|
+
* self-hosted gateway both spend resets through these.
|
|
9
|
+
*/
|
|
10
|
+
export const CODEX_BACKEND_URL = "https://chatgpt.com/backend-api";
|
|
11
|
+
export const CLAUDE_BASE_URL = "https://api.anthropic.com";
|
|
12
|
+
// Anthropic offers grants only to the Claude Code CLI surface.
|
|
13
|
+
const CLAUDE_USER_AGENT = "claude-cli/2.1.280 (external, cli)";
|
|
14
|
+
const CLAUDE_PROGRAM = "cedar_ember";
|
|
15
|
+
export async function codexUsage(fetch, access) {
|
|
16
|
+
const body = await codexRequest(fetch, "GET", "/wham/usage", access);
|
|
17
|
+
const rateLimit = isRecord(body.rate_limit) ? body.rate_limit : {};
|
|
18
|
+
const windows = [];
|
|
19
|
+
for (const name of ["primary_window", "secondary_window"]) {
|
|
20
|
+
const window = rateLimit[name];
|
|
21
|
+
if (!isRecord(window) || typeof window.used_percent !== "number")
|
|
22
|
+
continue;
|
|
23
|
+
windows.push([window.used_percent, Number.isInteger(window.reset_at) ? window.reset_at : null]);
|
|
24
|
+
}
|
|
25
|
+
const credits = body.rate_limit_reset_credits;
|
|
26
|
+
const available = isRecord(credits) ? credits.available_count : 0;
|
|
27
|
+
return {
|
|
28
|
+
allowed: typeof rateLimit.allowed === "boolean" ? rateLimit.allowed : null,
|
|
29
|
+
limitReached: typeof rateLimit.limit_reached === "boolean" ? rateLimit.limit_reached : null,
|
|
30
|
+
windows,
|
|
31
|
+
availableResets: Number.isInteger(available) ? Math.max(available, 0) : 0,
|
|
32
|
+
};
|
|
33
|
+
}
|
|
34
|
+
/** Every banked reset the ChatGPT plan can still spend, the soonest to expire first. */
|
|
35
|
+
export async function codexResets(fetch, access) {
|
|
36
|
+
const body = await codexRequest(fetch, "GET", "/wham/rate-limit-reset-credits", access);
|
|
37
|
+
const credits = (Array.isArray(body.credits) ? body.credits : []).filter((credit) => isRecord(credit) && credit.reset_type === "codex_rate_limits" && credit.status === "available"
|
|
38
|
+
&& typeof credit.id === "string");
|
|
39
|
+
return soonestFirst(credits.map((credit) => ({
|
|
40
|
+
id: credit.id,
|
|
41
|
+
label: typeof credit.title === "string" ? credit.title : "Full reset",
|
|
42
|
+
expiresAt: timestamp(credit.expires_at),
|
|
43
|
+
usable: credit.is_supported_by_plan !== false,
|
|
44
|
+
remaining: null,
|
|
45
|
+
})));
|
|
46
|
+
}
|
|
47
|
+
/** Spend a ChatGPT credit; Codex's answer, "reset" when it restored the plan. */
|
|
48
|
+
export async function consumeCodexReset(fetch, access, creditId, requestId) {
|
|
49
|
+
const body = await codexRequest(fetch, "POST", "/wham/rate-limit-reset-credits/consume", access, {
|
|
50
|
+
redeem_request_id: requestId,
|
|
51
|
+
credit_id: creditId,
|
|
52
|
+
});
|
|
53
|
+
return typeof body.code === "string" ? body.code : "unknown";
|
|
54
|
+
}
|
|
55
|
+
async function codexRequest(fetch, method, path, access, payload) {
|
|
56
|
+
const headers = {
|
|
57
|
+
Accept: "application/json",
|
|
58
|
+
Authorization: `Bearer ${access.accessToken}`,
|
|
59
|
+
"User-Agent": "Dari/1.0",
|
|
60
|
+
};
|
|
61
|
+
if (access.accountId)
|
|
62
|
+
headers["ChatGPT-Account-Id"] = access.accountId;
|
|
63
|
+
if (payload !== undefined)
|
|
64
|
+
headers["Content-Type"] = "application/json";
|
|
65
|
+
return await readJson(fetch, `${(access.baseUrl ?? CODEX_BACKEND_URL).replace(/\/+$/, "")}${path}`, {
|
|
66
|
+
method,
|
|
67
|
+
headers,
|
|
68
|
+
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
|
69
|
+
signal: AbortSignal.timeout(8_000),
|
|
70
|
+
}, "Codex usage request");
|
|
71
|
+
}
|
|
72
|
+
/** Claude Code's usage report: the plan's windows and its banked resets. */
|
|
73
|
+
export async function claudeUsageReport(fetch, token, baseUrl) {
|
|
74
|
+
return await claudeRequest(fetch, "GET", "/api/oauth/usage?cedar_ember=1&skip_spend=1", token, baseUrl);
|
|
75
|
+
}
|
|
76
|
+
/** The plan's 5 hour and weekly windows from a usage report. */
|
|
77
|
+
export function claudeUsageFromReport(report, now) {
|
|
78
|
+
return subscriptionUsageFromWindows([["five_hour", 5 * 60], ["seven_day", 7 * 24 * 60]].map(([name, minutes]) => {
|
|
79
|
+
const window = isRecord(report[name]) ? report[name] : {};
|
|
80
|
+
const used = window.utilization;
|
|
81
|
+
return {
|
|
82
|
+
minutes,
|
|
83
|
+
used: typeof used === "number" ? used / 100 : NaN,
|
|
84
|
+
resetsAt: timestamp(window.resets_at),
|
|
85
|
+
};
|
|
86
|
+
}), now);
|
|
87
|
+
}
|
|
88
|
+
/** Every limit reset a usage report says the account has left, the soonest to expire first. */
|
|
89
|
+
export function claudeResetsFromReport(report) {
|
|
90
|
+
const status = isRecord(report.cedar_ember) ? report.cedar_ember : {};
|
|
91
|
+
const eligible = status.eligible === true;
|
|
92
|
+
const grants = (Array.isArray(status.grants) ? status.grants : []).filter((grant) => isRecord(grant) && typeof grant.id === "string" && Number.isInteger(grant.resets_left) && grant.resets_left > 0);
|
|
93
|
+
return soonestFirst(grants.map((grant) => ({
|
|
94
|
+
id: grant.id,
|
|
95
|
+
label: claudeGrantKind(grant),
|
|
96
|
+
expiresAt: timestamp(grant.ends_at),
|
|
97
|
+
usable: eligible && grant.usable_now === true,
|
|
98
|
+
remaining: grant.resets_left,
|
|
99
|
+
})));
|
|
100
|
+
}
|
|
101
|
+
/** The grant Claude would spend next, when it can be spent now. */
|
|
102
|
+
export function nextClaudeGrant(report) {
|
|
103
|
+
const status = report.cedar_ember;
|
|
104
|
+
if (!isRecord(status) || status.eligible !== true)
|
|
105
|
+
return null;
|
|
106
|
+
const grantId = status.next_grant_id;
|
|
107
|
+
const grant = (Array.isArray(status.grants) ? status.grants : []).find((candidate) => isRecord(candidate) && candidate.id === grantId);
|
|
108
|
+
return typeof grantId === "string" && isRecord(grant) && grant.usable_now === true ? grantId : null;
|
|
109
|
+
}
|
|
110
|
+
/** The claude.ai organization the account's resets are claimed in. */
|
|
111
|
+
export async function claudeOrganizationUuid(fetch, token, baseUrl) {
|
|
112
|
+
const profile = await claudeRequest(fetch, "GET", "/api/oauth/profile", token, baseUrl);
|
|
113
|
+
const organization = profile.organization;
|
|
114
|
+
const uuid = isRecord(organization) ? organization.uuid : undefined;
|
|
115
|
+
return typeof uuid === "string" && uuid ? uuid : null;
|
|
116
|
+
}
|
|
117
|
+
/** Claim one reset of a grant; Claude's answer, "reset" when it restored the plan. */
|
|
118
|
+
export async function claimClaudeReset(fetch, token, claim, baseUrl) {
|
|
119
|
+
const body = await claudeRequest(fetch, "POST", `/api/organizations/${claim.organizationUuid}/reset_rate_limits`, token, baseUrl, { program: CLAUDE_PROGRAM, grant_id: claim.grantId, request_id: claim.requestId });
|
|
120
|
+
return typeof body.result === "string" ? body.result : "unknown";
|
|
121
|
+
}
|
|
122
|
+
// Name a grant by the limit it clears: Claude's own labels are sentences.
|
|
123
|
+
function claudeGrantKind(grant) {
|
|
124
|
+
const clears = Array.isArray(grant.clears) ? grant.clears : [];
|
|
125
|
+
if (clears.includes("seven_day"))
|
|
126
|
+
return "Weekly reset";
|
|
127
|
+
// The weekly limit Claude reports beside it as the Fable window.
|
|
128
|
+
if (clears.includes("seven_day_overage_included"))
|
|
129
|
+
return "Fable reset";
|
|
130
|
+
return "Limit reset";
|
|
131
|
+
}
|
|
132
|
+
async function claudeRequest(fetch, method, path, token, baseUrl, payload) {
|
|
133
|
+
const headers = {
|
|
134
|
+
Accept: "application/json",
|
|
135
|
+
Authorization: `Bearer ${token}`,
|
|
136
|
+
"anthropic-beta": "oauth-2025-04-20",
|
|
137
|
+
"User-Agent": CLAUDE_USER_AGENT,
|
|
138
|
+
};
|
|
139
|
+
if (payload !== undefined)
|
|
140
|
+
headers["Content-Type"] = "application/json";
|
|
141
|
+
return await readJson(fetch, `${(baseUrl ?? CLAUDE_BASE_URL).replace(/\/+$/, "")}${path}`, {
|
|
142
|
+
method,
|
|
143
|
+
headers,
|
|
144
|
+
...(payload === undefined ? {} : { body: JSON.stringify(payload) }),
|
|
145
|
+
signal: AbortSignal.timeout(25_000),
|
|
146
|
+
}, "Claude reset request");
|
|
147
|
+
}
|
|
148
|
+
async function readJson(fetch, url, init, operation) {
|
|
149
|
+
const response = await fetch(url, init);
|
|
150
|
+
if (!response.ok) {
|
|
151
|
+
await response.body?.cancel();
|
|
152
|
+
throw new Error(response.status === 429
|
|
153
|
+
? `${operation} was rate limited; try again in a minute.`
|
|
154
|
+
: `${operation} failed with status ${response.status}.`);
|
|
155
|
+
}
|
|
156
|
+
const body = await response.json().catch(() => {
|
|
157
|
+
throw new Error(`${operation} failed.`);
|
|
158
|
+
});
|
|
159
|
+
if (!isRecord(body))
|
|
160
|
+
throw new Error(`${operation} returned an invalid response.`);
|
|
161
|
+
return body;
|
|
162
|
+
}
|
|
163
|
+
function soonestFirst(resets) {
|
|
164
|
+
const at = (reset) => reset.expiresAt?.getTime() ?? Infinity;
|
|
165
|
+
return resets.sort((a, b) => at(a) - at(b));
|
|
166
|
+
}
|
|
167
|
+
function timestamp(value) {
|
|
168
|
+
if (typeof value !== "string" || !value)
|
|
169
|
+
return null;
|
|
170
|
+
const parsed = new Date(/[zZ]|[+-]\d\d:?\d\d$/.test(value) ? value : `${value}Z`);
|
|
171
|
+
return Number.isNaN(parsed.getTime()) ? null : parsed;
|
|
172
|
+
}
|
|
173
|
+
/** RFC 4122 name-based UUID (version 5), as Python's `uuid.uuid5`. */
|
|
174
|
+
export function uuidv5(name, namespace) {
|
|
175
|
+
const bytes = createHash("sha1")
|
|
176
|
+
.update(Buffer.from(namespace.replaceAll("-", ""), "hex"))
|
|
177
|
+
.update(name, "utf8")
|
|
178
|
+
.digest()
|
|
179
|
+
.subarray(0, 16);
|
|
180
|
+
bytes[6] = (bytes[6] & 0x0f) | 0x50;
|
|
181
|
+
bytes[8] = (bytes[8] & 0x3f) | 0x80;
|
|
182
|
+
const hex = bytes.toString("hex");
|
|
183
|
+
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
|
|
184
|
+
}
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
import type { GatewayPlatform } from "../platform/platform.js";
|
|
2
|
+
import type { HostedSync } from "./hosted_sync.js";
|
|
3
|
+
import { createSelfHostedPlatform } from "./platform.js";
|
|
4
|
+
/**
|
|
5
|
+
* A self-hosted gateway connected to hosted Dari (the Dari CLI runs one for
|
|
6
|
+
* plans kept "on this computer"): it serves a turn on the user's own plans
|
|
7
|
+
* when one serves the model, and otherwise hands the whole request to hosted
|
|
8
|
+
* Dari with the user's Dari key, so agents see one router either way.
|
|
9
|
+
*
|
|
10
|
+
* - Routers are the user's hosted routers, by id (`/<router id>/v1/...`, or
|
|
11
|
+
* the default router at `/v1/...`): each serves the hosted router's models
|
|
12
|
+
* that a local plan serves, chosen by the hosted Auto Router API.
|
|
13
|
+
* - A request no local plan can serve (none connected or every one held, or
|
|
14
|
+
* a model they do not serve) goes to hosted, as does every other path the
|
|
15
|
+
* gateway does not manage itself, such as model lists and commit reports.
|
|
16
|
+
* - The plans and served requests sync to hosted (hosted_sync.ts), which
|
|
17
|
+
* shows them in Accounts and Activity; private plans neither serve nor sync.
|
|
18
|
+
* Dari Link and Activity are hosted's, not served here.
|
|
19
|
+
*/
|
|
20
|
+
export type HostedConnection = {
|
|
21
|
+
url: string;
|
|
22
|
+
apiKey: string;
|
|
23
|
+
gatewayId: string;
|
|
24
|
+
gatewayName: string;
|
|
25
|
+
};
|
|
26
|
+
/**
|
|
27
|
+
* The connection `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY` set up, or null
|
|
28
|
+
* when neither is set. A connected gateway needs `DARI_GATEWAY_ID` and
|
|
29
|
+
* `DARI_GATEWAY_ENCRYPTION_KEY`; `DARI_GATEWAY_NAME` defaults to the host name.
|
|
30
|
+
*/
|
|
31
|
+
export declare function hostedConnectionFromEnv(env: Record<string, string | undefined>): HostedConnection | null;
|
|
32
|
+
type SelfHostedPlatformDeps = Parameters<typeof createSelfHostedPlatform>[0];
|
|
33
|
+
/** The self-hosted platform on hosted routers, reporting requests to hosted Dari. */
|
|
34
|
+
export declare function createConnectedPlatform(deps: SelfHostedPlatformDeps & {
|
|
35
|
+
hosted: HostedConnection;
|
|
36
|
+
sync: HostedSync;
|
|
37
|
+
}): GatewayPlatform;
|
|
38
|
+
/**
|
|
39
|
+
* Serve a connected gateway's routed surface: `gateway` (the gateway's own
|
|
40
|
+
* handler on the connected platform) first, and hosted Dari for a request it
|
|
41
|
+
* cannot serve on a local plan. Health checks stay local; every request
|
|
42
|
+
* forwarded must carry a gateway key.
|
|
43
|
+
*/
|
|
44
|
+
export declare function connectedHandler(deps: {
|
|
45
|
+
gateway: (request: Request) => Promise<Response>;
|
|
46
|
+
gatewayKeys: readonly string[];
|
|
47
|
+
hosted: HostedConnection;
|
|
48
|
+
sync: HostedSync;
|
|
49
|
+
fetch: typeof fetch;
|
|
50
|
+
}): (request: Request) => Promise<Response>;
|
|
51
|
+
export {};
|
|
@@ -0,0 +1,197 @@
|
|
|
1
|
+
import { hostname } from "node:os";
|
|
2
|
+
import { isReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
|
|
3
|
+
import { anthropicToken, bearerToken } from "../http/auth.js";
|
|
4
|
+
import { errorResponse, HttpError } from "../http/errors.js";
|
|
5
|
+
import { anthropicErrorResponse } from "../ingress/anthropic_messages.js";
|
|
6
|
+
import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
7
|
+
import { explicitModelId } from "../protocol/input/router_model.js";
|
|
8
|
+
import { parseGatewayConfig } from "./config.js";
|
|
9
|
+
import { createSelfHostedPlatform } from "./platform.js";
|
|
10
|
+
import { gatewayKeyIndex, resolveSelfHostedRouter } from "./resolve.js";
|
|
11
|
+
/**
|
|
12
|
+
* The connection `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY` set up, or null
|
|
13
|
+
* when neither is set. A connected gateway needs `DARI_GATEWAY_ID` and
|
|
14
|
+
* `DARI_GATEWAY_ENCRYPTION_KEY`; `DARI_GATEWAY_NAME` defaults to the host name.
|
|
15
|
+
*/
|
|
16
|
+
export function hostedConnectionFromEnv(env) {
|
|
17
|
+
const url = env.DARI_HOSTED_URL?.trim().replace(/\/+$/, "");
|
|
18
|
+
const apiKey = env.DARI_HOSTED_API_KEY?.trim();
|
|
19
|
+
if (!url && !apiKey)
|
|
20
|
+
return null;
|
|
21
|
+
if (!url || !apiKey)
|
|
22
|
+
throw new Error("Set both DARI_HOSTED_URL and DARI_HOSTED_API_KEY to connect to hosted Dari.");
|
|
23
|
+
const gatewayId = env.DARI_GATEWAY_ID?.trim();
|
|
24
|
+
if (!gatewayId)
|
|
25
|
+
throw new Error("A gateway connected to hosted Dari needs DARI_GATEWAY_ID.");
|
|
26
|
+
if (!env.DARI_GATEWAY_ENCRYPTION_KEY?.trim()) {
|
|
27
|
+
throw new Error("A gateway connected to hosted Dari needs DARI_GATEWAY_ENCRYPTION_KEY to encrypt its plans' tokens.");
|
|
28
|
+
}
|
|
29
|
+
return { url, apiKey, gatewayId, gatewayName: env.DARI_GATEWAY_NAME?.trim() || hostname() };
|
|
30
|
+
}
|
|
31
|
+
/** The self-hosted platform on hosted routers, reporting requests to hosted Dari. */
|
|
32
|
+
export function createConnectedPlatform(deps) {
|
|
33
|
+
const platform = createSelfHostedPlatform(deps);
|
|
34
|
+
const hostedRouter = hostedRouters(deps.hosted, deps.fetch);
|
|
35
|
+
return {
|
|
36
|
+
...platform,
|
|
37
|
+
async resolveRouter(request) {
|
|
38
|
+
const router = await hostedRouter(request.routerId);
|
|
39
|
+
return await resolveSelfHostedRouter({
|
|
40
|
+
...deps,
|
|
41
|
+
config: { ...deps.config, routers: { [request.routerId]: router } },
|
|
42
|
+
prefixHits: (args) => deps.prefixes.hits(args),
|
|
43
|
+
}, request);
|
|
44
|
+
},
|
|
45
|
+
recordRequest(record) {
|
|
46
|
+
console.info("routing request", JSON.stringify(record.summary));
|
|
47
|
+
try {
|
|
48
|
+
deps.sync.enqueue(record.row);
|
|
49
|
+
}
|
|
50
|
+
catch (error) {
|
|
51
|
+
console.error("hosted Activity queue failed", error instanceof Error ? error.message : String(error));
|
|
52
|
+
}
|
|
53
|
+
},
|
|
54
|
+
link: undefined,
|
|
55
|
+
activity: undefined,
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
const ROUTER_CACHE_MS = 60_000;
|
|
59
|
+
/**
|
|
60
|
+
* A hosted router as this gateway serves it: its models, read from hosted's
|
|
61
|
+
* model list (cached for a minute), on the user's plans only.
|
|
62
|
+
*/
|
|
63
|
+
function hostedRouters(hosted, fetchImpl) {
|
|
64
|
+
const cache = new Map();
|
|
65
|
+
return async (routerId) => {
|
|
66
|
+
const cached = cache.get(routerId);
|
|
67
|
+
if (cached !== undefined && Date.now() - cached.readAt < ROUTER_CACHE_MS)
|
|
68
|
+
return cached.router;
|
|
69
|
+
let router;
|
|
70
|
+
try {
|
|
71
|
+
router = await readHostedRouter(hosted, fetchImpl, routerId);
|
|
72
|
+
}
|
|
73
|
+
catch (error) {
|
|
74
|
+
if (cached !== undefined)
|
|
75
|
+
return cached.router;
|
|
76
|
+
console.error("hosted router read failed", error instanceof Error ? error.message : String(error));
|
|
77
|
+
// A 424 hands the request to hosted, which reports its own error.
|
|
78
|
+
throw new HttpError(424, `Router ${routerId} could not be read from hosted Dari.`, "hosted_router_unavailable");
|
|
79
|
+
}
|
|
80
|
+
cache.set(routerId, { router, readAt: Date.now() });
|
|
81
|
+
return router;
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
async function readHostedRouter(hosted, fetchImpl, routerId) {
|
|
85
|
+
const prefix = routerId === DEFAULT_ROUTER_ALIAS ? "" : `/${encodeURIComponent(routerId)}`;
|
|
86
|
+
const response = await fetchImpl(`${hosted.url}${prefix}/v1/models`, {
|
|
87
|
+
headers: { authorization: `Bearer ${hosted.apiKey}` },
|
|
88
|
+
signal: AbortSignal.timeout(30_000),
|
|
89
|
+
});
|
|
90
|
+
if (!response.ok)
|
|
91
|
+
throw new Error(`HTTP ${response.status}`);
|
|
92
|
+
const catalog = await response.json();
|
|
93
|
+
const models = (catalog.models ?? []).flatMap((entry) => {
|
|
94
|
+
// `dari/routing` is the router itself, not one of its models.
|
|
95
|
+
const id = explicitModelId(entry.slug);
|
|
96
|
+
if (id === null)
|
|
97
|
+
return [];
|
|
98
|
+
const thinking = entry.supported_reasoning_levels
|
|
99
|
+
?.map((level) => level.effort === "none" ? "off" : level.effort)
|
|
100
|
+
.filter((level) => isReasoningEffort(level));
|
|
101
|
+
return [thinking?.length ? { id, thinking } : { id }];
|
|
102
|
+
});
|
|
103
|
+
if (models.length === 0)
|
|
104
|
+
throw new Error("it lists no models");
|
|
105
|
+
return parseGatewayConfig({
|
|
106
|
+
routers: {
|
|
107
|
+
[routerId]: { models, subscriptions: true, nativeCompaction: catalog.remote_compaction === "v2" },
|
|
108
|
+
},
|
|
109
|
+
}).routers[routerId];
|
|
110
|
+
}
|
|
111
|
+
// The routed calls a local plan may serve; anything else the gateway does
|
|
112
|
+
// not manage goes to hosted.
|
|
113
|
+
const ROUTED_CALL = /^(?:\/[^/]+)?(?:\/v1)?\/(?:chat\/completions|responses|messages)$/;
|
|
114
|
+
/**
|
|
115
|
+
* Serve a connected gateway's routed surface: `gateway` (the gateway's own
|
|
116
|
+
* handler on the connected platform) first, and hosted Dari for a request it
|
|
117
|
+
* cannot serve on a local plan. Health checks stay local; every request
|
|
118
|
+
* forwarded must carry a gateway key.
|
|
119
|
+
*/
|
|
120
|
+
export function connectedHandler(deps) {
|
|
121
|
+
return async (request) => {
|
|
122
|
+
const { pathname } = new URL(request.url);
|
|
123
|
+
if (pathname === "/healthz" || pathname === "/health" || pathname === "/api/hello") {
|
|
124
|
+
return await deps.gateway(request);
|
|
125
|
+
}
|
|
126
|
+
// Claude Code reads errors in Anthropic's shape, as the gateway answers them.
|
|
127
|
+
const fail = MESSAGES_CALL.test(pathname) ? anthropicErrorResponse : errorResponse;
|
|
128
|
+
try {
|
|
129
|
+
const anthropic = !request.headers.has("authorization") && request.headers.has("x-api-key");
|
|
130
|
+
const key = anthropic ? anthropicToken(request.headers) : bearerToken(request.headers);
|
|
131
|
+
if (gatewayKeyIndex(deps.gatewayKeys, key) === null) {
|
|
132
|
+
throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
catch (error) {
|
|
136
|
+
return fail(error);
|
|
137
|
+
}
|
|
138
|
+
const body = request.method === "GET" || request.method === "HEAD" ? null : await request.arrayBuffer();
|
|
139
|
+
if (request.method === "POST" && ROUTED_CALL.test(pathname)) {
|
|
140
|
+
const local = await deps.gateway(new Request(request.url, {
|
|
141
|
+
method: request.method,
|
|
142
|
+
headers: request.headers,
|
|
143
|
+
body,
|
|
144
|
+
signal: request.signal,
|
|
145
|
+
}));
|
|
146
|
+
if (!(await servedElsewhere(local)))
|
|
147
|
+
return local;
|
|
148
|
+
await local.body?.cancel();
|
|
149
|
+
// Hosted logs the request it serves; the local attempt is not one.
|
|
150
|
+
const requestId = local.headers.get("x-request-id");
|
|
151
|
+
if (requestId !== null)
|
|
152
|
+
deps.sync.discard(requestId);
|
|
153
|
+
}
|
|
154
|
+
return await forward(request, body, deps, fail);
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
const MESSAGES_CALL = /\/messages(?:\/count_tokens)?$/;
|
|
158
|
+
/**
|
|
159
|
+
* Whether a local response means no local plan could serve the request: none
|
|
160
|
+
* serves the router's models or the one asked for (424, or the explicit
|
|
161
|
+
* model's 400), or every one is at its limit (429).
|
|
162
|
+
*/
|
|
163
|
+
async function servedElsewhere(response) {
|
|
164
|
+
if (response.status === 424 || response.status === 429)
|
|
165
|
+
return true;
|
|
166
|
+
if (response.status !== 400)
|
|
167
|
+
return false;
|
|
168
|
+
const text = await response.clone().text();
|
|
169
|
+
return text.includes("model_not_enabled") || text.includes("is not enabled on this router");
|
|
170
|
+
}
|
|
171
|
+
// The request as the client sent it, on hosted Dari with the user's key.
|
|
172
|
+
async function forward(request, body, deps, fail) {
|
|
173
|
+
const url = new URL(request.url);
|
|
174
|
+
const headers = new Headers(request.headers);
|
|
175
|
+
for (const name of ["host", "authorization", "x-api-key", "content-length", "connection", "accept-encoding"]) {
|
|
176
|
+
headers.delete(name);
|
|
177
|
+
}
|
|
178
|
+
headers.set("authorization", `Bearer ${deps.hosted.apiKey}`);
|
|
179
|
+
let response;
|
|
180
|
+
try {
|
|
181
|
+
response = await deps.fetch(`${deps.hosted.url}${url.pathname}${url.search}`, {
|
|
182
|
+
method: request.method,
|
|
183
|
+
headers,
|
|
184
|
+
body,
|
|
185
|
+
redirect: "manual",
|
|
186
|
+
signal: request.signal,
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
catch {
|
|
190
|
+
return fail(new HttpError(502, "Hosted Dari could not be reached.", "hosted_unreachable"));
|
|
191
|
+
}
|
|
192
|
+
// The body arrives decoded; its length and encoding no longer apply.
|
|
193
|
+
const responseHeaders = new Headers(response.headers);
|
|
194
|
+
responseHeaders.delete("content-encoding");
|
|
195
|
+
responseHeaders.delete("content-length");
|
|
196
|
+
return new Response(response.body, { status: response.status, statusText: response.statusText, headers: responseHeaders });
|
|
197
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
import type { Database } from "bun:sqlite";
|
|
2
|
+
import type { HostedConnection } from "./connected.js";
|
|
3
|
+
import { type ConnectedAccount, type SubscriptionStore } from "./subscriptions/index.js";
|
|
4
|
+
/**
|
|
5
|
+
* What a gateway connected to hosted Dari tells it: its plans (metadata, never
|
|
6
|
+
* tokens) as one snapshot `PUT /v1/gateway/subscriptions` replaces, and the
|
|
7
|
+
* requests it served, for Activity, `POST /v1/gateway/requests`. Snapshots go
|
|
8
|
+
* a moment after a plan changes and at most once a minute for usage; request
|
|
9
|
+
* rows wait in a SQLite outbox, sent in batches with backoff until hosted
|
|
10
|
+
* takes them. Private plans are never reported.
|
|
11
|
+
*/
|
|
12
|
+
export declare class HostedSync {
|
|
13
|
+
private readonly db;
|
|
14
|
+
private readonly subscriptions;
|
|
15
|
+
private readonly hosted;
|
|
16
|
+
private readonly fetch;
|
|
17
|
+
private readonly now;
|
|
18
|
+
private snapshotTimer;
|
|
19
|
+
private snapshotDueAt;
|
|
20
|
+
private snapshotFailures;
|
|
21
|
+
private snapshots;
|
|
22
|
+
private lastSnapshotAt;
|
|
23
|
+
private drainTimer;
|
|
24
|
+
private draining;
|
|
25
|
+
private drainFailures;
|
|
26
|
+
private drainPausedUntil;
|
|
27
|
+
constructor(db: Database, subscriptions: SubscriptionStore, hosted: HostedConnection, fetch: typeof globalThis.fetch, now?: () => number);
|
|
28
|
+
/** Report the plans now and send waiting requests, then keep at it. */
|
|
29
|
+
start(): void;
|
|
30
|
+
stop(): void;
|
|
31
|
+
/** A plan was connected, removed, renamed, moved, held, or released. */
|
|
32
|
+
plansChanged(): void;
|
|
33
|
+
/** A plan reported usage or served a turn. */
|
|
34
|
+
usageChanged(): void;
|
|
35
|
+
/** Queue a served request's log row for hosted Activity. */
|
|
36
|
+
enqueue(row: Record<string, unknown>): void;
|
|
37
|
+
/** Drop a queued request's row: hosted served that request itself and logs its own. */
|
|
38
|
+
discard(requestId: string): void;
|
|
39
|
+
/** The plans hosted Dari shows for this gateway. */
|
|
40
|
+
snapshot(): Record<string, unknown>;
|
|
41
|
+
private scheduleSnapshot;
|
|
42
|
+
private putSnapshot;
|
|
43
|
+
/** Send the queued request rows a batch at a time, unless hosted failed lately. */
|
|
44
|
+
drain(): Promise<void>;
|
|
45
|
+
private drainDue;
|
|
46
|
+
private call;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* The user's plans hosted Dari holds on other computers and on Dari, for the
|
|
50
|
+
* check before a sign-in connects an account: `GET /v1/gateway/accounts`
|
|
51
|
+
* returns each one's provider, account identity, and where it lives, never a token.
|
|
52
|
+
*/
|
|
53
|
+
export declare function readHostedAccounts(hosted: HostedConnection, fetchImpl: typeof globalThis.fetch): Promise<ConnectedAccount[]>;
|