@mupt-ai/dari-gateway 1.0.360 → 1.0.362
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/ingress/client_harness.d.ts +6 -0
- package/dist/ingress/client_harness.js +17 -1
- package/dist/ingress/models.js +0 -3
- package/dist/models/runtime_overrides.js +5 -0
- package/dist/platform/platform.d.ts +2 -1
- package/dist/platform/routing_contract.d.ts +1 -1
- package/dist/platform/routing_contract.js +3 -3
- package/dist/providers/pi.js +10 -2
- package/dist/runtime/prepare_routed_completion.d.ts +1 -0
- package/dist/runtime/prepare_routed_completion.js +1 -0
- package/dist/runtime/routed_completion.js +2 -0
- package/dist/self_host/connected.d.ts +29 -16
- package/dist/self_host/connected.js +64 -68
- package/dist/self_host/hosted_sync.d.ts +0 -2
- package/dist/self_host/hosted_sync.js +2 -10
- package/dist/self_host/main.d.ts +2 -2
- package/dist/self_host/main.js +10 -9
- package/dist/self_host/resolve.d.ts +7 -4
- package/dist/self_host/resolve.js +72 -18
- package/dist/self_host/subscriptions/http.js +13 -3
- package/dist/self_host/subscriptions/store.d.ts +3 -15
- package/dist/self_host/subscriptions/store.js +11 -27
- package/dist/telemetry/report.js +4 -0
- package/dist/types.d.ts +1 -0
- package/package.json +2 -2
- package/src/ingress/client_harness.ts +18 -1
- package/src/ingress/models.ts +0 -3
- package/src/models/runtime_overrides.ts +4 -0
- package/src/platform/platform.ts +5 -4
- package/src/platform/routing_contract.ts +3 -3
- package/src/providers/pi.ts +10 -2
- package/src/runtime/prepare_routed_completion.ts +2 -0
- package/src/runtime/routed_completion.ts +2 -0
- package/src/self_host/connected.ts +102 -82
- package/src/self_host/hosted_sync.ts +2 -13
- package/src/self_host/main.ts +10 -9
- package/src/self_host/resolve.ts +75 -19
- package/src/self_host/subscriptions/http.ts +12 -3
- package/src/self_host/subscriptions/store.ts +11 -25
- package/src/telemetry/report.ts +3 -0
- package/src/types.ts +2 -0
|
@@ -1,5 +1,11 @@
|
|
|
1
1
|
import type { ClientHarness } from "../types.js";
|
|
2
|
+
export declare const CLIENT_HARNESS_HEADER = "x-dari-client-harness";
|
|
2
3
|
export declare const CLIENT_HARNESSES: readonly string[];
|
|
4
|
+
/**
|
|
5
|
+
* The headers of `CLIENT_HEADERS` the request carries, as the client sent
|
|
6
|
+
* them, so hosted Dari serving it for a connected gateway sees the same client.
|
|
7
|
+
*/
|
|
8
|
+
export declare function clientHeaders(headers: Headers): Record<string, string>;
|
|
3
9
|
/**
|
|
4
10
|
* The coding agent `x-dari-client-harness` names, as the Dari CLI does for a
|
|
5
11
|
* model list. The header is a claim, not proof.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const CLIENT_HARNESS_HEADER = "x-dari-client-harness";
|
|
1
|
+
export const CLIENT_HARNESS_HEADER = "x-dari-client-harness";
|
|
2
2
|
export const CLIENT_HARNESSES = [
|
|
3
3
|
"claude_code",
|
|
4
4
|
"codex",
|
|
@@ -8,6 +8,22 @@ export const CLIENT_HARNESSES = [
|
|
|
8
8
|
"openclaw",
|
|
9
9
|
"hermes",
|
|
10
10
|
];
|
|
11
|
+
// The headers a coding agent names itself with: Claude Code's user agent,
|
|
12
|
+
// app, session, and betas, and Muse Code's client id.
|
|
13
|
+
const CLIENT_HEADERS = ["user-agent", "x-app", "x-claude-code-session-id", "anthropic-beta", "x-client-id"];
|
|
14
|
+
/**
|
|
15
|
+
* The headers of `CLIENT_HEADERS` the request carries, as the client sent
|
|
16
|
+
* them, so hosted Dari serving it for a connected gateway sees the same client.
|
|
17
|
+
*/
|
|
18
|
+
export function clientHeaders(headers) {
|
|
19
|
+
const found = {};
|
|
20
|
+
for (const name of CLIENT_HEADERS) {
|
|
21
|
+
const value = headers.get(name);
|
|
22
|
+
if (value !== null)
|
|
23
|
+
found[name] = value;
|
|
24
|
+
}
|
|
25
|
+
return found;
|
|
26
|
+
}
|
|
11
27
|
/**
|
|
12
28
|
* The coding agent `x-dari-client-harness` names, as the Dari CLI does for a
|
|
13
29
|
* model list. The header is a claim, not proof.
|
package/dist/ingress/models.js
CHANGED
|
@@ -18,7 +18,6 @@ import { anthropicModelsResponse } from "./anthropic_models.js";
|
|
|
18
18
|
import { namedClientHarness } from "./client_harness.js";
|
|
19
19
|
import { codexModelsEtag, codexModelsResponse } from "./codex_models.js";
|
|
20
20
|
import { CANONICAL_ROUTER_MODEL, explicitModelSlug, LINK_CHILD_TOKEN_PREFIX } from "../protocol/input/router_model.js";
|
|
21
|
-
import { GATEWAY_ID_HEADER } from "../platform/routing_contract.js";
|
|
22
21
|
export async function handleModels(request, routerId) {
|
|
23
22
|
// Anthropic SDK clients always send anthropic-version, and API-key probes
|
|
24
23
|
// authenticate via x-api-key instead of a bearer Authorization header.
|
|
@@ -37,14 +36,12 @@ export async function handleModels(request, routerId) {
|
|
|
37
36
|
// names its own version in the query, as only Codex does.
|
|
38
37
|
const codexDirect = !anthropicClient && query.has("client_version");
|
|
39
38
|
const clientHarness = namedClientHarness(request.headers) ?? (codexDirect ? "codex" : undefined);
|
|
40
|
-
const gatewayId = request.headers.get(GATEWAY_ID_HEADER)?.trim();
|
|
41
39
|
let router;
|
|
42
40
|
try {
|
|
43
41
|
router = await resolveRouter({
|
|
44
42
|
routerId,
|
|
45
43
|
apiKey,
|
|
46
44
|
...(clientHarness ? { clientHarness } : {}),
|
|
47
|
-
...(gatewayId ? { gatewayId } : {}),
|
|
48
45
|
});
|
|
49
46
|
}
|
|
50
47
|
catch (error) {
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { canonicalModelId, isRecord } from "@mupt-ai/dari-router/policy-engine";
|
|
2
|
+
import { HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
|
|
2
3
|
import { gatewayFor } from "./gateways.js";
|
|
3
4
|
const MODEL_CONTEXT_OVERRIDES = {
|
|
4
5
|
// Selector and title models are not router candidate configs, so their
|
|
@@ -215,6 +216,10 @@ export function inputModalitiesOverride(modelId) {
|
|
|
215
216
|
return MODEL_INPUT_OVERRIDES[canonicalModelId(modelId)];
|
|
216
217
|
}
|
|
217
218
|
export function runtimeCompat(provider, registered, modelId) {
|
|
219
|
+
// Hosted Dari reads the thinking level from Anthropic's adaptive effort and
|
|
220
|
+
// calls the provider itself, so no model's own wire settings apply.
|
|
221
|
+
if (provider === HOSTED_DARI_PROVIDER)
|
|
222
|
+
return { forceAdaptiveThinking: true };
|
|
218
223
|
const canonical = modelId ? canonicalModelId(modelId) : undefined;
|
|
219
224
|
const compatOverride = canonical
|
|
220
225
|
? PROVIDER_MODEL_COMPAT_OVERRIDES[provider]?.[canonical] ?? MODEL_COMPAT_OVERRIDES[canonical]
|
|
@@ -494,7 +494,7 @@ export type ResolveRouterRequest = {
|
|
|
494
494
|
conversationId?: string;
|
|
495
495
|
includePublicEvalCatalog?: boolean;
|
|
496
496
|
clientHarness?: ClientHarness;
|
|
497
|
-
|
|
497
|
+
clientHeaders?: Record<string, string>;
|
|
498
498
|
provisional?: boolean;
|
|
499
499
|
};
|
|
500
500
|
export type ProviderCredentialRequest = {
|
|
@@ -572,6 +572,7 @@ export type RequestRecord = {
|
|
|
572
572
|
costUsd: number | null;
|
|
573
573
|
credentialId: string | null;
|
|
574
574
|
};
|
|
575
|
+
subscriptionCredentialId?: string;
|
|
575
576
|
router: RequestRecordRouter;
|
|
576
577
|
candidates: Array<{
|
|
577
578
|
model: string;
|
|
@@ -3,6 +3,6 @@
|
|
|
3
3
|
export const DEFAULT_ROUTER_ALIAS = "default";
|
|
4
4
|
// The most prefix hashes one router resolution looks up.
|
|
5
5
|
export const ROUTING_PREFIX_HASHES_MAX_COUNT = 200;
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
export const
|
|
6
|
+
// The provider id of hosted Dari when a gateway connected to it calls it for
|
|
7
|
+
// a model, as `dari/model/<id>` with the user's Dari key.
|
|
8
|
+
export const HOSTED_DARI_PROVIDER = "dari";
|
package/dist/providers/pi.js
CHANGED
|
@@ -11,6 +11,7 @@ import { openAIResponsesApi } from "@mupt-ai/pi-ai/api/openai-responses.lazy";
|
|
|
11
11
|
import { getBuiltinModel } from "@mupt-ai/pi-ai/providers/all";
|
|
12
12
|
import { REASONING_EFFORTS, isRecord, nativeModelId, providerForModel, } from "@mupt-ai/dari-router/policy-engine";
|
|
13
13
|
import { HttpError } from "../http/errors.js";
|
|
14
|
+
import { HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
|
|
14
15
|
import { effectiveContextWindow } from "../models/context_limits.js";
|
|
15
16
|
import { defaultBaseUrl } from "../models/provider_defaults.js";
|
|
16
17
|
import { contextWindowOverride, inputModalitiesOverride, providerThinkingLevelOverrides, runtimeCompat, withThinkingLevelOverrides, } from "../models/runtime_overrides.js";
|
|
@@ -193,8 +194,14 @@ export function modelMetadataLookup(configs) {
|
|
|
193
194
|
export function buildModel(pi, modelId, pricing, config) {
|
|
194
195
|
const provider = config?.provider ?? providerForModel(modelId);
|
|
195
196
|
const nativeId = config?.native_model_id ?? nativeModelId(modelId);
|
|
196
|
-
|
|
197
|
-
|
|
197
|
+
let registered = resolveModelMetadata(pi, provider, modelId, nativeId);
|
|
198
|
+
let id = registered?.id ?? (provider === "anthropic" ? nativeId.replace(/(?<=\d)\.(?=\d)/g, "-") : nativeId);
|
|
199
|
+
if (provider === HOSTED_DARI_PROVIDER) {
|
|
200
|
+
// Hosted Dari serves a model under its Dari id, as the model's own
|
|
201
|
+
// provider describes it.
|
|
202
|
+
registered = resolveModelMetadata(pi, providerForModel(modelId), modelId, nativeModelId(modelId));
|
|
203
|
+
id = nativeId;
|
|
204
|
+
}
|
|
198
205
|
const price = executionPricing(pricing, config);
|
|
199
206
|
const configuredThinkingLevels = config?.supported_thinking_levels;
|
|
200
207
|
// A null catalog value delegates to Pi's registry when it knows the model.
|
|
@@ -241,6 +248,7 @@ export function buildModel(pi, modelId, pricing, config) {
|
|
|
241
248
|
...(effectiveThinkingLevels
|
|
242
249
|
? { supportedThinkingLevels: [...effectiveThinkingLevels] }
|
|
243
250
|
: {}),
|
|
251
|
+
...(config?.headers ? { headers: config.headers } : {}),
|
|
244
252
|
fastMode: config?.fast_mode ?? false,
|
|
245
253
|
zeroDataRetention: config?.zdr ?? false,
|
|
246
254
|
};
|
|
@@ -37,5 +37,6 @@ export declare function prepareRoutedCompletion(args: {
|
|
|
37
37
|
clientRequestId: string | null;
|
|
38
38
|
tagsHeader: string | null;
|
|
39
39
|
clientHarness?: ClientHarness;
|
|
40
|
+
clientHeaders?: Record<string, string>;
|
|
40
41
|
harnessConversationIdentity?: HarnessConversationIdentity;
|
|
41
42
|
}): Promise<PreparedRoutedCompletion>;
|
|
@@ -24,6 +24,7 @@ export async function prepareRoutedCompletion(args) {
|
|
|
24
24
|
routerId: args.routerId,
|
|
25
25
|
apiKey: args.apiKey,
|
|
26
26
|
includePublicEvalCatalog: true,
|
|
27
|
+
clientHeaders: args.clientHeaders,
|
|
27
28
|
};
|
|
28
29
|
// Direct /v1 callers are authenticated by API key, so their canonical
|
|
29
30
|
// organization router is not known until this resolve completes. Fingerprint
|
|
@@ -3,6 +3,7 @@ import { isBackgroundRequest } from "../interaction/types.js";
|
|
|
3
3
|
import { explicitModelId } from "../protocol/input/router_model.js";
|
|
4
4
|
import { captureRequestError } from "../observability/errors.js";
|
|
5
5
|
import { assertAutoroutingAllowed, assertCreditAvailableBeforeRouting, routerSelectsModels } from "../telemetry/usage.js";
|
|
6
|
+
import { clientHeaders } from "../ingress/client_harness.js";
|
|
6
7
|
import { withModelMenuHint } from "./model_menu_hint.js";
|
|
7
8
|
import { prepareRoutedCompletion } from "./prepare_routed_completion.js";
|
|
8
9
|
import { runPreparedRoutedCompletion } from "./routed_runtime.js";
|
|
@@ -22,6 +23,7 @@ export async function handleRoutedCompletion(args) {
|
|
|
22
23
|
clientRequestId,
|
|
23
24
|
tagsHeader: args.request.headers.get("x-dari-tags"),
|
|
24
25
|
clientHarness: args.clientHarness,
|
|
26
|
+
clientHeaders: clientHeaders(args.request.headers),
|
|
25
27
|
harnessConversationIdentity: args.harnessConversationIdentity,
|
|
26
28
|
}).catch((error) => ({ error }));
|
|
27
29
|
if ("error" in prepared) {
|
|
@@ -1,21 +1,25 @@
|
|
|
1
1
|
import type { GatewayPlatform } from "../platform/platform.js";
|
|
2
|
+
import { type RouterConfig } from "./config.js";
|
|
2
3
|
import type { HostedSync } from "./hosted_sync.js";
|
|
3
4
|
import { createSelfHostedPlatform } from "./platform.js";
|
|
4
5
|
/**
|
|
5
6
|
* A self-hosted gateway connected to hosted Dari (the Dari CLI runs one for
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
* Dari with the user's Dari key, so agents see one router either way.
|
|
7
|
+
* every launch signed in to Dari): it serves every routed call itself, on the
|
|
8
|
+
* user's plans on this computer first and then on hosted Dari as a provider.
|
|
9
9
|
*
|
|
10
10
|
* - Routers are the user's hosted routers, by id (`/<router id>/v1/...`, or
|
|
11
|
-
* the default router at `/v1/...`)
|
|
12
|
-
*
|
|
13
|
-
* - A
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
11
|
+
* the default router at `/v1/...`), read from hosted Dari: every model, each
|
|
12
|
+
* with its sources (models/sources.ts), chosen by the hosted Auto Router API.
|
|
13
|
+
* - A model's plans on this computer serve it first. Whatever comes next that
|
|
14
|
+
* only Dari can serve (its own plans, the router's key, managed credits) is
|
|
15
|
+
* one candidate: hosted Dari, called for `dari/model/<id>` with the user's
|
|
16
|
+
* Dari key (resolve.ts).
|
|
17
|
+
* - Every other path the gateway does not manage itself, such as commit
|
|
18
|
+
* reports, goes to hosted with the user's Dari key.
|
|
19
|
+
* - The plans and the requests served here sync to hosted (hosted_sync.ts),
|
|
20
|
+
* which shows them in Accounts and Activity. Private plans serve, but
|
|
21
|
+
* neither they nor their requests sync; requests hosted Dari served are
|
|
22
|
+
* hosted's to log. Dari Link and Activity are hosted's, not served here.
|
|
19
23
|
*/
|
|
20
24
|
export type HostedConnection = {
|
|
21
25
|
url: string;
|
|
@@ -34,18 +38,27 @@ type SelfHostedPlatformDeps = Parameters<typeof createSelfHostedPlatform>[0];
|
|
|
34
38
|
export declare function createConnectedPlatform(deps: SelfHostedPlatformDeps & {
|
|
35
39
|
hosted: HostedConnection;
|
|
36
40
|
sync: HostedSync;
|
|
41
|
+
hostedRouter: HostedRouters;
|
|
37
42
|
}): GatewayPlatform;
|
|
43
|
+
/** A hosted router as this gateway serves it, read from hosted Dari (cached for a minute). */
|
|
44
|
+
/** A hosted router as this gateway serves it, and whether it uses custom rules. */
|
|
45
|
+
export type HostedRouterState = {
|
|
46
|
+
config: RouterConfig;
|
|
47
|
+
customRules: boolean;
|
|
48
|
+
};
|
|
49
|
+
export type HostedRouters = (routerId: string) => Promise<HostedRouterState>;
|
|
50
|
+
export declare function hostedRouters(hosted: HostedConnection, fetchImpl: typeof fetch): HostedRouters;
|
|
38
51
|
/**
|
|
39
|
-
* Serve a connected gateway
|
|
40
|
-
* handler on the connected platform)
|
|
41
|
-
*
|
|
42
|
-
*
|
|
52
|
+
* Serve a connected gateway: routed calls and model lists on `gateway` (the
|
|
53
|
+
* gateway's own handler on the connected platform), and every other path on
|
|
54
|
+
* hosted Dari with the user's Dari key. Health checks stay local; every other
|
|
55
|
+
* request must carry a gateway key.
|
|
43
56
|
*/
|
|
44
57
|
export declare function connectedHandler(deps: {
|
|
45
58
|
gateway: (request: Request) => Promise<Response>;
|
|
46
59
|
gatewayKeys: readonly string[];
|
|
47
60
|
hosted: HostedConnection;
|
|
48
|
-
|
|
61
|
+
hostedRouter: HostedRouters;
|
|
49
62
|
fetch: typeof fetch;
|
|
50
63
|
}): (request: Request) => Promise<Response>;
|
|
51
64
|
export {};
|
|
@@ -1,10 +1,8 @@
|
|
|
1
1
|
import { hostname } from "node:os";
|
|
2
|
-
import { isReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
|
|
3
2
|
import { anthropicToken, bearerToken } from "../http/auth.js";
|
|
4
3
|
import { errorResponse, HttpError } from "../http/errors.js";
|
|
5
4
|
import { anthropicErrorResponse } from "../ingress/anthropic_messages.js";
|
|
6
|
-
import { DEFAULT_ROUTER_ALIAS,
|
|
7
|
-
import { explicitModelId } from "../protocol/input/router_model.js";
|
|
5
|
+
import { DEFAULT_ROUTER_ALIAS, HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
|
|
8
6
|
import { parseGatewayConfig } from "./config.js";
|
|
9
7
|
import { createSelfHostedPlatform } from "./platform.js";
|
|
10
8
|
import { gatewayKeyIndex, resolveSelfHostedRouter } from "./resolve.js";
|
|
@@ -31,11 +29,10 @@ export function hostedConnectionFromEnv(env) {
|
|
|
31
29
|
/** The self-hosted platform on hosted routers, reporting requests to hosted Dari. */
|
|
32
30
|
export function createConnectedPlatform(deps) {
|
|
33
31
|
const platform = createSelfHostedPlatform(deps);
|
|
34
|
-
const hostedRouter = hostedRouters(deps.hosted, deps.fetch);
|
|
35
32
|
return {
|
|
36
33
|
...platform,
|
|
37
34
|
async resolveRouter(request) {
|
|
38
|
-
const router = await hostedRouter(request.routerId);
|
|
35
|
+
const router = (await deps.hostedRouter(request.routerId)).config;
|
|
39
36
|
return await resolveSelfHostedRouter({
|
|
40
37
|
...deps,
|
|
41
38
|
config: { ...deps.config, routers: { [request.routerId]: router } },
|
|
@@ -44,6 +41,16 @@ export function createConnectedPlatform(deps) {
|
|
|
44
41
|
},
|
|
45
42
|
recordRequest(record) {
|
|
46
43
|
console.info("routing request", JSON.stringify(record.summary));
|
|
44
|
+
// Hosted Dari logs the requests it served itself.
|
|
45
|
+
if (record.summary.selected_provider === HOSTED_DARI_PROVIDER)
|
|
46
|
+
return;
|
|
47
|
+
// A private plan's requests stay on this computer, as the plan does; so
|
|
48
|
+
// does one whose plan is gone, since it may have been private.
|
|
49
|
+
if (record.subscriptionCredentialId !== undefined) {
|
|
50
|
+
const plan = deps.subscriptions.get(record.subscriptionCredentialId);
|
|
51
|
+
if (plan === null || plan.private)
|
|
52
|
+
return;
|
|
53
|
+
}
|
|
47
54
|
try {
|
|
48
55
|
deps.sync.enqueue(record.row);
|
|
49
56
|
}
|
|
@@ -56,11 +63,7 @@ export function createConnectedPlatform(deps) {
|
|
|
56
63
|
};
|
|
57
64
|
}
|
|
58
65
|
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) {
|
|
66
|
+
export function hostedRouters(hosted, fetchImpl) {
|
|
64
67
|
const cache = new Map();
|
|
65
68
|
return async (routerId) => {
|
|
66
69
|
const cached = cache.get(routerId);
|
|
@@ -74,49 +77,48 @@ function hostedRouters(hosted, fetchImpl) {
|
|
|
74
77
|
if (cached !== undefined)
|
|
75
78
|
return cached.router;
|
|
76
79
|
console.error("hosted router read failed", error instanceof Error ? error.message : String(error));
|
|
77
|
-
|
|
78
|
-
throw new HttpError(424, `Router ${routerId} could not be read from hosted Dari.`, "hosted_router_unavailable");
|
|
80
|
+
throw new HttpError(502, `Router ${routerId} could not be read from hosted Dari.`, "hosted_router_unavailable");
|
|
79
81
|
}
|
|
80
82
|
cache.set(routerId, { router, readAt: Date.now() });
|
|
81
83
|
return router;
|
|
82
84
|
};
|
|
83
85
|
}
|
|
84
86
|
async function readHostedRouter(hosted, fetchImpl, routerId) {
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
87
|
+
let path = `/v1/gateway/routers/${encodeURIComponent(routerId)}`;
|
|
88
|
+
if (routerId === DEFAULT_ROUTER_ALIAS)
|
|
89
|
+
path = "/v1/gateway/router";
|
|
90
|
+
const response = await fetchImpl(`${hosted.url}${path}`, {
|
|
91
|
+
headers: { authorization: `Bearer ${hosted.apiKey}` },
|
|
89
92
|
signal: AbortSignal.timeout(30_000),
|
|
90
93
|
});
|
|
91
94
|
if (!response.ok)
|
|
92
95
|
throw new Error(`HTTP ${response.status}`);
|
|
93
|
-
const
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
const id = explicitModelId(entry.slug);
|
|
97
|
-
if (id === null)
|
|
98
|
-
return [];
|
|
99
|
-
const thinking = entry.supported_reasoning_levels
|
|
100
|
-
?.map((level) => level.effort === "none" ? "off" : level.effort)
|
|
101
|
-
.filter((level) => isReasoningEffort(level));
|
|
102
|
-
return [thinking?.length ? { id, thinking } : { id }];
|
|
103
|
-
});
|
|
104
|
-
if (models.length === 0)
|
|
105
|
-
throw new Error("it lists no models");
|
|
106
|
-
return parseGatewayConfig({
|
|
96
|
+
const router = await response.json();
|
|
97
|
+
// A model's null thinking offers every level it supports.
|
|
98
|
+
const config = parseGatewayConfig({
|
|
107
99
|
routers: {
|
|
108
|
-
[routerId]: {
|
|
100
|
+
[routerId]: {
|
|
101
|
+
models: router.models,
|
|
102
|
+
resetMinHours: router.reset_min_hours,
|
|
103
|
+
nativeCompaction: router.native_compaction,
|
|
104
|
+
zdr: router.zdr,
|
|
105
|
+
sessionPinning: router.session_pinning,
|
|
106
|
+
retries: router.retries,
|
|
107
|
+
roleModels: router.role_models,
|
|
108
|
+
rolePrompts: router.role_prompts,
|
|
109
|
+
},
|
|
109
110
|
},
|
|
110
111
|
}).routers[routerId];
|
|
112
|
+
return { config, customRules: router.custom_rules === true };
|
|
111
113
|
}
|
|
112
|
-
// The
|
|
113
|
-
//
|
|
114
|
-
const
|
|
114
|
+
// The calls this gateway serves itself: routed calls and model lists. Every
|
|
115
|
+
// other path goes to hosted.
|
|
116
|
+
const LOCAL_CALL = /^(?:\/[^/]+)?(?:\/v1)?\/(?:chat\/completions|responses|messages|models)$/;
|
|
115
117
|
/**
|
|
116
|
-
* Serve a connected gateway
|
|
117
|
-
* handler on the connected platform)
|
|
118
|
-
*
|
|
119
|
-
*
|
|
118
|
+
* Serve a connected gateway: routed calls and model lists on `gateway` (the
|
|
119
|
+
* gateway's own handler on the connected platform), and every other path on
|
|
120
|
+
* hosted Dari with the user's Dari key. Health checks stay local; every other
|
|
121
|
+
* request must carry a gateway key.
|
|
120
122
|
*/
|
|
121
123
|
export function connectedHandler(deps) {
|
|
122
124
|
return async (request) => {
|
|
@@ -136,49 +138,43 @@ export function connectedHandler(deps) {
|
|
|
136
138
|
catch (error) {
|
|
137
139
|
return fail(error);
|
|
138
140
|
}
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
signal: request.signal,
|
|
146
|
-
}));
|
|
147
|
-
if (!(await servedElsewhere(local)))
|
|
148
|
-
return local;
|
|
149
|
-
await local.body?.cancel();
|
|
150
|
-
// Hosted logs the request it serves; the local attempt is not one.
|
|
151
|
-
const requestId = local.headers.get("x-request-id");
|
|
152
|
-
if (requestId !== null)
|
|
153
|
-
deps.sync.discard(requestId);
|
|
141
|
+
if (!LOCAL_CALL.test(pathname))
|
|
142
|
+
return await forward(request, deps, fail);
|
|
143
|
+
// Custom routing rules run only on hosted Dari: it serves those routers'
|
|
144
|
+
// calls whole.
|
|
145
|
+
if (request.method === "POST" && await usesCustomRules(deps.hostedRouter, pathname)) {
|
|
146
|
+
return await forward(request, deps, fail);
|
|
154
147
|
}
|
|
155
|
-
return await
|
|
148
|
+
return await deps.gateway(request);
|
|
156
149
|
};
|
|
157
150
|
}
|
|
158
151
|
const MESSAGES_CALL = /\/messages(?:\/count_tokens)?$/;
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
if (
|
|
152
|
+
// Whether the router a routed call's path names uses custom rules. A router
|
|
153
|
+
// that cannot be read goes to hosted Dari too: it may use them, and only Dari
|
|
154
|
+
// can run them.
|
|
155
|
+
async function usesCustomRules(hostedRouter, pathname) {
|
|
156
|
+
let routerId = DEFAULT_ROUTER_ALIAS;
|
|
157
|
+
const first = pathname.split("/")[1];
|
|
158
|
+
if (first !== undefined && first !== "v1" && !LOCAL_CALL.test(`/${first}`))
|
|
159
|
+
routerId = first;
|
|
160
|
+
try {
|
|
161
|
+
return (await hostedRouter(routerId)).customRules;
|
|
162
|
+
}
|
|
163
|
+
catch {
|
|
166
164
|
return true;
|
|
167
|
-
|
|
168
|
-
return false;
|
|
169
|
-
const text = await response.clone().text();
|
|
170
|
-
return text.includes("model_not_enabled") || text.includes("is not enabled on this router");
|
|
165
|
+
}
|
|
171
166
|
}
|
|
172
167
|
// The request as the client sent it, on hosted Dari with the user's key.
|
|
173
|
-
async function forward(request,
|
|
168
|
+
async function forward(request, deps, fail) {
|
|
174
169
|
const url = new URL(request.url);
|
|
175
170
|
const headers = new Headers(request.headers);
|
|
176
171
|
for (const name of ["host", "authorization", "x-api-key", "content-length", "connection", "accept-encoding"]) {
|
|
177
172
|
headers.delete(name);
|
|
178
173
|
}
|
|
179
174
|
headers.set("authorization", `Bearer ${deps.hosted.apiKey}`);
|
|
180
|
-
|
|
181
|
-
|
|
175
|
+
let body = null;
|
|
176
|
+
if (request.method !== "GET" && request.method !== "HEAD")
|
|
177
|
+
body = await request.arrayBuffer();
|
|
182
178
|
let response;
|
|
183
179
|
try {
|
|
184
180
|
response = await deps.fetch(`${deps.hosted.url}${url.pathname}${url.search}`, {
|
|
@@ -34,8 +34,6 @@ export declare class HostedSync {
|
|
|
34
34
|
usageChanged(): void;
|
|
35
35
|
/** Queue a served request's log row for hosted Activity. */
|
|
36
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
37
|
/** The plans hosted Dari shows for this gateway. */
|
|
40
38
|
snapshot(): Record<string, unknown>;
|
|
41
39
|
private scheduleSnapshot;
|
|
@@ -12,10 +12,7 @@ const USAGE_INTERVAL_MS = 60_000;
|
|
|
12
12
|
const HEARTBEAT_MS = 60 * 60_000;
|
|
13
13
|
const RETRY_BASE_MS = 5_000;
|
|
14
14
|
const RETRY_MAX_MS = 15 * 60_000;
|
|
15
|
-
// Queued rows wait at least this long, so a request handed on to hosted can
|
|
16
|
-
// take its own row back out first (`discard`).
|
|
17
15
|
const DRAIN_INTERVAL_MS = 2_000;
|
|
18
|
-
const SETTLE_MS = 1_000;
|
|
19
16
|
/**
|
|
20
17
|
* What a gateway connected to hosted Dari tells it: its plans (metadata, never
|
|
21
18
|
* tokens) as one snapshot `PUT /v1/gateway/subscriptions` replaces, and the
|
|
@@ -88,10 +85,6 @@ export class HostedSync {
|
|
|
88
85
|
}
|
|
89
86
|
this.db.run("INSERT INTO hosted_request_outbox (row_json, queued_at) VALUES (?, ?)", [json, this.now()]);
|
|
90
87
|
}
|
|
91
|
-
/** Drop a queued request's row: hosted served that request itself and logs its own. */
|
|
92
|
-
discard(requestId) {
|
|
93
|
-
this.db.run("DELETE FROM hosted_request_outbox WHERE json_extract(row_json, '$.request_id') = ?", [requestId]);
|
|
94
|
-
}
|
|
95
88
|
/** The plans hosted Dari shows for this gateway. */
|
|
96
89
|
snapshot() {
|
|
97
90
|
const now = new Date(this.now());
|
|
@@ -141,9 +134,8 @@ export class HostedSync {
|
|
|
141
134
|
async drainDue() {
|
|
142
135
|
while (this.now() >= this.drainPausedUntil) {
|
|
143
136
|
const due = this.db
|
|
144
|
-
.query("SELECT id, row_json FROM hosted_request_outbox
|
|
145
|
-
|
|
146
|
-
.all(this.now() - SETTLE_MS, MAX_BATCH_ROWS);
|
|
137
|
+
.query("SELECT id, row_json FROM hosted_request_outbox ORDER BY id LIMIT ?")
|
|
138
|
+
.all(MAX_BATCH_ROWS);
|
|
147
139
|
const batch = [];
|
|
148
140
|
let bytes = 0;
|
|
149
141
|
for (const row of due) {
|
package/dist/self_host/main.d.ts
CHANGED
|
@@ -27,8 +27,8 @@
|
|
|
27
27
|
* - `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY`: connect the gateway to hosted
|
|
28
28
|
* Dari (connected.ts), with `DARI_GATEWAY_ID`, `DARI_GATEWAY_NAME`, and
|
|
29
29
|
* `DARI_GATEWAY_ENCRYPTION_KEY`. It then serves the user's hosted routers on
|
|
30
|
-
* its own plans
|
|
31
|
-
*
|
|
30
|
+
* its own plans and then on hosted Dari, and syncs its plans and requests
|
|
31
|
+
* there; Dari Link and Activity are hosted's.
|
|
32
32
|
*/
|
|
33
33
|
export declare function startSelfHostedGateway(env?: Record<string, string>): Promise<{
|
|
34
34
|
server: import("../http/http2_server.js").Http2RoutingServer | Bun.Server<undefined>;
|
package/dist/self_host/main.js
CHANGED
|
@@ -9,7 +9,7 @@ import { installShutdownHandlers, startServer } from "../http/serve.js";
|
|
|
9
9
|
import { createAutoRoutingSelectorBackend } from "../strategies/auto_routing_selector.js";
|
|
10
10
|
import { createPrioritySelectorBackend } from "../strategies/priority_selector.js";
|
|
11
11
|
import { ActivityStore } from "./activity_store.js";
|
|
12
|
-
import { connectedHandler, createConnectedPlatform, hostedConnectionFromEnv } from "./connected.js";
|
|
12
|
+
import { connectedHandler, createConnectedPlatform, hostedConnectionFromEnv, hostedRouters } from "./connected.js";
|
|
13
13
|
import { HostedSync, readHostedAccounts } from "./hosted_sync.js";
|
|
14
14
|
import { createSelfHostedPlatform } from "./platform.js";
|
|
15
15
|
import { checkProviderKey } from "../providers/key_check.js";
|
|
@@ -59,8 +59,8 @@ const IDLE_USAGE_INTERVAL_MS = 5 * 60_000;
|
|
|
59
59
|
* - `DARI_HOSTED_URL` and `DARI_HOSTED_API_KEY`: connect the gateway to hosted
|
|
60
60
|
* Dari (connected.ts), with `DARI_GATEWAY_ID`, `DARI_GATEWAY_NAME`, and
|
|
61
61
|
* `DARI_GATEWAY_ENCRYPTION_KEY`. It then serves the user's hosted routers on
|
|
62
|
-
* its own plans
|
|
63
|
-
*
|
|
62
|
+
* its own plans and then on hosted Dari, and syncs its plans and requests
|
|
63
|
+
* there; Dari Link and Activity are hosted's.
|
|
64
64
|
*/
|
|
65
65
|
export async function startSelfHostedGateway(env = process.env) {
|
|
66
66
|
const hosted = hostedConnectionFromEnv(env);
|
|
@@ -84,8 +84,7 @@ export async function startSelfHostedGateway(env = process.env) {
|
|
|
84
84
|
if (secrets === null) {
|
|
85
85
|
console.warn("dari-gateway stores subscription tokens unencrypted; set DARI_GATEWAY_ENCRYPTION_KEY (openssl rand -base64 32) to encrypt them");
|
|
86
86
|
}
|
|
87
|
-
|
|
88
|
-
const subscriptions = new SubscriptionStore(db, secrets, { privatePlansServe: hosted === null });
|
|
87
|
+
const subscriptions = new SubscriptionStore(db, secrets);
|
|
89
88
|
const prefixes = new PrefixStore(db);
|
|
90
89
|
const sessionPins = new SessionPinStore(db);
|
|
91
90
|
const routerModels = new RouterModelStore(db);
|
|
@@ -104,6 +103,8 @@ export async function startSelfHostedGateway(env = process.env) {
|
|
|
104
103
|
const providerApiKey = async (provider) => (await piModels.getAuth(provider))?.auth.apiKey;
|
|
105
104
|
const autoRoutingKey = hosted?.apiKey ?? env.DARI_AUTO_ROUTING_API_KEY?.trim();
|
|
106
105
|
const sync = hosted === null ? null : new HostedSync(db, subscriptions, hosted, fetch);
|
|
106
|
+
// The hosted router, read once a minute, for both serving and routing calls.
|
|
107
|
+
const hostedRouter = hosted === null ? null : hostedRouters(hosted, fetch);
|
|
107
108
|
const baseUrls = providerBaseUrls(config.providers);
|
|
108
109
|
if (sync !== null) {
|
|
109
110
|
subscriptions.onChange = (change) => change === "usage" ? sync.usageChanged() : sync.plansChanged();
|
|
@@ -123,9 +124,9 @@ export async function startSelfHostedGateway(env = process.env) {
|
|
|
123
124
|
env,
|
|
124
125
|
fetch,
|
|
125
126
|
};
|
|
126
|
-
const platform = hosted === null || sync === null
|
|
127
|
+
const platform = hosted === null || sync === null || hostedRouter === null
|
|
127
128
|
? createSelfHostedPlatform(platformDeps)
|
|
128
|
-
: createConnectedPlatform({ ...platformDeps, hosted, sync });
|
|
129
|
+
: createConnectedPlatform({ ...platformDeps, hosted, sync, hostedRouter });
|
|
129
130
|
// A model without a credential is dropped at request time, so a missing key
|
|
130
131
|
// would otherwise surface only as a 424 on the first request.
|
|
131
132
|
const warnWithoutCredentials = async (routerId, router) => {
|
|
@@ -156,9 +157,9 @@ export async function startSelfHostedGateway(env = process.env) {
|
|
|
156
157
|
})
|
|
157
158
|
: createPrioritySelectorBackend();
|
|
158
159
|
const routed = createRequestHandler({ platform, selectorBackend });
|
|
159
|
-
const gateway = hosted === null || sync === null
|
|
160
|
+
const gateway = hosted === null || sync === null || hostedRouter === null
|
|
160
161
|
? routed
|
|
161
|
-
: connectedHandler({ gateway: routed, gatewayKeys, hosted,
|
|
162
|
+
: connectedHandler({ gateway: routed, gatewayKeys, hosted, hostedRouter, fetch });
|
|
162
163
|
// Subscriptions, model lists, and router specs are managed with any gateway
|
|
163
164
|
// key; every other path is the gateway's own.
|
|
164
165
|
const handler = async (request) => {
|
|
@@ -2,6 +2,7 @@ import { type RouterPrefixHit } from "@mupt-ai/dari-router/policy-engine";
|
|
|
2
2
|
import type { ResolveRouterRequest } from "../platform/platform.js";
|
|
3
3
|
import type { ResolvedRouter } from "../types.js";
|
|
4
4
|
import { type GatewayConfig, type RouterConfig } from "./config.js";
|
|
5
|
+
import type { HostedConnection } from "./connected.js";
|
|
5
6
|
import type { SqliteLinkStore } from "../link/sqlite_store.js";
|
|
6
7
|
import type { RouterModelStore } from "./router_models.js";
|
|
7
8
|
import { type RouterSpecStore } from "./router_specs.js";
|
|
@@ -24,14 +25,16 @@ export type SelfHostedResolverDeps = {
|
|
|
24
25
|
autoRouting: boolean;
|
|
25
26
|
env: Record<string, string | undefined>;
|
|
26
27
|
fetch: OAuthFetch;
|
|
28
|
+
hosted?: HostedConnection;
|
|
27
29
|
};
|
|
28
30
|
/**
|
|
29
31
|
* Resolve a configured router for one request. Each model is served by the
|
|
30
32
|
* connected personal subscriptions that serve it, when the router allows them,
|
|
31
|
-
* in plan order (see models/subscriptions.ts), then by its provider's API key
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
* list on the router is served that
|
|
33
|
+
* in plan order (see models/subscriptions.ts), then by its provider's API key
|
|
34
|
+
* (on a connected gateway, by hosted Dari): the first available serves and
|
|
35
|
+
* the rest fail over within the request. Models nothing can serve are left
|
|
36
|
+
* out. A coding agent with its own model list on the router is served that
|
|
37
|
+
* list.
|
|
35
38
|
*
|
|
36
39
|
* A Dari Link token is served apart from any router, on its grant's plans and
|
|
37
40
|
* API keys alone: `dari/routing` chooses among every catalog model they
|