@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
|
@@ -2,12 +2,13 @@ import { timingSafeEqual } from "node:crypto";
|
|
|
2
2
|
import { isReasoningEffort, nativeModelId, providerForModel, } from "@mupt-ai/dari-router/policy-engine";
|
|
3
3
|
import { HttpError } from "../http/errors.js";
|
|
4
4
|
import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
5
|
-
import { codexModelConfig, subscriptionModelProvider } from "../models/subscriptions.js";
|
|
6
|
-
import { CANONICAL_MODELS, providerModel } from "../models/canonical.js";
|
|
5
|
+
import { codexModelConfig, modelSubscriptions, subscriptionClient, subscriptionModelProvider, } from "../models/subscriptions.js";
|
|
6
|
+
import { CANONICAL_MODELS, otherModelProviders, providerModel } from "../models/canonical.js";
|
|
7
7
|
import { gatewayFor } from "../models/gateways.js";
|
|
8
8
|
import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
|
|
9
|
-
import { registeredModelPrice } from "../providers/pi.js";
|
|
9
|
+
import { buildModel, pi, registeredModelPrice } from "../providers/pi.js";
|
|
10
10
|
import { allRouterModels, modelProvider, routerModelsFor, } from "./config.js";
|
|
11
|
+
import { linkSubscription } from "../link/self_hosted.js";
|
|
11
12
|
import { linkTokenGrant } from "../link/service.js";
|
|
12
13
|
import { servedRouter } from "./router_specs.js";
|
|
13
14
|
import { refreshedAccessToken } from "./subscriptions/access.js";
|
|
@@ -17,11 +18,12 @@ import { activeModelHolds, freshAccessToken, } from "./subscriptions/index.js";
|
|
|
17
18
|
export const SELF_HOSTED_ORGANIZATION_ID = "self-hosted";
|
|
18
19
|
export const SELF_HOSTED_USER_ID = "self-hosted";
|
|
19
20
|
/**
|
|
20
|
-
* Resolve a configured router for one request. Each
|
|
21
|
-
* connected personal
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
*
|
|
21
|
+
* Resolve a configured router for one request. Each model is served by the
|
|
22
|
+
* connected personal subscriptions that serve it, when the router allows them,
|
|
23
|
+
* in plan order (see models/subscriptions.ts), then by its provider's API key:
|
|
24
|
+
* the first available serves and the rest fail over within the request.
|
|
25
|
+
* Models nothing can serve are left out. A coding agent with its own model
|
|
26
|
+
* list on the router is served that list.
|
|
25
27
|
*
|
|
26
28
|
* A Dari Link token is served apart from any router, on its grant's plans and
|
|
27
29
|
* API keys alone: `dari/routing` chooses among every catalog model they
|
|
@@ -30,7 +32,7 @@ export const SELF_HOSTED_USER_ID = "self-hosted";
|
|
|
30
32
|
*/
|
|
31
33
|
export async function resolveSelfHostedRouter(deps, request) {
|
|
32
34
|
const keyIndex = gatewayKeyIndex(deps.gatewayKeys, request.apiKey);
|
|
33
|
-
const grant = keyIndex === null ? await linkTokenGrant(deps.links, request.apiKey) : null;
|
|
35
|
+
const grant = keyIndex === null ? await linkTokenGrant(deps.links, { plansWithIds: async (ids) => deps.subscriptions.withIds(new Set(ids)).map(linkSubscription) }, request.apiKey) : null;
|
|
34
36
|
if (keyIndex === null && grant === null) {
|
|
35
37
|
throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
|
|
36
38
|
}
|
|
@@ -51,109 +53,59 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
51
53
|
const listed = grant === null ? routed : grantModels(grant, routed, granted, grantedKeys);
|
|
52
54
|
const now = new Date();
|
|
53
55
|
const servable = grant === null ? undefined : new Set(grant.credentialIds);
|
|
54
|
-
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
const active = subscription === null
|
|
62
|
-
? null
|
|
63
|
-
: deps.subscriptions.selectCredential(subscription, request.conversationId, now, servable);
|
|
64
|
-
if (active !== null) {
|
|
65
|
-
credentials.set(provider, {
|
|
66
|
-
// A provisional resolve's credentials never serve, so it neither marks
|
|
67
|
-
// the plan used nor refreshes its token.
|
|
68
|
-
key: request.provisional === true
|
|
69
|
-
? active.accessToken
|
|
70
|
-
: await freshAccessToken(deps.subscriptions, active, { fetch: deps.fetch }),
|
|
71
|
-
source: "subscription",
|
|
72
|
-
subscription: active,
|
|
73
|
-
});
|
|
74
|
-
continue;
|
|
75
|
-
}
|
|
76
|
-
if (grant !== null) {
|
|
77
|
-
// A plan first; else the key the user added for the provider.
|
|
78
|
-
const key = grantedKeys.get(provider);
|
|
79
|
-
credentials.set(provider, key === undefined ? null : { key, source: "user" });
|
|
80
|
-
continue;
|
|
81
|
-
}
|
|
82
|
-
if (subscription !== null && deps.subscriptions.list(subscription).length > 0)
|
|
83
|
-
exhausted.add(subscription);
|
|
84
|
-
const apiKey = await configuredProviderApiKey(deps, provider);
|
|
85
|
-
credentials.set(provider, apiKey ? { key: apiKey, source: "user" } : null);
|
|
86
|
-
}
|
|
87
|
-
// A model-specific hold tries the pool's other plans before removing the
|
|
88
|
-
// model. Its provider's active plan and conversation pin stay unchanged.
|
|
89
|
-
const modelCredentials = {};
|
|
90
|
-
// A provider the request wanted that no granted plan served.
|
|
91
|
-
const linkUnavailable = grant === null
|
|
92
|
-
? {}
|
|
93
|
-
: providersUnavailable(granted.map((credential) => ({ kind: credential.provider, unavailableUntil: credential.unavailableUntil })), [...credentials].filter(([, credential]) => credential === null).map(([provider]) => provider), request.clientHarness, now);
|
|
94
|
-
const models = [];
|
|
95
|
-
for (const model of listed) {
|
|
96
|
-
const credential = credentials.get(modelProvider(model));
|
|
97
|
-
if (credential == null)
|
|
98
|
-
continue;
|
|
99
|
-
const plan = credential.subscription;
|
|
100
|
-
const hold = plan === undefined ? undefined : activeModelHolds(plan, now).find((held) => held.model === model.id);
|
|
101
|
-
if (plan === undefined || hold === undefined) {
|
|
102
|
-
models.push(model);
|
|
103
|
-
continue;
|
|
56
|
+
// A grant uses the subscriptions its user chose, whatever the router allows.
|
|
57
|
+
const plansServe = router?.subscriptions === true || grant !== null;
|
|
58
|
+
// The plan of each kind that serves this conversation, chosen once.
|
|
59
|
+
const conversationPlans = new Map();
|
|
60
|
+
const conversationPlan = (kind) => {
|
|
61
|
+
if (!conversationPlans.has(kind)) {
|
|
62
|
+
conversationPlans.set(kind, deps.subscriptions.selectCredential(kind, request.conversationId, now, servable));
|
|
104
63
|
}
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
64
|
+
return conversationPlans.get(kind);
|
|
65
|
+
};
|
|
66
|
+
// The conversation's plan of a kind for a model, or with that model held at
|
|
67
|
+
// its own limit there, another plan of the kind that serves it.
|
|
68
|
+
const planFor = (kind, modelId) => {
|
|
69
|
+
const active = conversationPlan(kind);
|
|
70
|
+
if (active !== null && !activeModelHolds(active, now).some((hold) => hold.model === modelId))
|
|
71
|
+
return active;
|
|
72
|
+
return deps.subscriptions.selectCredential(kind, undefined, now, servable, modelId);
|
|
73
|
+
};
|
|
74
|
+
const tokens = new Map();
|
|
75
|
+
const planToken = (plan) => {
|
|
76
|
+
// A provisional resolve's credentials never serve, so it neither marks
|
|
77
|
+
// the plan used nor refreshes its token.
|
|
78
|
+
if (request.provisional === true)
|
|
79
|
+
return Promise.resolve(plan.accessToken);
|
|
80
|
+
if (!tokens.has(plan.id)) {
|
|
81
|
+
tokens.set(plan.id, conversationPlans.get(plan.provider)?.id === plan.id
|
|
82
|
+
? freshAccessToken(deps.subscriptions, plan, { fetch: deps.fetch })
|
|
83
|
+
// A model-only failover must not move the provider-wide rotation anchor.
|
|
84
|
+
: refreshedAccessToken(deps.subscriptions, plan, { fetch: deps.fetch }));
|
|
117
85
|
}
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
const gatewayKeyed = [...grantedKeys.keys()].some((provider) => gatewayFor(provider) !== undefined);
|
|
123
|
-
if (models.length === 0 && !gatewayKeyed) {
|
|
86
|
+
return tokens.get(plan.id);
|
|
87
|
+
};
|
|
88
|
+
const apiKeys = new Map();
|
|
89
|
+
const apiKey = (provider) => {
|
|
124
90
|
if (grant !== null)
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
91
|
+
return Promise.resolve(grantedKeys.get(provider));
|
|
92
|
+
if (!apiKeys.has(provider))
|
|
93
|
+
apiKeys.set(provider, configuredProviderApiKey(deps, provider));
|
|
94
|
+
return apiKeys.get(provider);
|
|
95
|
+
};
|
|
129
96
|
const resolved = {
|
|
130
97
|
// A grant's requests and prefix state are its own, apart from any router.
|
|
131
98
|
router_id: grant?.id ?? request.routerId,
|
|
132
99
|
organization_id: SELF_HOSTED_ORGANIZATION_ID,
|
|
133
100
|
api_key_id: grant === null ? `gateway_key_${keyIndex + 1}` : grant.id,
|
|
134
101
|
attributed_user_id: SELF_HOSTED_USER_ID,
|
|
135
|
-
enabled_models:
|
|
102
|
+
enabled_models: [],
|
|
136
103
|
routing_listed: deps.autoRouting,
|
|
137
104
|
provider_keys: {},
|
|
138
105
|
provider_key_sources: {},
|
|
139
|
-
|
|
140
|
-
|
|
106
|
+
provider_credentials: {},
|
|
107
|
+
model_fallbacks: {},
|
|
141
108
|
link_grant_id: grant?.id ?? null,
|
|
142
|
-
...(grant === null
|
|
143
|
-
? {}
|
|
144
|
-
: {
|
|
145
|
-
link_models: models.map((model) => model.id),
|
|
146
|
-
link_key_credential_ids: Object.fromEntries(grantKeys.map((key) => [key.provider, key.id])),
|
|
147
|
-
link_key_gateways: Object.fromEntries([...grantedKeys.keys()].filter((provider) => gatewayFor(provider) !== undefined).map((gateway) => {
|
|
148
|
-
const endpoint = deps.config.providers[gateway];
|
|
149
|
-
return [gateway, endpoint === undefined ? null : { api: endpoint.api, base_url: endpoint.baseUrl }];
|
|
150
|
-
})),
|
|
151
|
-
link_unavailable: linkUnavailable,
|
|
152
|
-
link_pins: grant.pins === undefined
|
|
153
|
-
? null
|
|
154
|
-
: grant.pins.map((pin) => ({ model: pin.model, thinking: isReasoningEffort(pin.thinking) ? pin.thinking : null })),
|
|
155
|
-
link_tags: grant.tags ?? null,
|
|
156
|
-
}),
|
|
157
109
|
zdr: router?.zdr ?? false,
|
|
158
110
|
speculative_routing: false,
|
|
159
111
|
session_pinning: router?.sessionPinning ?? false,
|
|
@@ -167,62 +119,128 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
167
119
|
model_thinking_levels: thinkingLevels(listed),
|
|
168
120
|
model_prices: {},
|
|
169
121
|
model_configs: {},
|
|
170
|
-
prefix_hits: deps.prefixHits({
|
|
171
|
-
routerId: grant?.id ?? request.routerId,
|
|
172
|
-
prefixHashes: request.prefixHashes ?? [],
|
|
173
|
-
...(request.conversationId ? { conversationId: request.conversationId } : {}),
|
|
174
|
-
}),
|
|
175
122
|
};
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
123
|
+
// Each model is served by the user's plans that serve it, in order, then by
|
|
124
|
+
// its provider's API key; the first serves and the rest are its fallbacks.
|
|
125
|
+
// A model nothing can serve is left out.
|
|
126
|
+
const exhausted = new Set();
|
|
127
|
+
// The providers of models nothing serves.
|
|
128
|
+
const unserved = new Set();
|
|
129
|
+
// A model held at its own limit on every plan that serves it.
|
|
130
|
+
const modelsUnavailable = {};
|
|
131
|
+
const models = [];
|
|
132
|
+
for (const model of listed) {
|
|
133
|
+
const base = modelProvider(model);
|
|
134
|
+
const candidates = [];
|
|
135
|
+
const heldKinds = [];
|
|
136
|
+
const modelHolds = [];
|
|
137
|
+
for (const kind of plansServe ? modelSubscriptions(model.id) : []) {
|
|
138
|
+
const client = subscriptionClient(kind);
|
|
139
|
+
if (client !== undefined && client !== request.clientHarness)
|
|
140
|
+
continue;
|
|
141
|
+
const plan = planFor(kind, model.id);
|
|
142
|
+
if (plan !== null) {
|
|
143
|
+
candidates.push({ provider: subscriptionModelProvider(kind), plan });
|
|
144
|
+
continue;
|
|
145
|
+
}
|
|
146
|
+
const connected = grant === null ? deps.subscriptions.list(kind) : deps.subscriptions.withIds(grant.credentialIds, kind);
|
|
147
|
+
if (connected.length === 0)
|
|
148
|
+
continue;
|
|
149
|
+
heldKinds.push(kind);
|
|
150
|
+
for (const credential of connected) {
|
|
151
|
+
for (const hold of activeModelHolds(credential, now))
|
|
152
|
+
if (hold.model === model.id)
|
|
153
|
+
modelHolds.push(hold.until);
|
|
184
154
|
}
|
|
185
155
|
}
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
if (
|
|
156
|
+
const key = await apiKey(base);
|
|
157
|
+
if (key !== undefined)
|
|
158
|
+
candidates.push({ provider: base, key });
|
|
159
|
+
if (candidates.length === 0) {
|
|
160
|
+
for (const kind of heldKinds)
|
|
161
|
+
exhausted.add(kind);
|
|
162
|
+
unserved.add(base);
|
|
163
|
+
// A granted plan may serve another maker's model: name the plan's provider too.
|
|
164
|
+
if (grant !== null)
|
|
165
|
+
for (const kind of heldKinds)
|
|
166
|
+
unserved.add(subscriptionModelProvider(kind));
|
|
167
|
+
if (modelHolds.length > 0) {
|
|
168
|
+
modelsUnavailable[model.id] = plansExhausted(heldKinds, new Date(Math.min(...modelHolds.map((until) => until.getTime()))));
|
|
169
|
+
}
|
|
190
170
|
continue;
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
const
|
|
196
|
-
// A model another provider serves runs as that provider's own model.
|
|
197
|
-
const served = model.provider === undefined ? undefined : providerModel(model.id, provider);
|
|
198
|
-
const price = served === undefined
|
|
199
|
-
? registeredModelPrice(model.id)
|
|
200
|
-
: registeredModelPrice(`${provider}/${served.native_model_id}`);
|
|
171
|
+
}
|
|
172
|
+
models.push(model);
|
|
173
|
+
const [first, ...rest] = candidates;
|
|
174
|
+
const firstConfig = candidateConfig(deps, model.id, first);
|
|
175
|
+
const price = priceFor(model.id, first.provider);
|
|
201
176
|
if (price !== null)
|
|
202
177
|
resolved.model_prices[model.id] = price;
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
native_model_id: served.native_model_id,
|
|
211
|
-
api: endpoint?.api ?? served.api,
|
|
212
|
-
base_url: endpoint?.baseUrl ?? served.base_url,
|
|
213
|
-
cost: price ?? { input: 0, output: 0 },
|
|
178
|
+
if (firstConfig !== undefined)
|
|
179
|
+
resolved.model_configs[model.id] = firstConfig;
|
|
180
|
+
if ("plan" in first) {
|
|
181
|
+
resolved.provider_credentials[model.id] = {
|
|
182
|
+
apiKey: await planToken(first.plan),
|
|
183
|
+
subscription: first.plan.provider,
|
|
184
|
+
credentialId: first.plan.id,
|
|
214
185
|
};
|
|
215
186
|
}
|
|
216
|
-
else
|
|
217
|
-
resolved.
|
|
218
|
-
|
|
219
|
-
native_model_id: nativeModelId(model.id),
|
|
220
|
-
api: endpoint.api,
|
|
221
|
-
base_url: endpoint.baseUrl,
|
|
222
|
-
cost: price ?? { input: 0, output: 0 },
|
|
223
|
-
};
|
|
187
|
+
else {
|
|
188
|
+
resolved.provider_keys[first.provider] = first.key;
|
|
189
|
+
resolved.provider_key_sources[first.provider] = "user";
|
|
224
190
|
}
|
|
191
|
+
const fallbacks = rest.flatMap((candidate) => {
|
|
192
|
+
const config = candidateConfig(deps, model.id, candidate) ?? registryConfig(model.id, candidate.provider);
|
|
193
|
+
if (config === undefined)
|
|
194
|
+
return [];
|
|
195
|
+
if ("plan" in candidate)
|
|
196
|
+
return [{ config, subscription: candidate.plan.provider }];
|
|
197
|
+
resolved.provider_keys[candidate.provider] = candidate.key;
|
|
198
|
+
resolved.provider_key_sources[candidate.provider] = "user";
|
|
199
|
+
return [{ config }];
|
|
200
|
+
});
|
|
201
|
+
if (fallbacks.length > 0)
|
|
202
|
+
resolved.model_fallbacks[model.id] = fallbacks;
|
|
203
|
+
}
|
|
204
|
+
// A grant's keys are all the user's: a gateway key serves any model of its
|
|
205
|
+
// gateway a request names, listed or not.
|
|
206
|
+
for (const [provider, key] of grantedKeys) {
|
|
207
|
+
resolved.provider_keys[provider] = key;
|
|
208
|
+
resolved.provider_key_sources[provider] = "user";
|
|
209
|
+
}
|
|
210
|
+
// A provider the request wanted that no granted plan served.
|
|
211
|
+
const linkUnavailable = grant === null
|
|
212
|
+
? {}
|
|
213
|
+
: {
|
|
214
|
+
...providersUnavailable(granted.map((credential) => ({ kind: credential.provider, unavailableUntil: credential.unavailableUntil })), unserved, request.clientHarness, now),
|
|
215
|
+
...modelsUnavailable,
|
|
216
|
+
};
|
|
217
|
+
const gatewayKeyed = [...grantedKeys.keys()].some((provider) => gatewayFor(provider) !== undefined);
|
|
218
|
+
if (models.length === 0 && !gatewayKeyed) {
|
|
219
|
+
if (grant !== null)
|
|
220
|
+
throw linkNothingServed(linkUnavailable, grant.pins);
|
|
221
|
+
throw unavailableRouterError(request.routerId, exhausted, [...unserved]);
|
|
225
222
|
}
|
|
223
|
+
resolved.enabled_models = models.map((model) => model.id);
|
|
224
|
+
if (grant !== null) {
|
|
225
|
+
Object.assign(resolved, {
|
|
226
|
+
link_models: models.map((model) => model.id),
|
|
227
|
+
link_key_credential_ids: Object.fromEntries(grantKeys.map((key) => [key.provider, key.id])),
|
|
228
|
+
link_key_gateways: Object.fromEntries([...grantedKeys.keys()].filter((provider) => gatewayFor(provider) !== undefined).map((gateway) => {
|
|
229
|
+
const endpoint = deps.config.providers[gateway];
|
|
230
|
+
return [gateway, endpoint === undefined ? null : { api: endpoint.api, base_url: endpoint.baseUrl }];
|
|
231
|
+
})),
|
|
232
|
+
link_unavailable: linkUnavailable,
|
|
233
|
+
link_pins: grant.pins === undefined
|
|
234
|
+
? null
|
|
235
|
+
: grant.pins.map((pin) => ({ model: pin.model, thinking: isReasoningEffort(pin.thinking) ? pin.thinking : null })),
|
|
236
|
+
link_tags: grant.tags ?? null,
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
resolved.prefix_hits = deps.prefixHits({
|
|
240
|
+
routerId: grant?.id ?? request.routerId,
|
|
241
|
+
prefixHashes: request.prefixHashes ?? [],
|
|
242
|
+
...(request.conversationId ? { conversationId: request.conversationId } : {}),
|
|
243
|
+
});
|
|
226
244
|
return resolved;
|
|
227
245
|
}
|
|
228
246
|
// The grant a live link token belongs to, or null for a token that is not
|
|
@@ -230,19 +248,29 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
230
248
|
/**
|
|
231
249
|
* The models a grant's request may be served: a child token's one model, or
|
|
232
250
|
* the router's own models followed by every other catalog model of the
|
|
233
|
-
* providers its
|
|
251
|
+
* providers its API keys serve and every one a granted plan has an offering
|
|
252
|
+
* of, whoever makes it (every OpenCode Go model is another maker's).
|
|
234
253
|
*/
|
|
235
254
|
function grantModels(grant, routed, granted, grantedKeys) {
|
|
236
255
|
const providers = new Set([
|
|
237
256
|
...granted.map((credential) => subscriptionModelProvider(credential.provider)),
|
|
238
257
|
...grantedKeys.keys(),
|
|
239
258
|
]);
|
|
259
|
+
const kinds = new Set(granted.map((credential) => credential.provider));
|
|
240
260
|
const routedIds = new Set(routed.map((model) => model.id));
|
|
241
261
|
const models = [
|
|
242
262
|
...routed,
|
|
243
|
-
...CANONICAL_MODELS
|
|
244
|
-
|
|
245
|
-
|
|
263
|
+
...CANONICAL_MODELS.flatMap((model) => {
|
|
264
|
+
if (routedIds.has(model.id))
|
|
265
|
+
return [];
|
|
266
|
+
if (providers.has(providerForModel(model.id)))
|
|
267
|
+
return registeredModelPrice(model.id) !== null ? [{ id: model.id }] : [];
|
|
268
|
+
if (!modelSubscriptions(model.id).some((kind) => kinds.has(kind)))
|
|
269
|
+
return [];
|
|
270
|
+
// The plans serve it first, then a granted key of a provider that runs it.
|
|
271
|
+
const keyed = otherModelProviders(model.id).find((provider) => grantedKeys.has(provider) && gatewayFor(provider) === undefined);
|
|
272
|
+
return [keyed === undefined ? { id: model.id } : { id: model.id, provider: keyed }];
|
|
273
|
+
}),
|
|
246
274
|
];
|
|
247
275
|
if (grant.pins === undefined)
|
|
248
276
|
return models;
|
|
@@ -270,26 +298,62 @@ export function gatewayKeyIndex(keys, presented) {
|
|
|
270
298
|
}
|
|
271
299
|
return null;
|
|
272
300
|
}
|
|
273
|
-
//
|
|
274
|
-
//
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
301
|
+
// How a candidate runs a model: a ChatGPT plan through the Codex backend, a
|
|
302
|
+
// provider that serves another maker's model as its own model, a configured
|
|
303
|
+
// endpoint, or (undefined) the model's own provider as the catalog has it.
|
|
304
|
+
function candidateConfig(deps, modelId, candidate) {
|
|
305
|
+
const { provider } = candidate;
|
|
306
|
+
const price = priceFor(modelId, provider);
|
|
307
|
+
if ("plan" in candidate && candidate.plan.provider === "openai_codex") {
|
|
308
|
+
return codexModelConfig(modelId, price, deps.config.providers["openai-codex"]?.baseUrl);
|
|
309
|
+
}
|
|
310
|
+
const served = providerModel(modelId, provider);
|
|
311
|
+
const endpoint = deps.config.providers[provider];
|
|
312
|
+
if (served !== undefined) {
|
|
313
|
+
return {
|
|
314
|
+
provider,
|
|
315
|
+
native_model_id: served.native_model_id,
|
|
316
|
+
api: endpoint?.api ?? served.api,
|
|
317
|
+
base_url: endpoint?.baseUrl ?? served.base_url,
|
|
318
|
+
cost: price ?? { input: 0, output: 0 },
|
|
319
|
+
};
|
|
320
|
+
}
|
|
321
|
+
if (endpoint === undefined)
|
|
322
|
+
return undefined;
|
|
323
|
+
return {
|
|
324
|
+
provider,
|
|
325
|
+
native_model_id: nativeModelId(modelId),
|
|
326
|
+
api: endpoint.api,
|
|
327
|
+
base_url: endpoint.baseUrl,
|
|
328
|
+
cost: price ?? { input: 0, output: 0 },
|
|
329
|
+
};
|
|
330
|
+
}
|
|
331
|
+
// A fallback names its endpoint even on the model's own provider, as the
|
|
332
|
+
// catalog has it; undefined when the catalog has none.
|
|
333
|
+
function registryConfig(modelId, provider) {
|
|
334
|
+
try {
|
|
335
|
+
const model = buildModel(pi, modelId, null);
|
|
336
|
+
if (typeof model.api !== "string" || typeof model.baseUrl !== "string")
|
|
337
|
+
return undefined;
|
|
338
|
+
return {
|
|
339
|
+
provider,
|
|
340
|
+
native_model_id: nativeModelId(modelId),
|
|
341
|
+
api: model.api,
|
|
342
|
+
base_url: model.baseUrl,
|
|
343
|
+
cost: priceFor(modelId, provider) ?? { input: 0, output: 0 },
|
|
344
|
+
};
|
|
345
|
+
}
|
|
346
|
+
catch {
|
|
347
|
+
return undefined;
|
|
278
348
|
}
|
|
279
|
-
if (provider === "meta")
|
|
280
|
-
return clientHarness === "muse_code" ? "meta_muse" : null;
|
|
281
|
-
if (provider === "openai")
|
|
282
|
-
return "openai_codex";
|
|
283
|
-
if (provider === "opencode-go")
|
|
284
|
-
return "opencode_go";
|
|
285
|
-
return null;
|
|
286
349
|
}
|
|
287
|
-
// A
|
|
288
|
-
//
|
|
289
|
-
function
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
350
|
+
// A model's price as a provider serves it, for estimates; a plan bills no
|
|
351
|
+
// tokens.
|
|
352
|
+
function priceFor(modelId, provider) {
|
|
353
|
+
const served = providerModel(modelId, provider);
|
|
354
|
+
return served === undefined
|
|
355
|
+
? registeredModelPrice(modelId)
|
|
356
|
+
: registeredModelPrice(`${provider}/${served.native_model_id}`);
|
|
293
357
|
}
|
|
294
358
|
function thinkingLevels(models) {
|
|
295
359
|
return Object.fromEntries(models.flatMap((model) => model.thinking ? [[model.id, model.thinking]] : []));
|
|
@@ -299,27 +363,30 @@ const SUBSCRIPTION_PLAN_NAMES = {
|
|
|
299
363
|
openai_codex: "ChatGPT",
|
|
300
364
|
meta_muse: "Muse Code",
|
|
301
365
|
opencode_go: "OpenCode Go",
|
|
366
|
+
github_copilot: "GitHub Copilot",
|
|
367
|
+
xai_grok: "Grok",
|
|
368
|
+
vercel_token_pass: "Vercel Token Pass",
|
|
302
369
|
};
|
|
303
370
|
/**
|
|
304
|
-
* Providers a router lists that no credential can serve: no API key
|
|
305
|
-
* connected subscription the router allows
|
|
306
|
-
* held subscription as connected (the request-time
|
|
307
|
-
*
|
|
371
|
+
* Providers a router lists models of that no credential can serve: no API key
|
|
372
|
+
* and no connected subscription the router allows that serves them. Startup
|
|
373
|
+
* uses this, so it counts a held subscription as connected (the request-time
|
|
374
|
+
* 424 reports holds) and ignores which client a plan is limited to, since
|
|
375
|
+
* startup does not know the client.
|
|
308
376
|
*/
|
|
309
377
|
export async function providersWithoutCredentials(deps, router) {
|
|
310
|
-
const missing =
|
|
311
|
-
for (const
|
|
312
|
-
const
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
const
|
|
316
|
-
if (
|
|
378
|
+
const missing = new Set();
|
|
379
|
+
for (const model of allRouterModels(router)) {
|
|
380
|
+
const provider = modelProvider(model);
|
|
381
|
+
if (missing.has(provider))
|
|
382
|
+
continue;
|
|
383
|
+
const plans = router.subscriptions ? modelSubscriptions(model.id) : [];
|
|
384
|
+
if (plans.some((plan) => deps.subscriptions.list(plan).length > 0))
|
|
317
385
|
continue;
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
missing.push(provider);
|
|
386
|
+
if (await configuredProviderApiKey(deps, provider) === undefined)
|
|
387
|
+
missing.add(provider);
|
|
321
388
|
}
|
|
322
|
-
return missing;
|
|
389
|
+
return [...missing];
|
|
323
390
|
}
|
|
324
391
|
function unavailableRouterError(routerId, exhausted, missing) {
|
|
325
392
|
const missingNote = missing.length > 0 ? ` Missing providers: ${missing.join(", ")}.` : "";
|
|
@@ -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
|
|
@@ -25,5 +26,5 @@
|
|
|
25
26
|
*/
|
|
26
27
|
export { freshAccessToken } from "./access.js";
|
|
27
28
|
export { handleSubscriptionRequest, type SubscriptionHttpDeps } from "./http.js";
|
|
28
|
-
export { CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, parseAuthorizationResponse, refreshOAuth, startOAuth, type OAuthAuthorization, type OAuthFetch, type OAuthOptions, type OAuthTokens, type SubscriptionProvider, } from "./oauth.js";
|
|
29
|
+
export { CODEX_APPROVAL_PENDING, GITHUB_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, XAI_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, parseAuthorizationResponse, refreshOAuth, startOAuth, type OAuthAuthorization, type OAuthFetch, type OAuthOptions, type OAuthTokens, type SubscriptionProvider, } from "./oauth.js";
|
|
29
30
|
export { SubscriptionStore, activeModelHolds, currentUsage, isHeld, type PendingOAuthSession, type SubscriptionCredential, type SubscriptionModelHold, } from "./store.js";
|
|
@@ -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
|
|
@@ -25,5 +26,5 @@
|
|
|
25
26
|
*/
|
|
26
27
|
export { freshAccessToken } from "./access.js";
|
|
27
28
|
export { handleSubscriptionRequest } from "./http.js";
|
|
28
|
-
export { CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, parseAuthorizationResponse, refreshOAuth, startOAuth, } from "./oauth.js";
|
|
29
|
+
export { CODEX_APPROVAL_PENDING, GITHUB_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, XAI_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, parseAuthorizationResponse, refreshOAuth, startOAuth, } from "./oauth.js";
|
|
29
30
|
export { SubscriptionStore, activeModelHolds, currentUsage, isHeld, } from "./store.js";
|
|
@@ -2,12 +2,14 @@
|
|
|
2
2
|
* OAuth protocols for personal subscriptions: Claude Code (PKCE, the user
|
|
3
3
|
* pastes back the `code#state` Anthropic shows), ChatGPT/Codex (device code,
|
|
4
4
|
* the gateway polls for approval), Muse Code (Meta's device code, then the
|
|
5
|
-
* subscription's Model API key minted from the sign-in token),
|
|
5
|
+
* subscription's Model API key minted from the sign-in token), OpenCode Go
|
|
6
6
|
* (the OpenCode Console device sign-in `opencode auth login` runs, scoped to
|
|
7
|
-
* the workspace that holds the plan)
|
|
7
|
+
* the workspace that holds the plan), GitHub Copilot, and Grok
|
|
8
|
+
* (each vendor's device sign-in, as its own coding agent runs it), and Vercel
|
|
9
|
+
* Token Pass (no protocol: the plan is a Token Pass key the user pastes).
|
|
8
10
|
* Every network call goes through the injected `fetch`.
|
|
9
11
|
*/
|
|
10
|
-
export type SubscriptionProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse" | "opencode_go";
|
|
12
|
+
export type SubscriptionProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse" | "opencode_go" | "github_copilot" | "xai_grok" | "vercel_token_pass";
|
|
11
13
|
export declare const SUBSCRIPTION_PROVIDERS: readonly SubscriptionProvider[];
|
|
12
14
|
export declare const OPENCODE_CLIENT_ID = "opencode-cli";
|
|
13
15
|
export declare const OPENCODE_APPROVAL_PENDING = "OpenCode approval is still pending. Enter the code in the OpenCode console, finish approval, then try again.";
|
|
@@ -45,6 +47,8 @@ export declare const CODEX_CLIENT_ID = "app_EMoamEEZ73f0CkXaXp7hrann";
|
|
|
45
47
|
export declare const CODEX_APPROVAL_PENDING = "OpenAI approval is still pending. Enter the code at OpenAI, finish approval, then try again.";
|
|
46
48
|
export declare const MUSE_CODE_CLIENT_ID = "1031625952748946";
|
|
47
49
|
export declare const META_APPROVAL_PENDING = "Meta approval is still pending. Enter the code at Meta, finish approval, then try again.";
|
|
50
|
+
export declare const GITHUB_APPROVAL_PENDING: string;
|
|
51
|
+
export declare const XAI_APPROVAL_PENDING: string;
|
|
48
52
|
export declare function startOAuth(provider: SubscriptionProvider, options: OAuthOptions): Promise<OAuthAuthorization>;
|
|
49
53
|
/**
|
|
50
54
|
* Finish a flow. Claude Code needs the pasted authorization response; the
|