@mupt-ai/dari-gateway 1.0.339 → 1.0.341
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 +9 -7
- package/dist/index.d.ts +1 -1
- package/dist/link/assets.js +7 -0
- package/dist/link/budget.d.ts +18 -7
- package/dist/link/budget.js +58 -16
- package/dist/link/endpoints.js +64 -45
- package/dist/link/errors.js +4 -1
- package/dist/link/self_hosted.d.ts +3 -1
- package/dist/link/self_hosted.js +25 -9
- package/dist/link/service.d.ts +4 -4
- package/dist/link/service.js +41 -22
- package/dist/models/catalog.js +1 -0
- package/dist/models/execution_provider.d.ts +6 -1
- package/dist/models/execution_provider.js +12 -0
- package/dist/models/provider_defaults.js +9 -0
- package/dist/models/provider_models.json +217 -0
- package/dist/models/subscriptions.d.ts +5 -0
- package/dist/models/subscriptions.js +21 -2
- package/dist/platform/platform.d.ts +11 -7
- package/dist/providers/execution.d.ts +5 -0
- package/dist/providers/execution.js +12 -2
- package/dist/providers/github_copilot.d.ts +8 -0
- package/dist/providers/github_copilot.js +21 -0
- package/dist/providers/pi.js +3 -0
- package/dist/providers/provider_attempt_runner.d.ts +2 -0
- package/dist/providers/provider_attempt_runner.js +9 -0
- package/dist/providers/provider_call.js +6 -2
- package/dist/providers/subscription_limits.d.ts +6 -5
- package/dist/providers/subscription_limits.js +20 -9
- package/dist/runtime/routed_runtime.js +68 -3
- package/dist/self_host/resolve.d.ts +11 -9
- package/dist/self_host/resolve.js +249 -182
- package/dist/self_host/subscriptions/index.d.ts +6 -5
- package/dist/self_host/subscriptions/index.js +6 -5
- package/dist/self_host/subscriptions/oauth.d.ts +7 -3
- package/dist/self_host/subscriptions/oauth.js +195 -5
- package/dist/self_host/subscriptions/store.js +3 -0
- package/dist/telemetry/prefix_state.d.ts +1 -0
- package/dist/telemetry/prefix_state.js +1 -1
- package/dist/telemetry/report.js +2 -3
- package/dist/types.d.ts +6 -2
- package/package.json +2 -2
- package/src/index.ts +1 -1
- package/src/link/assets.ts +7 -0
- package/src/link/budget.ts +53 -18
- package/src/link/endpoints.ts +66 -45
- package/src/link/errors.ts +4 -1
- package/src/link/self_hosted.ts +26 -8
- package/src/link/service.ts +45 -23
- package/src/models/catalog.ts +1 -0
- package/src/models/execution_provider.ts +24 -1
- package/src/models/provider_defaults.ts +9 -0
- package/src/models/provider_models.json +217 -0
- package/src/models/subscriptions.ts +22 -2
- package/src/platform/platform.ts +13 -8
- package/src/providers/execution.ts +22 -2
- package/src/providers/github_copilot.ts +24 -0
- package/src/providers/pi.ts +2 -0
- package/src/providers/provider_attempt_runner.ts +15 -0
- package/src/providers/provider_call.ts +6 -2
- package/src/providers/subscription_limits.ts +20 -10
- package/src/runtime/routed_runtime.ts +79 -3
- package/src/self_host/resolve.ts +255 -187
- package/src/self_host/subscriptions/index.ts +7 -4
- package/src/self_host/subscriptions/oauth.ts +264 -8
- package/src/self_host/subscriptions/store.ts +3 -0
- package/src/telemetry/prefix_state.ts +4 -1
- package/src/telemetry/report.ts +2 -3
- package/src/types.ts +27 -3
package/src/self_host/resolve.ts
CHANGED
|
@@ -5,17 +5,28 @@ import {
|
|
|
5
5
|
nativeModelId,
|
|
6
6
|
providerForModel,
|
|
7
7
|
type ReasoningEffort,
|
|
8
|
+
type RouterModelPrice,
|
|
8
9
|
type RouterPrefixHit,
|
|
9
10
|
} from "@mupt-ai/dari-router/policy-engine";
|
|
10
11
|
import { HttpError } from "../http/errors.js";
|
|
11
12
|
import type { ResolveRouterRequest } from "../platform/platform.js";
|
|
12
13
|
import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
13
|
-
import {
|
|
14
|
-
|
|
14
|
+
import {
|
|
15
|
+
codexModelConfig,
|
|
16
|
+
modelSubscriptions,
|
|
17
|
+
subscriptionClient,
|
|
18
|
+
subscriptionModelProvider,
|
|
19
|
+
} from "../models/subscriptions.js";
|
|
20
|
+
import { CANONICAL_MODELS, otherModelProviders, providerModel } from "../models/canonical.js";
|
|
15
21
|
import { gatewayFor } from "../models/gateways.js";
|
|
16
22
|
import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
|
|
17
|
-
import { registeredModelPrice } from "../providers/pi.js";
|
|
18
|
-
import type {
|
|
23
|
+
import { buildModel, pi, registeredModelPrice } from "../providers/pi.js";
|
|
24
|
+
import type {
|
|
25
|
+
LinkUnavailable,
|
|
26
|
+
ModelFallback,
|
|
27
|
+
ResolvedRouter,
|
|
28
|
+
ResolvedRouterModelConfig,
|
|
29
|
+
} from "../types.js";
|
|
19
30
|
import {
|
|
20
31
|
allRouterModels,
|
|
21
32
|
modelProvider,
|
|
@@ -26,6 +37,7 @@ import {
|
|
|
26
37
|
} from "./config.js";
|
|
27
38
|
import type { ActiveLinkGrant } from "../link/grants.js";
|
|
28
39
|
import type { SqliteLinkStore } from "../link/sqlite_store.js";
|
|
40
|
+
import { linkSubscription } from "../link/self_hosted.js";
|
|
29
41
|
import { linkTokenGrant } from "../link/service.js";
|
|
30
42
|
import type { RouterModelStore } from "./router_models.js";
|
|
31
43
|
import { servedRouter, type RouterSpecStore } from "./router_specs.js";
|
|
@@ -67,18 +79,18 @@ export type SelfHostedResolverDeps = {
|
|
|
67
79
|
fetch: OAuthFetch;
|
|
68
80
|
};
|
|
69
81
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
};
|
|
82
|
+
// One way to serve a model: a connected plan, or its provider's API key.
|
|
83
|
+
type Candidate =
|
|
84
|
+
| { provider: string; plan: SubscriptionCredential }
|
|
85
|
+
| { provider: string; key: string };
|
|
75
86
|
|
|
76
87
|
/**
|
|
77
|
-
* Resolve a configured router for one request. Each
|
|
78
|
-
* connected personal
|
|
79
|
-
*
|
|
80
|
-
*
|
|
81
|
-
*
|
|
88
|
+
* Resolve a configured router for one request. Each model is served by the
|
|
89
|
+
* connected personal subscriptions that serve it, when the router allows them,
|
|
90
|
+
* in plan order (see models/subscriptions.ts), then by its provider's API key:
|
|
91
|
+
* the first available serves and the rest fail over within the request.
|
|
92
|
+
* Models nothing can serve are left out. A coding agent with its own model
|
|
93
|
+
* list on the router is served that list.
|
|
82
94
|
*
|
|
83
95
|
* A Dari Link token is served apart from any router, on its grant's plans and
|
|
84
96
|
* API keys alone: `dari/routing` chooses among every catalog model they
|
|
@@ -90,7 +102,7 @@ export async function resolveSelfHostedRouter(
|
|
|
90
102
|
request: ResolveRouterRequest,
|
|
91
103
|
): Promise<ResolvedRouter> {
|
|
92
104
|
const keyIndex = gatewayKeyIndex(deps.gatewayKeys, request.apiKey);
|
|
93
|
-
const grant = keyIndex === null ? await linkTokenGrant(deps.links, request.apiKey) : null;
|
|
105
|
+
const grant = keyIndex === null ? await linkTokenGrant(deps.links, { plansWithIds: async (ids) => deps.subscriptions.withIds(new Set(ids)).map(linkSubscription) }, request.apiKey) : null;
|
|
94
106
|
if (keyIndex === null && grant === null) {
|
|
95
107
|
throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
|
|
96
108
|
}
|
|
@@ -112,115 +124,57 @@ export async function resolveSelfHostedRouter(
|
|
|
112
124
|
const listed = grant === null ? routed : grantModels(grant, routed, granted, grantedKeys);
|
|
113
125
|
const now = new Date();
|
|
114
126
|
const servable = grant === null ? undefined : new Set(grant.credentialIds);
|
|
115
|
-
|
|
116
|
-
const
|
|
117
|
-
for (const provider of new Set(listed.map(modelProvider))) {
|
|
118
|
-
// A grant uses the subscriptions its user chose, whatever the router allows.
|
|
119
|
-
const subscription = router?.subscriptions || grant !== null
|
|
120
|
-
? subscriptionProviderFor(provider, request.clientHarness)
|
|
121
|
-
: null;
|
|
122
|
-
const active = subscription === null
|
|
123
|
-
? null
|
|
124
|
-
: deps.subscriptions.selectCredential(subscription, request.conversationId, now, servable);
|
|
125
|
-
if (active !== null) {
|
|
126
|
-
credentials.set(provider, {
|
|
127
|
-
// A provisional resolve's credentials never serve, so it neither marks
|
|
128
|
-
// the plan used nor refreshes its token.
|
|
129
|
-
key: request.provisional === true
|
|
130
|
-
? active.accessToken
|
|
131
|
-
: await freshAccessToken(deps.subscriptions, active, { fetch: deps.fetch }),
|
|
132
|
-
source: "subscription",
|
|
133
|
-
subscription: active,
|
|
134
|
-
});
|
|
135
|
-
continue;
|
|
136
|
-
}
|
|
137
|
-
if (grant !== null) {
|
|
138
|
-
// A plan first; else the key the user added for the provider.
|
|
139
|
-
const key = grantedKeys.get(provider);
|
|
140
|
-
credentials.set(provider, key === undefined ? null : { key, source: "user" });
|
|
141
|
-
continue;
|
|
142
|
-
}
|
|
143
|
-
if (subscription !== null && deps.subscriptions.list(subscription).length > 0) exhausted.add(subscription);
|
|
144
|
-
const apiKey = await configuredProviderApiKey(deps, provider);
|
|
145
|
-
credentials.set(provider, apiKey ? { key: apiKey, source: "user" } : null);
|
|
146
|
-
}
|
|
127
|
+
// A grant uses the subscriptions its user chose, whatever the router allows.
|
|
128
|
+
const plansServe = router?.subscriptions === true || grant !== null;
|
|
147
129
|
|
|
148
|
-
//
|
|
149
|
-
|
|
150
|
-
const
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
? {}
|
|
154
|
-
: providersUnavailable(
|
|
155
|
-
granted.map((credential) => ({ kind: credential.provider, unavailableUntil: credential.unavailableUntil })),
|
|
156
|
-
[...credentials].filter(([, credential]) => credential === null).map(([provider]) => provider),
|
|
157
|
-
request.clientHarness,
|
|
158
|
-
now,
|
|
159
|
-
);
|
|
160
|
-
const models = [];
|
|
161
|
-
for (const model of listed) {
|
|
162
|
-
const credential = credentials.get(modelProvider(model));
|
|
163
|
-
if (credential == null) continue;
|
|
164
|
-
const plan = credential.subscription;
|
|
165
|
-
const hold = plan === undefined ? undefined : activeModelHolds(plan, now).find((held) => held.model === model.id);
|
|
166
|
-
if (plan === undefined || hold === undefined) {
|
|
167
|
-
models.push(model);
|
|
168
|
-
continue;
|
|
130
|
+
// The plan of each kind that serves this conversation, chosen once.
|
|
131
|
+
const conversationPlans = new Map<SubscriptionProvider, SubscriptionCredential | null>();
|
|
132
|
+
const conversationPlan = (kind: SubscriptionProvider) => {
|
|
133
|
+
if (!conversationPlans.has(kind)) {
|
|
134
|
+
conversationPlans.set(kind, deps.subscriptions.selectCredential(kind, request.conversationId, now, servable));
|
|
169
135
|
}
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
136
|
+
return conversationPlans.get(kind)!;
|
|
137
|
+
};
|
|
138
|
+
// The conversation's plan of a kind for a model, or with that model held at
|
|
139
|
+
// its own limit there, another plan of the kind that serves it.
|
|
140
|
+
const planFor = (kind: SubscriptionProvider, modelId: string) => {
|
|
141
|
+
const active = conversationPlan(kind);
|
|
142
|
+
if (active !== null && !activeModelHolds(active, now).some((hold) => hold.model === modelId)) return active;
|
|
143
|
+
return deps.subscriptions.selectCredential(kind, undefined, now, servable, modelId);
|
|
144
|
+
};
|
|
145
|
+
const tokens = new Map<string, Promise<string>>();
|
|
146
|
+
const planToken = (plan: SubscriptionCredential) => {
|
|
147
|
+
// A provisional resolve's credentials never serve, so it neither marks
|
|
148
|
+
// the plan used nor refreshes its token.
|
|
149
|
+
if (request.provisional === true) return Promise.resolve(plan.accessToken);
|
|
150
|
+
if (!tokens.has(plan.id)) {
|
|
151
|
+
tokens.set(plan.id, conversationPlans.get(plan.provider)?.id === plan.id
|
|
152
|
+
? freshAccessToken(deps.subscriptions, plan, { fetch: deps.fetch })
|
|
153
|
+
// A model-only failover must not move the provider-wide rotation anchor.
|
|
154
|
+
: refreshedAccessToken(deps.subscriptions, plan, { fetch: deps.fetch }));
|
|
182
155
|
}
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
156
|
+
return tokens.get(plan.id)!;
|
|
157
|
+
};
|
|
158
|
+
const apiKeys = new Map<string, Promise<string | undefined>>();
|
|
159
|
+
const apiKey = (provider: string) => {
|
|
160
|
+
if (grant !== null) return Promise.resolve(grantedKeys.get(provider));
|
|
161
|
+
if (!apiKeys.has(provider)) apiKeys.set(provider, configuredProviderApiKey(deps, provider));
|
|
162
|
+
return apiKeys.get(provider)!;
|
|
163
|
+
};
|
|
186
164
|
|
|
187
|
-
// A grant with a gateway key serves the gateway's models by name, listed or not.
|
|
188
|
-
const gatewayKeyed = [...grantedKeys.keys()].some((provider) => gatewayFor(provider) !== undefined);
|
|
189
|
-
if (models.length === 0 && !gatewayKeyed) {
|
|
190
|
-
if (grant !== null) throw linkNothingServed(linkUnavailable, grant.pins);
|
|
191
|
-
const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
|
|
192
|
-
throw unavailableRouterError(request.routerId, exhausted, missing);
|
|
193
|
-
}
|
|
194
165
|
const resolved: ResolvedRouter = {
|
|
195
166
|
// A grant's requests and prefix state are its own, apart from any router.
|
|
196
167
|
router_id: grant?.id ?? request.routerId,
|
|
197
168
|
organization_id: SELF_HOSTED_ORGANIZATION_ID,
|
|
198
169
|
api_key_id: grant === null ? `gateway_key_${keyIndex! + 1}` : grant.id,
|
|
199
170
|
attributed_user_id: SELF_HOSTED_USER_ID,
|
|
200
|
-
enabled_models:
|
|
171
|
+
enabled_models: [],
|
|
201
172
|
routing_listed: deps.autoRouting,
|
|
202
173
|
provider_keys: {},
|
|
203
174
|
provider_key_sources: {},
|
|
204
|
-
|
|
205
|
-
|
|
175
|
+
provider_credentials: {},
|
|
176
|
+
model_fallbacks: {},
|
|
206
177
|
link_grant_id: grant?.id ?? null,
|
|
207
|
-
...(grant === null
|
|
208
|
-
? {}
|
|
209
|
-
: {
|
|
210
|
-
link_models: models.map((model) => model.id),
|
|
211
|
-
link_key_credential_ids: Object.fromEntries(grantKeys.map((key) => [key.provider, key.id])),
|
|
212
|
-
link_key_gateways: Object.fromEntries(
|
|
213
|
-
[...grantedKeys.keys()].filter((provider) => gatewayFor(provider) !== undefined).map((gateway) => {
|
|
214
|
-
const endpoint = deps.config.providers[gateway];
|
|
215
|
-
return [gateway, endpoint === undefined ? null : { api: endpoint.api, base_url: endpoint.baseUrl }];
|
|
216
|
-
}),
|
|
217
|
-
),
|
|
218
|
-
link_unavailable: linkUnavailable,
|
|
219
|
-
link_pins: grant.pins === undefined
|
|
220
|
-
? null
|
|
221
|
-
: grant.pins.map((pin) => ({ model: pin.model, thinking: isReasoningEffort(pin.thinking) ? pin.thinking : null })),
|
|
222
|
-
link_tags: grant.tags ?? null,
|
|
223
|
-
}),
|
|
224
178
|
zdr: router?.zdr ?? false,
|
|
225
179
|
speculative_routing: false,
|
|
226
180
|
session_pinning: router?.sessionPinning ?? false,
|
|
@@ -234,57 +188,124 @@ export async function resolveSelfHostedRouter(
|
|
|
234
188
|
model_thinking_levels: thinkingLevels(listed),
|
|
235
189
|
model_prices: {},
|
|
236
190
|
model_configs: {},
|
|
237
|
-
prefix_hits: deps.prefixHits({
|
|
238
|
-
routerId: grant?.id ?? request.routerId,
|
|
239
|
-
prefixHashes: request.prefixHashes ?? [],
|
|
240
|
-
...(request.conversationId ? { conversationId: request.conversationId } : {}),
|
|
241
|
-
}),
|
|
242
191
|
};
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
192
|
+
|
|
193
|
+
// Each model is served by the user's plans that serve it, in order, then by
|
|
194
|
+
// its provider's API key; the first serves and the rest are its fallbacks.
|
|
195
|
+
// A model nothing can serve is left out.
|
|
196
|
+
const exhausted = new Set<SubscriptionProvider>();
|
|
197
|
+
// The providers of models nothing serves.
|
|
198
|
+
const unserved = new Set<string>();
|
|
199
|
+
// A model held at its own limit on every plan that serves it.
|
|
200
|
+
const modelsUnavailable: Record<string, LinkUnavailable> = {};
|
|
201
|
+
const models: RouterModelConfig[] = [];
|
|
202
|
+
for (const model of listed) {
|
|
203
|
+
const base = modelProvider(model);
|
|
204
|
+
const candidates: Candidate[] = [];
|
|
205
|
+
const heldKinds: SubscriptionProvider[] = [];
|
|
206
|
+
const modelHolds: Date[] = [];
|
|
207
|
+
for (const kind of plansServe ? modelSubscriptions(model.id) : []) {
|
|
208
|
+
const client = subscriptionClient(kind);
|
|
209
|
+
if (client !== undefined && client !== request.clientHarness) continue;
|
|
210
|
+
const plan = planFor(kind, model.id);
|
|
211
|
+
if (plan !== null) {
|
|
212
|
+
candidates.push({ provider: subscriptionModelProvider(kind), plan });
|
|
213
|
+
continue;
|
|
214
|
+
}
|
|
215
|
+
const connected = grant === null ? deps.subscriptions.list(kind) : deps.subscriptions.withIds(grant.credentialIds, kind);
|
|
216
|
+
if (connected.length === 0) continue;
|
|
217
|
+
heldKinds.push(kind);
|
|
218
|
+
for (const credential of connected) {
|
|
219
|
+
for (const hold of activeModelHolds(credential, now)) if (hold.model === model.id) modelHolds.push(hold.until);
|
|
250
220
|
}
|
|
251
221
|
}
|
|
222
|
+
const key = await apiKey(base);
|
|
223
|
+
if (key !== undefined) candidates.push({ provider: base, key });
|
|
224
|
+
|
|
225
|
+
if (candidates.length === 0) {
|
|
226
|
+
for (const kind of heldKinds) exhausted.add(kind);
|
|
227
|
+
unserved.add(base);
|
|
228
|
+
// A granted plan may serve another maker's model: name the plan's provider too.
|
|
229
|
+
if (grant !== null) for (const kind of heldKinds) unserved.add(subscriptionModelProvider(kind));
|
|
230
|
+
if (modelHolds.length > 0) {
|
|
231
|
+
modelsUnavailable[model.id] = plansExhausted(heldKinds, new Date(Math.min(...modelHolds.map((until) => until.getTime()))));
|
|
232
|
+
}
|
|
233
|
+
continue;
|
|
234
|
+
}
|
|
235
|
+
models.push(model);
|
|
236
|
+
const [first, ...rest] = candidates;
|
|
237
|
+
const firstConfig = candidateConfig(deps, model.id, first!);
|
|
238
|
+
const price = priceFor(model.id, first!.provider);
|
|
239
|
+
if (price !== null) resolved.model_prices![model.id] = price;
|
|
240
|
+
if (firstConfig !== undefined) resolved.model_configs![model.id] = firstConfig;
|
|
241
|
+
if ("plan" in first!) {
|
|
242
|
+
resolved.provider_credentials![model.id] = {
|
|
243
|
+
apiKey: await planToken(first.plan),
|
|
244
|
+
subscription: first.plan.provider,
|
|
245
|
+
credentialId: first.plan.id,
|
|
246
|
+
};
|
|
247
|
+
} else {
|
|
248
|
+
resolved.provider_keys[first!.provider] = first!.key;
|
|
249
|
+
resolved.provider_key_sources![first!.provider] = "user";
|
|
250
|
+
}
|
|
251
|
+
const fallbacks = rest.flatMap((candidate): ModelFallback[] => {
|
|
252
|
+
const config = candidateConfig(deps, model.id, candidate) ?? registryConfig(model.id, candidate.provider);
|
|
253
|
+
if (config === undefined) return [];
|
|
254
|
+
if ("plan" in candidate) return [{ config, subscription: candidate.plan.provider }];
|
|
255
|
+
resolved.provider_keys[candidate.provider] = candidate.key;
|
|
256
|
+
resolved.provider_key_sources![candidate.provider] = "user";
|
|
257
|
+
return [{ config }];
|
|
258
|
+
});
|
|
259
|
+
if (fallbacks.length > 0) resolved.model_fallbacks![model.id] = fallbacks;
|
|
252
260
|
}
|
|
253
|
-
|
|
261
|
+
|
|
262
|
+
// A grant's keys are all the user's: a gateway key serves any model of its
|
|
263
|
+
// gateway a request names, listed or not.
|
|
254
264
|
for (const [provider, key] of grantedKeys) {
|
|
255
|
-
if (resolved.provider_keys[provider] !== undefined) continue;
|
|
256
265
|
resolved.provider_keys[provider] = key;
|
|
257
266
|
resolved.provider_key_sources![provider] = "user";
|
|
258
267
|
}
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
} else if (served !== undefined) {
|
|
271
|
-
resolved.model_configs![model.id] = {
|
|
272
|
-
provider,
|
|
273
|
-
native_model_id: served.native_model_id,
|
|
274
|
-
api: endpoint?.api ?? served.api,
|
|
275
|
-
base_url: endpoint?.baseUrl ?? served.base_url,
|
|
276
|
-
cost: price ?? { input: 0, output: 0 },
|
|
277
|
-
};
|
|
278
|
-
} else if (endpoint !== undefined) {
|
|
279
|
-
resolved.model_configs![model.id] = {
|
|
280
|
-
provider,
|
|
281
|
-
native_model_id: nativeModelId(model.id),
|
|
282
|
-
api: endpoint.api,
|
|
283
|
-
base_url: endpoint.baseUrl,
|
|
284
|
-
cost: price ?? { input: 0, output: 0 },
|
|
268
|
+
// A provider the request wanted that no granted plan served.
|
|
269
|
+
const linkUnavailable = grant === null
|
|
270
|
+
? {}
|
|
271
|
+
: {
|
|
272
|
+
...providersUnavailable(
|
|
273
|
+
granted.map((credential) => ({ kind: credential.provider, unavailableUntil: credential.unavailableUntil })),
|
|
274
|
+
unserved,
|
|
275
|
+
request.clientHarness,
|
|
276
|
+
now,
|
|
277
|
+
),
|
|
278
|
+
...modelsUnavailable,
|
|
285
279
|
};
|
|
286
|
-
|
|
280
|
+
|
|
281
|
+
const gatewayKeyed = [...grantedKeys.keys()].some((provider) => gatewayFor(provider) !== undefined);
|
|
282
|
+
if (models.length === 0 && !gatewayKeyed) {
|
|
283
|
+
if (grant !== null) throw linkNothingServed(linkUnavailable, grant.pins);
|
|
284
|
+
throw unavailableRouterError(request.routerId, exhausted, [...unserved]);
|
|
285
|
+
}
|
|
286
|
+
resolved.enabled_models = models.map((model) => model.id);
|
|
287
|
+
if (grant !== null) {
|
|
288
|
+
Object.assign(resolved, {
|
|
289
|
+
link_models: models.map((model) => model.id),
|
|
290
|
+
link_key_credential_ids: Object.fromEntries(grantKeys.map((key) => [key.provider, key.id])),
|
|
291
|
+
link_key_gateways: Object.fromEntries(
|
|
292
|
+
[...grantedKeys.keys()].filter((provider) => gatewayFor(provider) !== undefined).map((gateway) => {
|
|
293
|
+
const endpoint = deps.config.providers[gateway];
|
|
294
|
+
return [gateway, endpoint === undefined ? null : { api: endpoint.api, base_url: endpoint.baseUrl }];
|
|
295
|
+
}),
|
|
296
|
+
),
|
|
297
|
+
link_unavailable: linkUnavailable,
|
|
298
|
+
link_pins: grant.pins === undefined
|
|
299
|
+
? null
|
|
300
|
+
: grant.pins.map((pin) => ({ model: pin.model, thinking: isReasoningEffort(pin.thinking) ? pin.thinking : null })),
|
|
301
|
+
link_tags: grant.tags ?? null,
|
|
302
|
+
});
|
|
287
303
|
}
|
|
304
|
+
resolved.prefix_hits = deps.prefixHits({
|
|
305
|
+
routerId: grant?.id ?? request.routerId,
|
|
306
|
+
prefixHashes: request.prefixHashes ?? [],
|
|
307
|
+
...(request.conversationId ? { conversationId: request.conversationId } : {}),
|
|
308
|
+
});
|
|
288
309
|
return resolved;
|
|
289
310
|
}
|
|
290
311
|
|
|
@@ -294,7 +315,8 @@ export async function resolveSelfHostedRouter(
|
|
|
294
315
|
/**
|
|
295
316
|
* The models a grant's request may be served: a child token's one model, or
|
|
296
317
|
* the router's own models followed by every other catalog model of the
|
|
297
|
-
* providers its
|
|
318
|
+
* providers its API keys serve and every one a granted plan has an offering
|
|
319
|
+
* of, whoever makes it (every OpenCode Go model is another maker's).
|
|
298
320
|
*/
|
|
299
321
|
function grantModels(
|
|
300
322
|
grant: ActiveLinkGrant,
|
|
@@ -306,12 +328,18 @@ function grantModels(
|
|
|
306
328
|
...granted.map((credential) => subscriptionModelProvider(credential.provider)),
|
|
307
329
|
...grantedKeys.keys(),
|
|
308
330
|
]);
|
|
331
|
+
const kinds = new Set(granted.map((credential) => credential.provider));
|
|
309
332
|
const routedIds = new Set(routed.map((model) => model.id));
|
|
310
333
|
const models = [
|
|
311
334
|
...routed,
|
|
312
|
-
...CANONICAL_MODELS
|
|
313
|
-
|
|
314
|
-
.
|
|
335
|
+
...CANONICAL_MODELS.flatMap((model): RouterModelConfig[] => {
|
|
336
|
+
if (routedIds.has(model.id)) return [];
|
|
337
|
+
if (providers.has(providerForModel(model.id))) return registeredModelPrice(model.id) !== null ? [{ id: model.id }] : [];
|
|
338
|
+
if (!modelSubscriptions(model.id).some((kind) => kinds.has(kind))) return [];
|
|
339
|
+
// The plans serve it first, then a granted key of a provider that runs it.
|
|
340
|
+
const keyed = otherModelProviders(model.id).find((provider) => grantedKeys.has(provider) && gatewayFor(provider) === undefined);
|
|
341
|
+
return [keyed === undefined ? { id: model.id } : { id: model.id, provider: keyed }];
|
|
342
|
+
}),
|
|
315
343
|
];
|
|
316
344
|
if (grant.pins === undefined) return models;
|
|
317
345
|
// A pinned level replaces the router's own choice of levels for the model.
|
|
@@ -342,27 +370,65 @@ export function gatewayKeyIndex(keys: readonly string[], presented: string): num
|
|
|
342
370
|
return null;
|
|
343
371
|
}
|
|
344
372
|
|
|
345
|
-
//
|
|
346
|
-
//
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
373
|
+
// How a candidate runs a model: a ChatGPT plan through the Codex backend, a
|
|
374
|
+
// provider that serves another maker's model as its own model, a configured
|
|
375
|
+
// endpoint, or (undefined) the model's own provider as the catalog has it.
|
|
376
|
+
function candidateConfig(
|
|
377
|
+
deps: Pick<SelfHostedResolverDeps, "config">,
|
|
378
|
+
modelId: string,
|
|
379
|
+
candidate: Candidate,
|
|
380
|
+
): ResolvedRouterModelConfig | undefined {
|
|
381
|
+
const { provider } = candidate;
|
|
382
|
+
const price = priceFor(modelId, provider);
|
|
383
|
+
if ("plan" in candidate && candidate.plan.provider === "openai_codex") {
|
|
384
|
+
return codexModelConfig(modelId, price, deps.config.providers["openai-codex"]?.baseUrl);
|
|
353
385
|
}
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
if (
|
|
357
|
-
|
|
386
|
+
const served = providerModel(modelId, provider);
|
|
387
|
+
const endpoint = deps.config.providers[provider];
|
|
388
|
+
if (served !== undefined) {
|
|
389
|
+
return {
|
|
390
|
+
provider,
|
|
391
|
+
native_model_id: served.native_model_id,
|
|
392
|
+
api: endpoint?.api ?? served.api,
|
|
393
|
+
base_url: endpoint?.baseUrl ?? served.base_url,
|
|
394
|
+
cost: price ?? { input: 0, output: 0 },
|
|
395
|
+
};
|
|
396
|
+
}
|
|
397
|
+
if (endpoint === undefined) return undefined;
|
|
398
|
+
return {
|
|
399
|
+
provider,
|
|
400
|
+
native_model_id: nativeModelId(modelId),
|
|
401
|
+
api: endpoint.api,
|
|
402
|
+
base_url: endpoint.baseUrl,
|
|
403
|
+
cost: price ?? { input: 0, output: 0 },
|
|
404
|
+
};
|
|
358
405
|
}
|
|
359
406
|
|
|
360
|
-
// A
|
|
361
|
-
//
|
|
362
|
-
function
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
407
|
+
// A fallback names its endpoint even on the model's own provider, as the
|
|
408
|
+
// catalog has it; undefined when the catalog has none.
|
|
409
|
+
function registryConfig(modelId: string, provider: string): ResolvedRouterModelConfig | undefined {
|
|
410
|
+
try {
|
|
411
|
+
const model = buildModel(pi, modelId, null);
|
|
412
|
+
if (typeof model.api !== "string" || typeof model.baseUrl !== "string") return undefined;
|
|
413
|
+
return {
|
|
414
|
+
provider,
|
|
415
|
+
native_model_id: nativeModelId(modelId),
|
|
416
|
+
api: model.api,
|
|
417
|
+
base_url: model.baseUrl,
|
|
418
|
+
cost: priceFor(modelId, provider) ?? { input: 0, output: 0 },
|
|
419
|
+
};
|
|
420
|
+
} catch {
|
|
421
|
+
return undefined;
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
|
|
425
|
+
// A model's price as a provider serves it, for estimates; a plan bills no
|
|
426
|
+
// tokens.
|
|
427
|
+
function priceFor(modelId: string, provider: string): RouterModelPrice | null {
|
|
428
|
+
const served = providerModel(modelId, provider);
|
|
429
|
+
return served === undefined
|
|
430
|
+
? registeredModelPrice(modelId)
|
|
431
|
+
: registeredModelPrice(`${provider}/${served.native_model_id}`);
|
|
366
432
|
}
|
|
367
433
|
|
|
368
434
|
function thinkingLevels(models: readonly RouterModelConfig[]): Record<string, ReasoningEffort[]> {
|
|
@@ -376,29 +442,31 @@ const SUBSCRIPTION_PLAN_NAMES: Record<SubscriptionProvider, string> = {
|
|
|
376
442
|
openai_codex: "ChatGPT",
|
|
377
443
|
meta_muse: "Muse Code",
|
|
378
444
|
opencode_go: "OpenCode Go",
|
|
445
|
+
github_copilot: "GitHub Copilot",
|
|
446
|
+
xai_grok: "Grok",
|
|
447
|
+
vercel_token_pass: "Vercel Token Pass",
|
|
379
448
|
};
|
|
380
449
|
|
|
381
450
|
/**
|
|
382
|
-
* Providers a router lists that no credential can serve: no API key
|
|
383
|
-
* connected subscription the router allows
|
|
384
|
-
* held subscription as connected (the request-time
|
|
385
|
-
*
|
|
451
|
+
* Providers a router lists models of that no credential can serve: no API key
|
|
452
|
+
* and no connected subscription the router allows that serves them. Startup
|
|
453
|
+
* uses this, so it counts a held subscription as connected (the request-time
|
|
454
|
+
* 424 reports holds) and ignores which client a plan is limited to, since
|
|
455
|
+
* startup does not know the client.
|
|
386
456
|
*/
|
|
387
457
|
export async function providersWithoutCredentials(
|
|
388
458
|
deps: Pick<SelfHostedResolverDeps, "subscriptions" | "providerApiKey" | "config" | "env">,
|
|
389
459
|
router: RouterConfig,
|
|
390
460
|
): Promise<string[]> {
|
|
391
|
-
const missing
|
|
392
|
-
for (const
|
|
393
|
-
const
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
if (
|
|
398
|
-
const apiKey = await configuredProviderApiKey(deps, provider);
|
|
399
|
-
if (apiKey === undefined) missing.push(provider);
|
|
461
|
+
const missing = new Set<string>();
|
|
462
|
+
for (const model of allRouterModels(router)) {
|
|
463
|
+
const provider = modelProvider(model);
|
|
464
|
+
if (missing.has(provider)) continue;
|
|
465
|
+
const plans = router.subscriptions ? modelSubscriptions(model.id) : [];
|
|
466
|
+
if (plans.some((plan) => deps.subscriptions.list(plan).length > 0)) continue;
|
|
467
|
+
if (await configuredProviderApiKey(deps, provider) === undefined) missing.add(provider);
|
|
400
468
|
}
|
|
401
|
-
return missing;
|
|
469
|
+
return [...missing];
|
|
402
470
|
}
|
|
403
471
|
|
|
404
472
|
function unavailableRouterError(
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
/**
|
|
2
|
-
* Personal subscriptions for a self-hosted, single-tenant gateway: Claude Code
|
|
3
|
-
*
|
|
4
|
-
* of API keys.
|
|
2
|
+
* Personal subscriptions for a self-hosted, single-tenant gateway: Claude Code,
|
|
3
|
+
* ChatGPT, Muse Code, OpenCode Go, GitHub Copilot, and Grok plans
|
|
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
|
|
7
|
-
* pasted `code#state`,
|
|
7
|
+
* pasted `code#state`, the others' device codes, a pasted Token Pass key)
|
|
8
|
+
* and token refresh.
|
|
8
9
|
* - `store.ts`: SQLite storage. Tokens are plaintext in the gateway's own
|
|
9
10
|
* database file; protect that file like a secret.
|
|
10
11
|
* - `access.ts`: `freshAccessToken` refreshes a token expiring within five
|
|
@@ -27,8 +28,10 @@ export { freshAccessToken } from "./access.js";
|
|
|
27
28
|
export { handleSubscriptionRequest, type SubscriptionHttpDeps } from "./http.js";
|
|
28
29
|
export {
|
|
29
30
|
CODEX_APPROVAL_PENDING,
|
|
31
|
+
GITHUB_APPROVAL_PENDING,
|
|
30
32
|
META_APPROVAL_PENDING,
|
|
31
33
|
OPENCODE_APPROVAL_PENDING,
|
|
34
|
+
XAI_APPROVAL_PENDING,
|
|
32
35
|
SUBSCRIPTION_PROVIDERS,
|
|
33
36
|
SubscriptionOAuthInputError,
|
|
34
37
|
SubscriptionOAuthProviderError,
|