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