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