@mupt-ai/dari-gateway 1.0.313 → 1.0.314
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 +17 -20
- package/dist/http/handler.js +1 -1
- package/dist/ingress/anthropic_messages.js +1 -1
- package/dist/ingress/models.js +1 -1
- package/dist/{link_client.d.ts → link/client.d.ts} +7 -11
- package/dist/{link_client.js → link/client.js} +5 -6
- package/dist/{ingress/link.d.ts → link/endpoints.d.ts} +3 -4
- package/dist/{ingress/link.js → link/endpoints.js} +158 -62
- package/dist/{runtime/link_grant_access.js → link/grant_access.js} +1 -1
- package/dist/link/grants.d.ts +151 -0
- package/dist/link/grants.js +275 -0
- package/dist/link/key_providers.d.ts +6 -0
- package/dist/link/key_providers.js +21 -0
- package/dist/link/self_hosted.d.ts +3 -0
- package/dist/link/self_hosted.js +166 -0
- package/dist/link/service.d.ts +85 -0
- package/dist/link/service.js +187 -0
- package/dist/link/sqlite_store.d.ts +74 -0
- package/dist/link/sqlite_store.js +381 -0
- package/dist/models/canonical_models.json +19 -0
- package/dist/platform/platform.d.ts +42 -47
- package/dist/runtime/explicit_model.js +1 -1
- package/dist/runtime/prepare_routed_completion.js +1 -1
- package/dist/self_host/main.js +2 -2
- package/dist/self_host/platform.js +4 -249
- package/dist/self_host/resolve.d.ts +2 -2
- package/dist/self_host/resolve.js +3 -19
- package/dist/self_host/stub_gateway.js +3 -3
- package/dist/self_host/subscriptions/http.js +2 -2
- package/dist/telemetry/report.js +1 -1
- package/package.json +2 -2
- package/src/http/handler.ts +1 -1
- package/src/ingress/anthropic_messages.ts +1 -1
- package/src/ingress/models.ts +1 -1
- package/src/{link_client.ts → link/client.ts} +11 -14
- package/src/{ingress/link.ts → link/endpoints.ts} +172 -69
- package/src/{runtime/link_grant_access.ts → link/grant_access.ts} +1 -1
- package/src/link/grants.ts +436 -0
- package/src/link/key_providers.ts +25 -0
- package/src/link/self_hosted.ts +186 -0
- package/src/link/service.ts +281 -0
- package/src/link/sqlite_store.ts +512 -0
- package/src/models/canonical_models.json +19 -0
- package/src/platform/platform.ts +39 -45
- package/src/runtime/explicit_model.ts +1 -1
- package/src/runtime/prepare_routed_completion.ts +1 -1
- package/src/self_host/main.ts +2 -2
- package/src/self_host/platform.ts +5 -267
- package/src/self_host/resolve.ts +6 -21
- package/src/self_host/stub_gateway.ts +3 -3
- package/src/self_host/subscriptions/http.ts +2 -2
- package/src/telemetry/report.ts +1 -1
- package/dist/self_host/link_store.d.ts +0 -167
- package/dist/self_host/link_store.js +0 -564
- package/src/self_host/link_store.ts +0 -782
- /package/dist/{ingress/link_assets.d.ts → link/assets.d.ts} +0 -0
- /package/dist/{ingress/link_assets.js → link/assets.js} +0 -0
- /package/dist/{runtime/link_budget.d.ts → link/budget.d.ts} +0 -0
- /package/dist/{runtime/link_budget.js → link/budget.js} +0 -0
- /package/dist/{models/link_errors.d.ts → link/errors.d.ts} +0 -0
- /package/dist/{models/link_errors.js → link/errors.js} +0 -0
- /package/dist/{ingress/link_font.d.ts → link/font.d.ts} +0 -0
- /package/dist/{ingress/link_font.js → link/font.js} +0 -0
- /package/dist/{runtime/link_grant_access.d.ts → link/grant_access.d.ts} +0 -0
- /package/dist/{runtime/link_in_flight.d.ts → link/in_flight.d.ts} +0 -0
- /package/dist/{runtime/link_in_flight.js → link/in_flight.js} +0 -0
- /package/src/{ingress/link_assets.ts → link/assets.ts} +0 -0
- /package/src/{runtime/link_budget.ts → link/budget.ts} +0 -0
- /package/src/{models/link_errors.ts → link/errors.ts} +0 -0
- /package/src/{ingress/link_font.ts → link/font.ts} +0 -0
- /package/src/{runtime/link_in_flight.ts → link/in_flight.ts} +0 -0
|
@@ -81,31 +81,26 @@ export type GatewayPlatform = {
|
|
|
81
81
|
link?: LinkPlatform;
|
|
82
82
|
};
|
|
83
83
|
/**
|
|
84
|
-
* Dari Link
|
|
85
|
-
* (
|
|
86
|
-
*
|
|
87
|
-
* issues tokens.
|
|
84
|
+
* Dari Link as the gateway's endpoints use it. A platform builds it with
|
|
85
|
+
* `linkPlatform` (link/service.ts) from its storage and its users, so the
|
|
86
|
+
* rules are the same everywhere.
|
|
88
87
|
*
|
|
89
88
|
* Methods throw HttpError(401) for a key that cannot act, HttpError(401,
|
|
90
89
|
* `invalid_client`) for a confidential client without its secret, and
|
|
91
90
|
* HttpError(400) with code `invalid_grant`, `refresh_race`, `invalid_client`,
|
|
92
91
|
* or `invalid_request` for a request the protocol refuses.
|
|
93
92
|
*
|
|
94
|
-
* A link token is a gateway key for `resolveRouter`: the platform
|
|
95
|
-
*
|
|
96
|
-
*
|
|
97
|
-
*
|
|
98
|
-
* `
|
|
99
|
-
*
|
|
100
|
-
*
|
|
93
|
+
* A link token is a gateway key for `resolveRouter`: the platform checks it
|
|
94
|
+
* with `linkTokenGrant` (live, within its budget) and serves it the default
|
|
95
|
+
* router on only the grant's subscriptions, never an API key or credits, and
|
|
96
|
+
* sets `link_grant_id` and `link_models`. It fails the request with 424
|
|
97
|
+
* `subscription_exhausted` (and `resets_at`), `subscription_client_mismatch`,
|
|
98
|
+
* or `model_not_granted` when no granted plan can serve. A revoked grant's
|
|
99
|
+
* tokens stop at once.
|
|
101
100
|
*/
|
|
102
101
|
export type LinkPlatform = {
|
|
103
|
-
/**
|
|
104
|
-
|
|
105
|
-
* names its consent page, and the gateway sends the authorization request
|
|
106
|
-
* there; otherwise the gateway serves the approval page itself.
|
|
107
|
-
*/
|
|
108
|
-
approval: LinkConsentPage | LinkApprovalPage;
|
|
102
|
+
/** What the gateway's approval and connections pages need. */
|
|
103
|
+
approval: LinkApprovalPage;
|
|
109
104
|
/**
|
|
110
105
|
* Hosts, besides loopback, an app may register an http (not https) redirect
|
|
111
106
|
* URI on: exact names, or `*.suffix` for any subdomain. For private dev hosts
|
|
@@ -179,24 +174,15 @@ export type LinkPlatform = {
|
|
|
179
174
|
}): Promise<boolean>;
|
|
180
175
|
};
|
|
181
176
|
/**
|
|
182
|
-
*
|
|
183
|
-
*
|
|
184
|
-
*
|
|
185
|
-
|
|
186
|
-
export type LinkConsentPage = {
|
|
187
|
-
consentUrl: string;
|
|
188
|
-
connectedAppsUrl: string;
|
|
189
|
-
};
|
|
190
|
-
/**
|
|
191
|
-
* What the gateway's own approval page needs from the platform. The page
|
|
192
|
-
* needs no account: a user connects a plan by signing in to its provider, and
|
|
193
|
-
* the gateway remembers them in a signed cookie as an opaque subject, so their
|
|
194
|
-
* plans are there the next time an app asks.
|
|
177
|
+
* What the gateway's approval and connections pages need. The pages need no
|
|
178
|
+
* account: a user connects a plan by signing in to its provider, and the
|
|
179
|
+
* gateway remembers them in a signed cookie as a subject, so their plans are
|
|
180
|
+
* there the next time an app asks and they manage their connections there.
|
|
195
181
|
*/
|
|
196
182
|
export type LinkApprovalPage = {
|
|
197
183
|
/**
|
|
198
|
-
* The secret that signs the
|
|
199
|
-
*
|
|
184
|
+
* The secret that signs the pages' cookies. Throws HttpError(503,
|
|
185
|
+
* `link_not_configured`) when the platform has none.
|
|
200
186
|
*/
|
|
201
187
|
sessionSecret(): string;
|
|
202
188
|
/** The kinds of plan a user can connect on the page, in the order offered. */
|
|
@@ -205,24 +191,22 @@ export type LinkApprovalPage = {
|
|
|
205
191
|
keyProviders: readonly LinkKeyProvider[];
|
|
206
192
|
/**
|
|
207
193
|
* Add the user's API key for one of `keyProviders`, replacing their earlier
|
|
208
|
-
* key for it
|
|
194
|
+
* key for it; without a subject, the key makes a new user. Throws
|
|
195
|
+
* HttpError(400) for a key the provider refuses.
|
|
209
196
|
*/
|
|
210
|
-
addKey(subject: string, provider: string, apiKey: string): Promise<
|
|
211
|
-
credentialId: string;
|
|
212
|
-
}>;
|
|
197
|
+
addKey(subject: string | null, provider: string, apiKey: string): Promise<LinkPlanAdded>;
|
|
213
198
|
/** The plans this user connected and the API keys they added, which an approval chooses among. */
|
|
214
199
|
subscriptions(subject: string): Promise<LinkSubscription[]>;
|
|
215
200
|
/** Start the provider's sign-in for a plan of this kind. */
|
|
216
|
-
startConnect(
|
|
201
|
+
startConnect(kind: SubscriptionKind): Promise<LinkConnect>;
|
|
217
202
|
/**
|
|
218
203
|
* Finish a sign-in `startConnect` began: with the code the provider showed
|
|
219
204
|
* the user, or for a provider that shows the user a code to enter, with
|
|
220
|
-
* nothing.
|
|
221
|
-
* HttpError(400) for a code the
|
|
205
|
+
* nothing. Without a subject, the plan makes a new user. Null while the
|
|
206
|
+
* provider still waits on the user. Throws HttpError(400) for a code the
|
|
207
|
+
* provider refuses or a sign-in that ended.
|
|
222
208
|
*/
|
|
223
|
-
completeConnect(subject: string, session: string, authorizationResponse: string): Promise<
|
|
224
|
-
credentialId: string;
|
|
225
|
-
} | null>;
|
|
209
|
+
completeConnect(subject: string | null, session: string, authorizationResponse: string): Promise<LinkPlanAdded | null>;
|
|
226
210
|
/**
|
|
227
211
|
* Forget one of the user's plans or API keys: its stored tokens or key are
|
|
228
212
|
* deleted, every app loses it, and a grant left with nothing is revoked.
|
|
@@ -238,6 +222,21 @@ export type LinkApprovalPage = {
|
|
|
238
222
|
approve(request: LinkApproval): Promise<{
|
|
239
223
|
code: string;
|
|
240
224
|
}>;
|
|
225
|
+
/** The user's live grants, oldest first, as the connections page shows them. */
|
|
226
|
+
connections(subject: string): Promise<LinkConnection[]>;
|
|
227
|
+
/** The user ends one of their grants; false when they have none by that id. */
|
|
228
|
+
disconnect(subject: string, grantId: string): Promise<boolean>;
|
|
229
|
+
/** Replace one of the user's grants' budget (empty removes it); false when they have none by that id. */
|
|
230
|
+
setBudget(subject: string, grantId: string, budget: LinkBudget[]): Promise<boolean>;
|
|
231
|
+
};
|
|
232
|
+
/** A plan or API key the user added, and who they are now. */
|
|
233
|
+
export type LinkPlanAdded = {
|
|
234
|
+
subject: string;
|
|
235
|
+
credentialId: string;
|
|
236
|
+
};
|
|
237
|
+
/** One of a user's grants on the connections page. */
|
|
238
|
+
export type LinkConnection = LinkGrantDetail & {
|
|
239
|
+
usage: LinkUsageTotals;
|
|
241
240
|
};
|
|
242
241
|
/** A model provider or gateway whose API key a user can add on the approval page. */
|
|
243
242
|
export type LinkKeyProvider = {
|
|
@@ -252,7 +251,7 @@ export type LinkConnect = {
|
|
|
252
251
|
};
|
|
253
252
|
/**
|
|
254
253
|
* The most tokens a grant's app may use in a rolling window, across all of
|
|
255
|
-
* the grant's plans and API keys. See
|
|
254
|
+
* the grant's plans and API keys. See link/budget.ts for how tokens
|
|
256
255
|
* are counted.
|
|
257
256
|
*/
|
|
258
257
|
export type LinkBudget = {
|
|
@@ -365,10 +364,6 @@ export type LinkUsage = LinkUsageTotals & {
|
|
|
365
364
|
export type LinkGrantDetail = Omit<LinkGrant, "credentialIds" | "budget"> & {
|
|
366
365
|
budget: LinkBudgetStanding[];
|
|
367
366
|
subscriptions: LinkSubscription[];
|
|
368
|
-
user: {
|
|
369
|
-
email: string | null;
|
|
370
|
-
name: string | null;
|
|
371
|
-
} | null;
|
|
372
367
|
};
|
|
373
368
|
export type ResolveRouterRequest = {
|
|
374
369
|
routerId: string;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { HttpError } from "../http/errors.js";
|
|
2
|
-
import { modelNotServed } from "../
|
|
2
|
+
import { modelNotServed } from "../link/errors.js";
|
|
3
3
|
import { explicitModelId } from "../protocol/input/router_model.js";
|
|
4
4
|
/* A request for `dari/model/<id>` is served by exactly that enabled model,
|
|
5
5
|
with no selector or lease: the user chose it, like picking a
|
|
@@ -11,7 +11,7 @@ import { resolveRouter } from "../strategies/routing.js";
|
|
|
11
11
|
import { RequestReporter } from "../telemetry/report.js";
|
|
12
12
|
import { RoutingBillingFinalization } from "../telemetry/billing_finalization.js";
|
|
13
13
|
import { requestTags } from "./request_tags.js";
|
|
14
|
-
import { linkGrantAccess } from "
|
|
14
|
+
import { linkGrantAccess } from "../link/grant_access.js";
|
|
15
15
|
import { rolePrompt, withRoleModel } from "./role_model.js";
|
|
16
16
|
import { strictProviderAccess } from "./strict_provider_access.js";
|
|
17
17
|
import { scopedHarnessAgentId, scopedHarnessConversationId, scopedHarnessSessionId, } from "./harness_identity/index.js";
|
package/dist/self_host/main.js
CHANGED
|
@@ -14,7 +14,7 @@ import { checkProviderKey } from "../providers/key_check.js";
|
|
|
14
14
|
import { CANONICAL_MODELS } from "../models/canonical.js";
|
|
15
15
|
import { allRouterModels, loadGatewayConfig } from "./config.js";
|
|
16
16
|
import { configuredProviderApiKey, gatewayKeyIndex, providersWithoutCredentials } from "./resolve.js";
|
|
17
|
-
import {
|
|
17
|
+
import { SqliteLinkStore } from "../link/sqlite_store.js";
|
|
18
18
|
import { secretBoxFromEnv } from "./secret_box.js";
|
|
19
19
|
import { PrefixStore } from "./prefix_store.js";
|
|
20
20
|
import { handleRouterModelsRequest, ROUTER_MODELS_ROUTE, RouterModelStore } from "./router_models.js";
|
|
@@ -67,7 +67,7 @@ export async function startSelfHostedGateway(env = process.env) {
|
|
|
67
67
|
const prefixes = new PrefixStore(db);
|
|
68
68
|
const sessionPins = new SessionPinStore(db);
|
|
69
69
|
const routerModels = new RouterModelStore(db);
|
|
70
|
-
const links = new
|
|
70
|
+
const links = new SqliteLinkStore(db, secrets);
|
|
71
71
|
// Pi's provider auth reads each provider's standard key variable, such as
|
|
72
72
|
// OPENAI_API_KEY, from this environment only.
|
|
73
73
|
const piModels = builtinModels({
|
|
@@ -1,15 +1,8 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import { linkGrantRevoked, linkTokenExpired } from "../models/link_errors.js";
|
|
1
|
+
import { errorCode } from "../http/errors.js";
|
|
2
|
+
import { selfHostedLink } from "../link/self_hosted.js";
|
|
4
3
|
import { subscriptionOAuthProviderFor } from "../providers/subscription_limits.js";
|
|
5
|
-
import {
|
|
6
|
-
import {
|
|
7
|
-
import { CANONICAL_MODELS } from "../models/canonical.js";
|
|
8
|
-
import { LINK_KEY_GATEWAYS, gatewayFor } from "../models/gateways.js";
|
|
9
|
-
import { checkProviderKey } from "../providers/key_check.js";
|
|
10
|
-
import { linkCompleteThrough } from "../runtime/link_in_flight.js";
|
|
11
|
-
import { gatewayKeyIndex, resolveSelfHostedRouter } from "./resolve.js";
|
|
12
|
-
import { CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, currentUsage, freshAccessToken, startOAuth, } from "./subscriptions/index.js";
|
|
4
|
+
import { resolveSelfHostedRouter } from "./resolve.js";
|
|
5
|
+
import { freshAccessToken } from "./subscriptions/index.js";
|
|
13
6
|
/**
|
|
14
7
|
* The self-hosted platform: routers from the config file, subscriptions,
|
|
15
8
|
* Dari Link grants, prefix-cache state, and session pins in the gateway's
|
|
@@ -108,241 +101,3 @@ export function createSelfHostedPlatform(deps) {
|
|
|
108
101
|
link: selfHostedLink(deps),
|
|
109
102
|
};
|
|
110
103
|
}
|
|
111
|
-
const PROVIDER_NAMES = {
|
|
112
|
-
anthropic: "Anthropic",
|
|
113
|
-
openai: "OpenAI",
|
|
114
|
-
meta: "Meta",
|
|
115
|
-
moonshotai: "Moonshot AI",
|
|
116
|
-
xai: "xAI",
|
|
117
|
-
};
|
|
118
|
-
// Whose API key a user can add on the approval page: each provider with
|
|
119
|
-
// catalog models this gateway can call with a key, then the gateways.
|
|
120
|
-
const LINK_KEY_PROVIDERS = [
|
|
121
|
-
...[...new Set(CANONICAL_MODELS.map((model) => providerForModel(model.id)))]
|
|
122
|
-
.filter((provider) => getBuiltinProviders().includes(provider))
|
|
123
|
-
.map((provider) => ({ id: provider, name: PROVIDER_NAMES[provider] ?? provider })),
|
|
124
|
-
...LINK_KEY_GATEWAYS.map((gateway) => ({ id: gateway, name: gatewayFor(gateway).label })),
|
|
125
|
-
];
|
|
126
|
-
// A user of the approval page connects their own plans there, which serve
|
|
127
|
-
// only the grants they approve; a gateway key manages every grant, and apps
|
|
128
|
-
// register with one or openly.
|
|
129
|
-
function selfHostedLink(deps) {
|
|
130
|
-
// A provider the operator points at its own endpoint takes users' keys only
|
|
131
|
-
// when that endpoint takes a key too: one without (a proxy that adds its own
|
|
132
|
-
// credential) would serve anyone's "key" on the operator's account.
|
|
133
|
-
const keyProviders = LINK_KEY_PROVIDERS.filter((provider) => {
|
|
134
|
-
const endpoint = deps.config.providers[provider.id];
|
|
135
|
-
return endpoint === undefined || endpoint.apiKeyEnv !== undefined;
|
|
136
|
-
});
|
|
137
|
-
const requireGatewayKey = (apiKey) => {
|
|
138
|
-
if (gatewayKeyIndex(deps.gatewayKeys, apiKey) === null) {
|
|
139
|
-
throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
|
|
140
|
-
}
|
|
141
|
-
};
|
|
142
|
-
// The cookie that remembers an approval page's user is signed with
|
|
143
|
-
// DARI_LINK_SESSION_SECRET; without it a process signs with a secret of its
|
|
144
|
-
// own, and a restart forgets who connected which plans.
|
|
145
|
-
const sessionSecret = deps.env.DARI_LINK_SESSION_SECRET?.trim() || randomBytes(32).toString("base64url");
|
|
146
|
-
const granted = (credentialIds) => [
|
|
147
|
-
...deps.subscriptions.withIds(credentialIds).map(linkSubscription),
|
|
148
|
-
...deps.links.keysWithIds(credentialIds).map(linkKey),
|
|
149
|
-
];
|
|
150
|
-
// The live grant a grant's own access token names; a child token cannot
|
|
151
|
-
// read its grant or its usage.
|
|
152
|
-
const parentGrantId = (accessToken) => {
|
|
153
|
-
const auth = deps.links.authenticate(accessToken);
|
|
154
|
-
if (auth === null)
|
|
155
|
-
throw new HttpError(401, "Missing or invalid Dari Link access token.", "authentication_error");
|
|
156
|
-
if (auth.status === "expired")
|
|
157
|
-
throw linkTokenExpired();
|
|
158
|
-
if (auth.status === "revoked")
|
|
159
|
-
throw linkGrantRevoked(auth.revokedBy, auth.revokedAt);
|
|
160
|
-
if (auth.grant.pins !== undefined) {
|
|
161
|
-
throw new HttpError(403, "A child token cannot read its grant or its usage.", "permission_denied");
|
|
162
|
-
}
|
|
163
|
-
return auth.grant.id;
|
|
164
|
-
};
|
|
165
|
-
// Other people's subscriptions and keys are taken only by a gateway that
|
|
166
|
-
// encrypts what it stores.
|
|
167
|
-
const requireEncryption = () => {
|
|
168
|
-
if (!deps.subscriptions.encrypted) {
|
|
169
|
-
throw new HttpError(503, "This gateway cannot keep subscriptions safely yet. Its operator must set DARI_GATEWAY_ENCRYPTION_KEY.", "link_not_configured");
|
|
170
|
-
}
|
|
171
|
-
};
|
|
172
|
-
return {
|
|
173
|
-
httpRedirectHosts: deps.config.link?.allowHttpRedirectHosts ?? [],
|
|
174
|
-
approval: {
|
|
175
|
-
sessionSecret: () => sessionSecret,
|
|
176
|
-
connectable: SUBSCRIPTION_PROVIDERS,
|
|
177
|
-
keyProviders,
|
|
178
|
-
async subscriptions(subject) {
|
|
179
|
-
return [...deps.subscriptions.owned(subject).map(linkSubscription), ...deps.links.keys(subject).map(linkKey)];
|
|
180
|
-
},
|
|
181
|
-
async addKey(subject, provider, apiKey) {
|
|
182
|
-
requireEncryption();
|
|
183
|
-
const known = keyProviders.find((candidate) => candidate.id === provider);
|
|
184
|
-
if (known === undefined)
|
|
185
|
-
throw new HttpError(400, "Choose a provider to add a key for.", "invalid_request");
|
|
186
|
-
const check = await checkProviderKey({
|
|
187
|
-
provider,
|
|
188
|
-
key: apiKey,
|
|
189
|
-
...(deps.config.providers[provider] ? { endpoint: deps.config.providers[provider] } : {}),
|
|
190
|
-
fetch: deps.fetch,
|
|
191
|
-
});
|
|
192
|
-
if (check.result === "rejected") {
|
|
193
|
-
throw new HttpError(400, `${known.name} did not accept that key. Check it and try again.`, "invalid_request");
|
|
194
|
-
}
|
|
195
|
-
return { credentialId: deps.links.addKey(subject, provider, apiKey).id };
|
|
196
|
-
},
|
|
197
|
-
async startConnect(subject, kind) {
|
|
198
|
-
requireEncryption();
|
|
199
|
-
let authorization;
|
|
200
|
-
try {
|
|
201
|
-
authorization = await startOAuth(kind, { fetch: deps.fetch });
|
|
202
|
-
}
|
|
203
|
-
catch (error) {
|
|
204
|
-
if (error instanceof SubscriptionOAuthProviderError) {
|
|
205
|
-
throw new HttpError(502, "The provider did not start a sign-in.", "provider_error");
|
|
206
|
-
}
|
|
207
|
-
throw error;
|
|
208
|
-
}
|
|
209
|
-
const session = deps.subscriptions.createSession({
|
|
210
|
-
provider: kind,
|
|
211
|
-
flow: authorization.flow,
|
|
212
|
-
credentialName: null,
|
|
213
|
-
owner: subject,
|
|
214
|
-
expiresAt: authorization.expiresAt,
|
|
215
|
-
});
|
|
216
|
-
return { session: session.token, authorizationUrl: authorization.authorizationUrl, userCode: authorization.userCode };
|
|
217
|
-
},
|
|
218
|
-
async completeConnect(subject, token, authorizationResponse) {
|
|
219
|
-
const session = deps.subscriptions.getSession(token);
|
|
220
|
-
if (session === null || session.owner !== subject || session.expiresAt <= new Date()) {
|
|
221
|
-
throw new HttpError(400, "That sign-in ended. Start again.", "invalid_request");
|
|
222
|
-
}
|
|
223
|
-
let tokens;
|
|
224
|
-
try {
|
|
225
|
-
tokens = await completeOAuth(session.provider, session.flow, authorizationResponse, { fetch: deps.fetch });
|
|
226
|
-
}
|
|
227
|
-
catch (error) {
|
|
228
|
-
if (error instanceof SubscriptionOAuthInputError) {
|
|
229
|
-
if ([CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING].includes(error.message))
|
|
230
|
-
return null;
|
|
231
|
-
throw new HttpError(400, error.message, "invalid_request");
|
|
232
|
-
}
|
|
233
|
-
if (error instanceof SubscriptionOAuthProviderError) {
|
|
234
|
-
throw new HttpError(400, "The provider did not accept that sign-in. Try again.", "invalid_request");
|
|
235
|
-
}
|
|
236
|
-
throw error;
|
|
237
|
-
}
|
|
238
|
-
deps.subscriptions.deleteSession(token);
|
|
239
|
-
return { credentialId: deps.subscriptions.connect(tokens, null, new Date(), subject).id };
|
|
240
|
-
},
|
|
241
|
-
async remove(subject, credentialId) {
|
|
242
|
-
const plan = deps.subscriptions.owned(subject).find((credential) => credential.id === credentialId);
|
|
243
|
-
const removed = plan !== undefined
|
|
244
|
-
? deps.subscriptions.disconnect(plan.name, subject) !== null
|
|
245
|
-
: deps.links.removeKey(subject, credentialId);
|
|
246
|
-
if (removed)
|
|
247
|
-
deps.links.dropCredential(credentialId);
|
|
248
|
-
return removed;
|
|
249
|
-
},
|
|
250
|
-
async grant(subject, grantId, clientId) {
|
|
251
|
-
const grant = deps.links.grants().find((candidate) => candidate.id === grantId && candidate.clientId === clientId);
|
|
252
|
-
if (grant === undefined || deps.links.subject(grantId) !== subject)
|
|
253
|
-
return null;
|
|
254
|
-
return { credentialIds: grant.credentialIds, budget: grant.budget };
|
|
255
|
-
},
|
|
256
|
-
async approve(request) {
|
|
257
|
-
const connected = new Set([
|
|
258
|
-
...deps.subscriptions.owned(request.subject).map((credential) => credential.id),
|
|
259
|
-
...deps.links.keys(request.subject).map((key) => key.id),
|
|
260
|
-
]);
|
|
261
|
-
if (request.credentialIds.length === 0 || !request.credentialIds.every((id) => connected.has(id))) {
|
|
262
|
-
throw new HttpError(400, "Choose one or more connected subscriptions.", "invalid_request");
|
|
263
|
-
}
|
|
264
|
-
return { code: deps.links.approve(request) };
|
|
265
|
-
},
|
|
266
|
-
},
|
|
267
|
-
async registerApp({ apiKey, name, redirectUris, confidential }) {
|
|
268
|
-
if (apiKey !== undefined)
|
|
269
|
-
requireGatewayKey(apiKey);
|
|
270
|
-
return deps.links.registerApp(name, redirectUris, confidential === true);
|
|
271
|
-
},
|
|
272
|
-
async app(clientId) {
|
|
273
|
-
return deps.links.app(clientId);
|
|
274
|
-
},
|
|
275
|
-
async exchangeCode(request) {
|
|
276
|
-
return deps.links.exchangeCode(request);
|
|
277
|
-
},
|
|
278
|
-
async refresh(request) {
|
|
279
|
-
return deps.links.refresh(request);
|
|
280
|
-
},
|
|
281
|
-
async exchangeToken(request) {
|
|
282
|
-
return deps.links.exchangeToken(request);
|
|
283
|
-
},
|
|
284
|
-
async grant(accessToken) {
|
|
285
|
-
const grantId = parentGrantId(accessToken);
|
|
286
|
-
const grant = deps.links.grants().find((candidate) => candidate.id === grantId);
|
|
287
|
-
const { credentialIds, budget: _, ...rest } = grant;
|
|
288
|
-
const budget = deps.links.budgetStandings(grant.id).map((standing) => ({
|
|
289
|
-
...standing,
|
|
290
|
-
resetsAt: standing.resetsAt?.toISOString() ?? null,
|
|
291
|
-
}));
|
|
292
|
-
// The approval page knows its users only as opaque subjects.
|
|
293
|
-
return { ...rest, budget, subscriptions: granted(new Set(credentialIds)), user: null };
|
|
294
|
-
},
|
|
295
|
-
async usage({ accessToken, ...query }) {
|
|
296
|
-
const grantId = parentGrantId(accessToken);
|
|
297
|
-
// Read before the rows, so a request recorded in between is counted.
|
|
298
|
-
const completeThrough = linkCompleteThrough(grantId).toISOString();
|
|
299
|
-
return { ...deps.links.usage(grantId, query), completeThrough };
|
|
300
|
-
},
|
|
301
|
-
async revokeToken(request) {
|
|
302
|
-
deps.links.revokeToken(request);
|
|
303
|
-
},
|
|
304
|
-
async grants(apiKey) {
|
|
305
|
-
requireGatewayKey(apiKey);
|
|
306
|
-
return deps.links.grants();
|
|
307
|
-
},
|
|
308
|
-
async setBudget({ apiKey, grantId, budget }) {
|
|
309
|
-
requireGatewayKey(apiKey);
|
|
310
|
-
return deps.links.setBudget(grantId, budget);
|
|
311
|
-
},
|
|
312
|
-
async revokeGrant({ apiKey, grantId }) {
|
|
313
|
-
requireGatewayKey(apiKey);
|
|
314
|
-
return deps.links.revoke(grantId, "user");
|
|
315
|
-
},
|
|
316
|
-
};
|
|
317
|
-
}
|
|
318
|
-
// An API key as the approval page and the app see it: never the key itself.
|
|
319
|
-
function linkKey(key) {
|
|
320
|
-
return {
|
|
321
|
-
id: key.id,
|
|
322
|
-
provider: "api_key",
|
|
323
|
-
apiKeyProvider: key.provider,
|
|
324
|
-
name: LINK_KEY_PROVIDERS.find((provider) => provider.id === key.provider)?.name ?? key.provider,
|
|
325
|
-
label: `Key ending ${key.apiKey.slice(-4)}`,
|
|
326
|
-
accountEmail: null,
|
|
327
|
-
unavailableUntil: null,
|
|
328
|
-
usage: [],
|
|
329
|
-
};
|
|
330
|
-
}
|
|
331
|
-
function linkSubscription(credential) {
|
|
332
|
-
const now = new Date();
|
|
333
|
-
return {
|
|
334
|
-
id: credential.id,
|
|
335
|
-
provider: credential.provider,
|
|
336
|
-
name: credential.name,
|
|
337
|
-
label: credential.label,
|
|
338
|
-
accountEmail: credential.accountEmail,
|
|
339
|
-
unavailableUntil: credential.unavailableUntil !== null && credential.unavailableUntil > now
|
|
340
|
-
? credential.unavailableUntil.toISOString()
|
|
341
|
-
: null,
|
|
342
|
-
usage: (currentUsage(credential, now)?.windows ?? []).map((window) => ({
|
|
343
|
-
minutes: window.minutes,
|
|
344
|
-
utilization: window.utilization,
|
|
345
|
-
resetsAt: window.resetsAt.toISOString(),
|
|
346
|
-
})),
|
|
347
|
-
};
|
|
348
|
-
}
|
|
@@ -2,7 +2,7 @@ import { type RouterPrefixHit } from "@mupt-ai/dari-router/policy-engine";
|
|
|
2
2
|
import type { ResolveRouterRequest } from "../platform/platform.js";
|
|
3
3
|
import type { ResolvedRouter } from "../types.js";
|
|
4
4
|
import { type GatewayConfig, type RouterConfig } from "./config.js";
|
|
5
|
-
import type {
|
|
5
|
+
import type { SqliteLinkStore } from "../link/sqlite_store.js";
|
|
6
6
|
import type { RouterModelStore } from "./router_models.js";
|
|
7
7
|
import { type OAuthFetch, type SubscriptionStore } from "./subscriptions/index.js";
|
|
8
8
|
export declare const SELF_HOSTED_ORGANIZATION_ID = "self-hosted";
|
|
@@ -12,7 +12,7 @@ export type SelfHostedResolverDeps = {
|
|
|
12
12
|
routerModels: RouterModelStore;
|
|
13
13
|
gatewayKeys: readonly string[];
|
|
14
14
|
subscriptions: SubscriptionStore;
|
|
15
|
-
links:
|
|
15
|
+
links: SqliteLinkStore;
|
|
16
16
|
prefixHits: (args: {
|
|
17
17
|
routerId: string;
|
|
18
18
|
prefixHashes: readonly string[];
|
|
@@ -5,10 +5,10 @@ import { DEFAULT_ROUTER_ALIAS } from "../platform/routing_contract.js";
|
|
|
5
5
|
import { codexModelConfig, subscriptionClient, subscriptionModelProvider } from "../models/subscriptions.js";
|
|
6
6
|
import { CANONICAL_MODELS } from "../models/canonical.js";
|
|
7
7
|
import { gatewayFor } from "../models/gateways.js";
|
|
8
|
-
import {
|
|
8
|
+
import { linkGrantUnavailableError, modelNotServed, plansExhausted, plansForAnotherClient, } from "../link/errors.js";
|
|
9
9
|
import { registeredModelPrice } from "../providers/pi.js";
|
|
10
10
|
import { allRouterModels, routerModelsFor, } from "./config.js";
|
|
11
|
-
import {
|
|
11
|
+
import { linkTokenGrant } from "../link/service.js";
|
|
12
12
|
import { activeModelHolds, freshAccessToken, } from "./subscriptions/index.js";
|
|
13
13
|
// A self-hosted gateway is one tenant; these stand in for the hosted
|
|
14
14
|
// organization and the user a personal subscription belongs to.
|
|
@@ -29,19 +29,13 @@ export const SELF_HOSTED_USER_ID = "self-hosted";
|
|
|
29
29
|
*/
|
|
30
30
|
export async function resolveSelfHostedRouter(deps, request) {
|
|
31
31
|
const keyIndex = gatewayKeyIndex(deps.gatewayKeys, request.apiKey);
|
|
32
|
-
const grant = keyIndex === null ?
|
|
32
|
+
const grant = keyIndex === null ? await linkTokenGrant(deps.links, request.apiKey) : null;
|
|
33
33
|
if (keyIndex === null && grant === null) {
|
|
34
34
|
throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
|
|
35
35
|
}
|
|
36
36
|
if (grant !== null && request.routerId !== DEFAULT_ROUTER_ALIAS) {
|
|
37
37
|
throw new HttpError(403, "Dari Link tokens serve only the default router.", "permission_denied");
|
|
38
38
|
}
|
|
39
|
-
if (grant !== null) {
|
|
40
|
-
// A grant at its token budget serves nothing until its window rolls on.
|
|
41
|
-
const back = overBudgetUntil(deps.links.budgetStandings(grant.id));
|
|
42
|
-
if (back !== undefined)
|
|
43
|
-
throw linkUnavailableError(budgetExhausted(back));
|
|
44
|
-
}
|
|
45
39
|
const configured = deps.config.routers[request.routerId];
|
|
46
40
|
if (configured === undefined) {
|
|
47
41
|
throw new HttpError(404, `Router ${request.routerId} is not configured on this gateway.`, "router_not_found");
|
|
@@ -205,16 +199,6 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
205
199
|
}
|
|
206
200
|
// The grant a live link token belongs to, or null for a token that is not
|
|
207
201
|
// one. A dead token is refused with the reason.
|
|
208
|
-
function activeLinkGrant(links, token) {
|
|
209
|
-
const auth = links.authenticate(token);
|
|
210
|
-
if (auth === null)
|
|
211
|
-
return null;
|
|
212
|
-
if (auth.status === "expired")
|
|
213
|
-
throw linkTokenExpired();
|
|
214
|
-
if (auth.status === "revoked")
|
|
215
|
-
throw linkGrantRevoked(auth.revokedBy, auth.revokedAt);
|
|
216
|
-
return auth.grant;
|
|
217
|
-
}
|
|
218
202
|
/**
|
|
219
203
|
* The models a grant's request may be served: a child token's one model, or
|
|
220
204
|
* the router's own models followed by every other catalog model of the
|
|
@@ -50,8 +50,8 @@ import { tmpdir } from "node:os";
|
|
|
50
50
|
import { join } from "node:path";
|
|
51
51
|
import { fileURLToPath } from "node:url";
|
|
52
52
|
import { zstdDecompressSync } from "node:zlib";
|
|
53
|
-
import { linkUserCookie } from "../
|
|
54
|
-
import {
|
|
53
|
+
import { linkUserCookie } from "../link/endpoints.js";
|
|
54
|
+
import { SqliteLinkStore } from "../link/sqlite_store.js";
|
|
55
55
|
import { secretBoxFromEnv } from "./secret_box.js";
|
|
56
56
|
import { SubscriptionStore } from "./subscriptions/index.js";
|
|
57
57
|
// The approval page's user who connected the stand-in plans.
|
|
@@ -163,7 +163,7 @@ export async function startStubGateway(options = {}) {
|
|
|
163
163
|
}, null, new Date(), options.owner === "gateway" ? null : STUB_USER).id;
|
|
164
164
|
});
|
|
165
165
|
const keys = options.keys ?? [];
|
|
166
|
-
const links = new
|
|
166
|
+
const links = new SqliteLinkStore(new Database(dbPath), secrets);
|
|
167
167
|
const keyIds = keys.map((key) => links.addKey(STUB_USER, key, `stub-key-${key}`).id);
|
|
168
168
|
const stubUrl = `http://127.0.0.1:${provider.port}`;
|
|
169
169
|
const configPath = join(dir, "dari-gateway.yaml");
|
|
@@ -73,7 +73,7 @@ export async function handleSubscriptionRequest(request, deps) {
|
|
|
73
73
|
return json(200, summary(deps.store, found(deps.store.markAvailable(name, now), name), now));
|
|
74
74
|
}
|
|
75
75
|
if (action === "/auto-reset" && request.method === "POST") {
|
|
76
|
-
throw new HttpError(400, "Spending banked
|
|
76
|
+
throw new HttpError(400, "Spending banked limit resets is not supported by this gateway.");
|
|
77
77
|
}
|
|
78
78
|
return null;
|
|
79
79
|
}
|
|
@@ -190,7 +190,7 @@ function credentialBody(credential, active, now) {
|
|
|
190
190
|
// The share of its tightest window the plan last reported used, while
|
|
191
191
|
// that window has not reset; null when it reports none.
|
|
192
192
|
usage: usageBody(credential, now),
|
|
193
|
-
// Spending banked
|
|
193
|
+
// Spending banked limit resets is hosted-only.
|
|
194
194
|
auto_redeem_resets: false,
|
|
195
195
|
};
|
|
196
196
|
}
|
package/dist/telemetry/report.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// fire-and-forget; streams hold their terminal marker on the prefix-state
|
|
4
4
|
// write so the immediate next turn can see next_model. Reporting failures are
|
|
5
5
|
// always logged and swallowed.
|
|
6
|
-
import { linkRequestRecorded, linkRequestStarted } from "../
|
|
6
|
+
import { linkRequestRecorded, linkRequestStarted } from "../link/in_flight.js";
|
|
7
7
|
import { selectPrefixHit, } from "@mupt-ai/dari-router/policy-engine";
|
|
8
8
|
import { errorCode } from "../http/errors.js";
|
|
9
9
|
import { executionProviderForModel } from "../models/execution_provider.js";
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mupt-ai/dari-gateway",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.314",
|
|
4
4
|
"description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@aws-sdk/client-sts": "3.1063.0",
|
|
55
|
-
"@mupt-ai/dari-router": "1.0.
|
|
55
|
+
"@mupt-ai/dari-router": "1.0.314",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.1"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
package/src/http/handler.ts
CHANGED
|
@@ -2,7 +2,7 @@ import {
|
|
|
2
2
|
handleResponses,
|
|
3
3
|
handleResponsesWebSocketFallback,
|
|
4
4
|
} from "../ingress/codex.js";
|
|
5
|
-
import { handleLinkRequest, LINK_METADATA_PATH, LINK_ROUTE_PREFIX } from "../
|
|
5
|
+
import { handleLinkRequest, LINK_METADATA_PATH, LINK_ROUTE_PREFIX } from "../link/endpoints.js";
|
|
6
6
|
import { handleModels } from "../ingress/models.js";
|
|
7
7
|
import { handleMuseCodeModels } from "../ingress/muse_models.js";
|
|
8
8
|
import { handleChatCompletions } from "../ingress/chat_completions.js";
|
|
@@ -3,7 +3,7 @@ import { anthropicMessagesResponse } from "../protocol/output/anthropic_messages
|
|
|
3
3
|
import { anthropicMessagesSseStream } from "../protocol/output/anthropic_messages_stream.js";
|
|
4
4
|
import { anthropicToken } from "../http/auth.js";
|
|
5
5
|
import { errorResponseHeaders, HttpError, normalizeError } from "../http/errors.js";
|
|
6
|
-
import { LINK_GRANT_ERROR_CODES, LINK_TOKEN_ERROR_CODES } from "../
|
|
6
|
+
import { LINK_GRANT_ERROR_CODES, LINK_TOKEN_ERROR_CODES } from "../link/errors.js";
|
|
7
7
|
import { captureRequestError } from "../observability/errors.js";
|
|
8
8
|
import { anthropicMessagesToInteraction } from "../protocol/input/anthropic_messages.js";
|
|
9
9
|
import { explicitModelId, linkTokenModel } from "../protocol/input/router_model.js";
|
package/src/ingress/models.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
|
|
9
9
|
import { anthropicToken, bearerToken } from "../http/auth.js";
|
|
10
10
|
import { errorResponse, HttpError } from "../http/errors.js";
|
|
11
|
-
import { LINK_GRANT_ERROR_CODES } from "../
|
|
11
|
+
import { LINK_GRANT_ERROR_CODES } from "../link/errors.js";
|
|
12
12
|
import { captureRequestError } from "../observability/errors.js";
|
|
13
13
|
import { anthropicErrorResponse } from "./anthropic_messages.js";
|
|
14
14
|
import { listModelCatalog } from "../models/catalog.js";
|