@mupt-ai/dari-gateway 1.0.342 → 1.0.344
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/dist/link/client.d.ts +40 -12
- package/dist/link/client.js +70 -15
- package/dist/link/endpoints.js +193 -33
- package/dist/link/errors.js +5 -2
- package/dist/link/grants.d.ts +7 -0
- package/dist/link/grants.js +31 -0
- package/dist/link/service.d.ts +1 -0
- package/dist/link/service.js +24 -10
- package/dist/link/sqlite_store.js +6 -3
- package/dist/platform/platform.d.ts +4 -1
- package/dist/providers/execution.js +5 -0
- package/dist/self_host/resolve.js +1 -1
- package/dist/self_host/stub_gateway.js +86 -24
- package/dist/self_host/stub_main.js +1 -1
- package/dist/self_host/subscriptions/store.d.ts +2 -2
- package/dist/self_host/subscriptions/store.js +3 -3
- package/package.json +2 -2
- package/src/link/client.ts +102 -28
- package/src/link/endpoints.ts +195 -29
- package/src/link/errors.ts +5 -2
- package/src/link/grants.ts +30 -0
- package/src/link/service.ts +25 -9
- package/src/link/sqlite_store.ts +6 -3
- package/src/platform/platform.ts +5 -1
- package/src/providers/execution.ts +5 -0
- package/src/self_host/resolve.ts +1 -1
- package/src/self_host/stub_gateway.ts +93 -26
- package/src/self_host/stub_main.ts +1 -1
- package/src/self_host/subscriptions/store.ts +3 -3
package/dist/link/service.js
CHANGED
|
@@ -13,7 +13,7 @@ import { randomUUID } from "node:crypto";
|
|
|
13
13
|
import { HttpError } from "../http/errors.js";
|
|
14
14
|
import { budgetStandings, grantSpend, overBudgetUntil, usesSince, } from "./budget.js";
|
|
15
15
|
import { budgetExhausted, limitsReached, linkGrantRevoked, linkTokenExpired, linkUnavailableError } from "./errors.js";
|
|
16
|
-
import { LINK_CLIENT_SECRET_PREFIX, LINK_CODE_PREFIX, LINK_CODE_TTL_MS, linkGrants, linkHash, linkSecret, LINK_TOKEN_RETENTION_MS, TOKEN_PREFIX, } from "./grants.js";
|
|
16
|
+
import { LINK_CLIENT_SECRET_PREFIX, LINK_CODE_PREFIX, LINK_CODE_TTL_MS, linkGrants, linkHash, linkSecret, LINK_TOKEN_RETENTION_MS, registeredRedirect, TOKEN_PREFIX, } from "./grants.js";
|
|
17
17
|
/** The built-in app every personal endpoint's grant belongs to. */
|
|
18
18
|
export const LINK_PERSONAL_CLIENT_ID = "lnk_personal";
|
|
19
19
|
export function linkPlatform(store, users) {
|
|
@@ -24,10 +24,10 @@ export function linkPlatform(store, users) {
|
|
|
24
24
|
return grant !== null && (subject === null || grant.subject === subject) ? grant : null;
|
|
25
25
|
};
|
|
26
26
|
// A grant's budget windows and each granted plan or key's spend this month.
|
|
27
|
-
const standings = async (grant, now = new Date()) => {
|
|
27
|
+
const standings = async (grant, known, now = new Date()) => {
|
|
28
28
|
const [uses, plans] = await Promise.all([
|
|
29
29
|
store.budgetUses(grant.id, usesSince(grant.budget, now)),
|
|
30
|
-
users.plansWithIds(grant.credentialIds),
|
|
30
|
+
known ?? users.plansWithIds(grant.credentialIds),
|
|
31
31
|
]);
|
|
32
32
|
return {
|
|
33
33
|
budget: budgetStandings(grant.budget, uses, now).map((standing) => ({
|
|
@@ -107,15 +107,17 @@ export function linkPlatform(store, users) {
|
|
|
107
107
|
},
|
|
108
108
|
async grant(subject, grantId, clientId) {
|
|
109
109
|
const grant = await ownGrant(subject, grantId);
|
|
110
|
-
return grant === null || grant.clientId !== clientId ? null : { credentialIds: grant.credentialIds, budget: grant.budget };
|
|
110
|
+
return grant === null || grant.clientId !== clientId ? null : { credentialIds: grant.credentialIds, budget: grant.budget, limits: grant.limits };
|
|
111
111
|
},
|
|
112
112
|
async approve(request) {
|
|
113
|
-
const
|
|
113
|
+
const plans = await users.plans(request.subject);
|
|
114
|
+
const owned = new Set(plans.map((plan) => plan.id));
|
|
114
115
|
if (request.credentialIds.length === 0 || !request.credentialIds.every((id) => owned.has(id))) {
|
|
115
116
|
throw new HttpError(400, "Choose one or more connected subscriptions.", "invalid_request");
|
|
116
117
|
}
|
|
118
|
+
requireLimitsFit(request.limits, request.credentialIds, plans);
|
|
117
119
|
const app = await store.appRecord(request.clientId);
|
|
118
|
-
if (app === null || !app.redirectUris
|
|
120
|
+
if (app === null || !registeredRedirect(app.redirectUris, request.redirectUri)) {
|
|
119
121
|
throw new HttpError(400, "Unknown app or redirect URI.", "invalid_client");
|
|
120
122
|
}
|
|
121
123
|
const code = linkSecret(LINK_CODE_PREFIX);
|
|
@@ -130,6 +132,7 @@ export function linkPlatform(store, users) {
|
|
|
130
132
|
codeExpiresAt: now + LINK_CODE_TTL_MS,
|
|
131
133
|
credentialIds: [...new Set(request.credentialIds)].sort(),
|
|
132
134
|
budget: request.budget,
|
|
135
|
+
limits: request.limits,
|
|
133
136
|
now,
|
|
134
137
|
});
|
|
135
138
|
if (grantId === null)
|
|
@@ -137,16 +140,23 @@ export function linkPlatform(store, users) {
|
|
|
137
140
|
return { code };
|
|
138
141
|
},
|
|
139
142
|
async connections(subject) {
|
|
140
|
-
|
|
141
|
-
|
|
143
|
+
const grants = await store.grants(subject);
|
|
144
|
+
// One lookup for every grant's plans, not one per grant per use.
|
|
145
|
+
const plans = await users.plansWithIds([...new Set(grants.flatMap((grant) => grant.credentialIds))]);
|
|
146
|
+
return await Promise.all(grants.map(async (grant) => {
|
|
147
|
+
const shared = plans.filter((plan) => grant.credentialIds.includes(plan.id));
|
|
148
|
+
const [{ byModel: _, ...usage }, standing] = await Promise.all([
|
|
149
|
+
protocol.usage(grant.id, { tags: {} }),
|
|
150
|
+
standings(grant, shared),
|
|
151
|
+
]);
|
|
142
152
|
return {
|
|
143
153
|
id: grant.id,
|
|
144
154
|
clientId: grant.clientId,
|
|
145
155
|
appName: grant.appName,
|
|
146
156
|
endpoint: grant.clientId === LINK_PERSONAL_CLIENT_ID,
|
|
147
157
|
createdAt: grant.createdAt,
|
|
148
|
-
...
|
|
149
|
-
subscriptions:
|
|
158
|
+
...standing,
|
|
159
|
+
subscriptions: shared,
|
|
150
160
|
usage,
|
|
151
161
|
};
|
|
152
162
|
}));
|
|
@@ -178,6 +188,10 @@ export function linkPlatform(store, users) {
|
|
|
178
188
|
const { clientSecretHash: _, ...app } = record;
|
|
179
189
|
return app;
|
|
180
190
|
},
|
|
191
|
+
async authenticateClient(request) {
|
|
192
|
+
const { clientSecretHash: _, ...app } = await protocol.authenticateClient(request);
|
|
193
|
+
return app;
|
|
194
|
+
},
|
|
181
195
|
exchangeCode: (request) => protocol.exchangeCode(request),
|
|
182
196
|
refresh: (request) => protocol.refresh(request),
|
|
183
197
|
exchangeToken: (request) => protocol.exchangeToken(request),
|
|
@@ -224,12 +224,14 @@ export class SqliteLinkStore {
|
|
|
224
224
|
}
|
|
225
225
|
saveGrant(request) {
|
|
226
226
|
const budget = request.budget.length === 0 ? null : JSON.stringify(request.budget);
|
|
227
|
+
const limits = request.limits.length === 0 ? null : JSON.stringify(request.limits);
|
|
227
228
|
if (request.grantId !== undefined) {
|
|
228
|
-
const updated = this.db.run(`UPDATE link_grants SET credential_ids = ?, budget = ?, code_hash = ?, code_challenge = ?, redirect_uri = ?,
|
|
229
|
+
const updated = this.db.run(`UPDATE link_grants SET credential_ids = ?, budget = ?, limits = ?, code_hash = ?, code_challenge = ?, redirect_uri = ?,
|
|
229
230
|
code_expires_at = ?
|
|
230
231
|
WHERE id = ? AND client_id = ? AND subject = ? AND revoked_at IS NULL`, [
|
|
231
232
|
JSON.stringify(request.credentialIds),
|
|
232
233
|
budget,
|
|
234
|
+
limits,
|
|
233
235
|
request.codeHash,
|
|
234
236
|
request.codeChallenge,
|
|
235
237
|
request.redirectUri,
|
|
@@ -242,8 +244,8 @@ export class SqliteLinkStore {
|
|
|
242
244
|
}
|
|
243
245
|
const id = `lgr_${randomUUID().replaceAll("-", "")}`;
|
|
244
246
|
this.db.run(`INSERT INTO link_grants (id, client_id, credential_ids, code_hash, code_challenge, redirect_uri,
|
|
245
|
-
code_expires_at, created_at, budget, subject)
|
|
246
|
-
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
247
|
+
code_expires_at, created_at, budget, limits, subject)
|
|
248
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`, [
|
|
247
249
|
id,
|
|
248
250
|
request.clientId,
|
|
249
251
|
JSON.stringify(request.credentialIds),
|
|
@@ -253,6 +255,7 @@ export class SqliteLinkStore {
|
|
|
253
255
|
request.codeExpiresAt,
|
|
254
256
|
request.now,
|
|
255
257
|
budget,
|
|
258
|
+
limits,
|
|
256
259
|
request.subject,
|
|
257
260
|
]);
|
|
258
261
|
return id;
|
|
@@ -129,6 +129,8 @@ export type LinkPlatform = {
|
|
|
129
129
|
}>;
|
|
130
130
|
/** The registered app, or null for an unknown client id. */
|
|
131
131
|
app(clientId: string): Promise<LinkApp | null>;
|
|
132
|
+
/** The app a client id and secret prove; throws `invalid_client` otherwise. */
|
|
133
|
+
authenticateClient(request: LinkClient): Promise<LinkApp>;
|
|
132
134
|
/** Redeem a code once for the grant's first tokens. */
|
|
133
135
|
exchangeCode(request: LinkCodeExchange): Promise<LinkTokens>;
|
|
134
136
|
/**
|
|
@@ -272,7 +274,7 @@ export type LinkApprovalPage = {
|
|
|
272
274
|
* One of the user's live grants for this app, which an update request edits
|
|
273
275
|
* in place; null when the user has none by that id.
|
|
274
276
|
*/
|
|
275
|
-
grant(subject: string, grantId: string, clientId: string): Promise<Pick<LinkGrant, "credentialIds" | "budget"> | null>;
|
|
277
|
+
grant(subject: string, grantId: string, clientId: string): Promise<Pick<LinkGrant, "credentialIds" | "budget" | "limits"> | null>;
|
|
276
278
|
/** Create a grant on the chosen subscriptions and return its one-time code. */
|
|
277
279
|
approve(request: LinkApproval): Promise<{
|
|
278
280
|
code: string;
|
|
@@ -400,6 +402,7 @@ export type LinkApproval = {
|
|
|
400
402
|
codeChallenge: string;
|
|
401
403
|
credentialIds: string[];
|
|
402
404
|
budget: LinkBudget[];
|
|
405
|
+
limits: LinkLimit[];
|
|
403
406
|
};
|
|
404
407
|
export type LinkCodeExchange = LinkClient & {
|
|
405
408
|
code: string;
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { HttpError } from "../http/errors.js";
|
|
2
|
+
import { linkUnavailableError, plansExhausted } from "../link/errors.js";
|
|
2
3
|
import { piMessageToInteractionOutput } from "./pi_output.js";
|
|
3
4
|
import { captureOperationalError } from "../observability/errors.js";
|
|
4
5
|
import { CustomerDisconnectedError, customerCanceledProviderMessage, } from "../runtime/customer_disconnect.js";
|
|
@@ -261,6 +262,10 @@ async function throwProviderFailure(args) {
|
|
|
261
262
|
// The client's retry is served by the user's next subscription.
|
|
262
263
|
throw new HttpError(503, subscriptionSwitchedMessage(limit), "subscription_switched", undefined, { "retry-after": "1" });
|
|
263
264
|
}
|
|
265
|
+
if (limit !== null && result.choice.execution.subscriptionLinkGrantId) {
|
|
266
|
+
// A Dari Link app gets the one plan-limit contract, without CLI advice.
|
|
267
|
+
throw linkUnavailableError(plansExhausted([limit.oauthProvider], limit.resetsAt));
|
|
268
|
+
}
|
|
264
269
|
if (limit !== null) {
|
|
265
270
|
const accountsUrl = gatewayPlatform().accountsUrl;
|
|
266
271
|
const codex = codexUsageLimitError(limit, accountsUrl);
|
|
@@ -34,7 +34,7 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
34
34
|
const keyIndex = gatewayKeyIndex(deps.gatewayKeys, request.apiKey);
|
|
35
35
|
const grant = keyIndex === null ? await linkTokenGrant(deps.links, { plansWithIds: async (ids) => deps.subscriptions.withIds(new Set(ids)).map(linkSubscription) }, request.apiKey) : null;
|
|
36
36
|
if (keyIndex === null && grant === null) {
|
|
37
|
-
throw new HttpError(401, "Missing or invalid gateway key.", "authentication_error");
|
|
37
|
+
throw new HttpError(401, "Missing or invalid gateway key or Dari Link access token.", "authentication_error");
|
|
38
38
|
}
|
|
39
39
|
if (grant !== null && request.routerId !== DEFAULT_ROUTER_ALIAS) {
|
|
40
40
|
throw new HttpError(403, "Dari Link tokens serve only the default router.", "permission_denied");
|
|
@@ -33,9 +33,10 @@
|
|
|
33
33
|
* Each lands in `gateway.messages` and `GET <controlUrl>/messages`.
|
|
34
34
|
*
|
|
35
35
|
* Error states on demand: `gateway.setState({...})` (or `POST
|
|
36
|
-
* <controlUrl>/state`): `limited: true`
|
|
37
|
-
*
|
|
38
|
-
*
|
|
36
|
+
* <controlUrl>/state`): `limited: true` holds every plan at its usage limit
|
|
37
|
+
* for an hour at once (`plans[].state` `plan_limit` with `available_at`) and
|
|
38
|
+
* makes every provider call a usage-limit refusal, so Link requests get 424
|
|
39
|
+
* `subscription_exhausted`; `limited: false` (or a state without it) clears it; `five_hour` and `weekly` (0 to 1) are the plan
|
|
39
40
|
* usage each default reply reports, which fills `plans[].usage`. A grant's
|
|
40
41
|
* token budget, once its replies' tokens reach it, leads to 424
|
|
41
42
|
* `grant_budget_exhausted`.
|
|
@@ -63,19 +64,36 @@ import { zstdDecompressSync } from "node:zlib";
|
|
|
63
64
|
import { authorizeUrl, LinkError } from "../link/client.js";
|
|
64
65
|
import { linkUserCookie } from "../link/endpoints.js";
|
|
65
66
|
import { SqliteLinkStore } from "../link/sqlite_store.js";
|
|
67
|
+
import { CANONICAL_MODELS } from "../models/canonical.js";
|
|
66
68
|
import { secretBoxFromEnv } from "./secret_box.js";
|
|
67
69
|
import { SubscriptionStore } from "./subscriptions/index.js";
|
|
68
70
|
// The approval page's user who connected the stand-in plans.
|
|
69
71
|
const STUB_USER = "stub-user";
|
|
70
72
|
export async function startStubGateway(options = {}) {
|
|
71
|
-
|
|
72
|
-
const
|
|
73
|
+
// A plain stub serves any app: a Claude Code plan serves only Claude Code.
|
|
74
|
+
const kinds = options.plans ?? ["openai_codex"];
|
|
75
|
+
const models = (options.models ?? ["anthropic/claude-sonnet-5-5", "openai/gpt-6.2-astra"]).map((model) => model.replace(/^dari\/model\//, ""));
|
|
76
|
+
const unknown = models.filter((model) => !CANONICAL_MODELS.some((entry) => entry.id === model));
|
|
77
|
+
if (unknown.length > 0) {
|
|
78
|
+
throw new Error(`startStubGateway models must be canonical "provider/model" ids, such as "openai/gpt-6.1-sol"; unknown: ${unknown.join(", ")}.`);
|
|
79
|
+
}
|
|
73
80
|
const gatewayKey = options.gatewayKey ?? "k";
|
|
74
81
|
const upstream = options.upstream;
|
|
75
82
|
const served = [];
|
|
76
83
|
const calls = [];
|
|
77
84
|
const messages = [];
|
|
78
85
|
let state = {};
|
|
86
|
+
// While `limited`: when the forced limit resets.
|
|
87
|
+
let limitedUntil = null;
|
|
88
|
+
// Set once the plans are stored.
|
|
89
|
+
let holdPlans = () => { };
|
|
90
|
+
// A forced limit holds the plans at once, as a refusal would, until it
|
|
91
|
+
// resets or `limited: false` clears it.
|
|
92
|
+
const setState = (next) => {
|
|
93
|
+
state = next;
|
|
94
|
+
limitedUntil = next.limited ? new Date(Date.now() + 3_600_000) : null;
|
|
95
|
+
holdPlans(limitedUntil);
|
|
96
|
+
};
|
|
79
97
|
let approve = async () => {
|
|
80
98
|
throw new Error("The gateway is not up yet.");
|
|
81
99
|
};
|
|
@@ -92,7 +110,7 @@ export async function startStubGateway(options = {}) {
|
|
|
92
110
|
if (pathname === "/messages" && request.method === "GET")
|
|
93
111
|
return Response.json({ messages });
|
|
94
112
|
if (pathname === "/state" && request.method === "POST") {
|
|
95
|
-
|
|
113
|
+
setState((await request.json()));
|
|
96
114
|
return Response.json({ state });
|
|
97
115
|
}
|
|
98
116
|
if (pathname === "/connect" && request.method === "POST") {
|
|
@@ -110,7 +128,7 @@ export async function startStubGateway(options = {}) {
|
|
|
110
128
|
return Response.json({ code: result.code, code_verifier: result.codeVerifier, state: result.state });
|
|
111
129
|
}
|
|
112
130
|
catch (error) {
|
|
113
|
-
return Response.json({ error: error instanceof LinkError ? error.code :
|
|
131
|
+
return Response.json({ error: error instanceof LinkError ? error.code : errorMessage(error) }, { status: 400 });
|
|
114
132
|
}
|
|
115
133
|
}
|
|
116
134
|
if (pathname === "/approve" && request.method === "POST") {
|
|
@@ -123,9 +141,12 @@ export async function startStubGateway(options = {}) {
|
|
|
123
141
|
return Response.json({ message: result.message, target_origin: result.targetOrigin });
|
|
124
142
|
}
|
|
125
143
|
catch (error) {
|
|
126
|
-
return Response.json({ error:
|
|
144
|
+
return Response.json({ error: errorMessage(error) }, { status: 400 });
|
|
127
145
|
}
|
|
128
146
|
}
|
|
147
|
+
// A provider key check (list models): the operator's stand-in keys are good.
|
|
148
|
+
if (pathname.endsWith("/models") && request.method === "GET")
|
|
149
|
+
return Response.json({ data: [] });
|
|
129
150
|
// The Codex usage report: a fresh plan, nothing used.
|
|
130
151
|
if (pathname.endsWith("/wham/usage")) {
|
|
131
152
|
return Response.json({ rate_limit: { primary_window: { used_percent: 0, reset_at: null } } });
|
|
@@ -171,8 +192,8 @@ export async function startStubGateway(options = {}) {
|
|
|
171
192
|
if (chat)
|
|
172
193
|
return chatReply(call.model);
|
|
173
194
|
const plan = kind === "openai_codex" ? kind : "anthropic_claude_code";
|
|
174
|
-
if (
|
|
175
|
-
return limitRefusal(plan);
|
|
195
|
+
if (limitedUntil !== null)
|
|
196
|
+
return limitRefusal(plan, limitedUntil);
|
|
176
197
|
return stubReply(plan, call.model, usageHeaders(plan, state));
|
|
177
198
|
},
|
|
178
199
|
});
|
|
@@ -194,6 +215,14 @@ export async function startStubGateway(options = {}) {
|
|
|
194
215
|
accountEmail: `${letter}@example.com`,
|
|
195
216
|
}, null, new Date(), options.owner === "gateway" ? null : STUB_USER).id;
|
|
196
217
|
});
|
|
218
|
+
holdPlans = (until) => {
|
|
219
|
+
for (const id of planIds) {
|
|
220
|
+
if (until === null)
|
|
221
|
+
store.markAvailable(store.get(id).name, new Date(), options.owner === "gateway" ? null : STUB_USER);
|
|
222
|
+
else
|
|
223
|
+
store.markUnavailable(id, until, "The stub gateway's forced usage limit.");
|
|
224
|
+
}
|
|
225
|
+
};
|
|
197
226
|
const keys = options.keys ?? [];
|
|
198
227
|
const links = new SqliteLinkStore(new Database(dbPath), secrets);
|
|
199
228
|
const keyIds = keys.map((key) => links.addKey(STUB_USER, key, `stub-key-${key}`).id);
|
|
@@ -208,14 +237,22 @@ providers:
|
|
|
208
237
|
baseUrl: ${stubUrl}
|
|
209
238
|
api: anthropic-messages
|
|
210
239
|
apiKeyEnv: STUB_ANTHROPIC_API_KEY
|
|
240
|
+
openai:
|
|
241
|
+
baseUrl: ${stubUrl}/openai
|
|
242
|
+
apiKeyEnv: STUB_OPENAI_API_KEY
|
|
211
243
|
openai-codex:
|
|
212
244
|
baseUrl: ${stubUrl}/backend-api
|
|
213
|
-
${keys.filter((key) => key
|
|
214
|
-
|
|
245
|
+
${keys.filter((key) => key === "openrouter").map((key) => ` ${key}:\n baseUrl: ${stubUrl}/${key}\n apiKeyEnv: STUB_${key.toUpperCase().replaceAll("-", "_")}_API_KEY\n`).join("")}${options.allowHttpRedirectHosts?.length ? `link:\n allowHttpRedirectHosts: [${options.allowHttpRedirectHosts.map((host) => JSON.stringify(host)).join(", ")}]\n` : ""}`);
|
|
246
|
+
// 0, like none, is a free one.
|
|
247
|
+
const port = options.port || await freePort();
|
|
215
248
|
const sessionSecret = randomBytes(32).toString("base64url");
|
|
216
249
|
// The gateway's own entrypoint, beside this file as source or as built.
|
|
217
250
|
const entrypoint = fileURLToPath(new URL(import.meta.url.endsWith(".ts") ? "./main.ts" : "./main.js", import.meta.url));
|
|
218
|
-
|
|
251
|
+
// The gateway exits once its stdin closes: when this process dies, however
|
|
252
|
+
// it dies, the gateway goes with it.
|
|
253
|
+
const child = `process.stdin.on("end", () => process.exit(0)).resume(); `
|
|
254
|
+
+ `await (await import(${JSON.stringify(entrypoint)})).runSelfHostedGateway();`;
|
|
255
|
+
const gateway = Bun.spawn([process.execPath, "-e", child], {
|
|
219
256
|
env: {
|
|
220
257
|
PATH: process.env.PATH ?? "",
|
|
221
258
|
DARI_GATEWAY_KEYS: gatewayKey,
|
|
@@ -224,13 +261,24 @@ ${keys.filter((key) => key !== "anthropic").map((key) => ` ${key}:\n baseUrl
|
|
|
224
261
|
DARI_LINK_SESSION_SECRET: sessionSecret,
|
|
225
262
|
DARI_GATEWAY_ENCRYPTION_KEY: encryptionKey,
|
|
226
263
|
// The operator's own keys for the stand-in providers.
|
|
227
|
-
...Object.fromEntries(["anthropic", ...keys].map((key) => [`STUB_${key.toUpperCase().replaceAll("-", "_")}_API_KEY`, "stub-operator-key"])),
|
|
264
|
+
...Object.fromEntries(["anthropic", "openai", ...keys].map((key) => [`STUB_${key.toUpperCase().replaceAll("-", "_")}_API_KEY`, "stub-operator-key"])),
|
|
228
265
|
PORT: String(port),
|
|
229
266
|
},
|
|
267
|
+
stdin: "pipe",
|
|
230
268
|
stdout: "pipe",
|
|
231
|
-
stderr: "
|
|
269
|
+
stderr: "pipe",
|
|
232
270
|
});
|
|
233
|
-
|
|
271
|
+
const killGateway = () => gateway.kill();
|
|
272
|
+
process.on("exit", killGateway);
|
|
273
|
+
const stderr = echo(gateway.stderr);
|
|
274
|
+
try {
|
|
275
|
+
await waitForLine(gateway.stdout, "dari-gateway listening");
|
|
276
|
+
}
|
|
277
|
+
catch {
|
|
278
|
+
await gateway.exited;
|
|
279
|
+
await provider.stop(true);
|
|
280
|
+
throw new Error(`The stub gateway did not start:\n${(await stderr).trim()}`);
|
|
281
|
+
}
|
|
234
282
|
const baseUrl = `http://127.0.0.1:${port}`;
|
|
235
283
|
const userCookie = linkUserCookie(sessionSecret, STUB_USER);
|
|
236
284
|
approve = async (authorizeUrl, approveOptions = {}) => {
|
|
@@ -279,10 +327,9 @@ ${keys.filter((key) => key !== "anthropic").map((key) => ` ${key}:\n baseUrl
|
|
|
279
327
|
approve: (url, approveOptions) => approve(url, approveOptions),
|
|
280
328
|
app,
|
|
281
329
|
connect: (connectOptions) => connect(connectOptions),
|
|
282
|
-
setState
|
|
283
|
-
state = next;
|
|
284
|
-
},
|
|
330
|
+
setState,
|
|
285
331
|
stop: async () => {
|
|
332
|
+
process.off("exit", killGateway);
|
|
286
333
|
gateway.kill();
|
|
287
334
|
await gateway.exited;
|
|
288
335
|
await provider.stop(true);
|
|
@@ -297,8 +344,10 @@ async function driveApproval(baseUrl, cookie, authorizeUrl, options) {
|
|
|
297
344
|
const params = [...url.searchParams];
|
|
298
345
|
const choose = await (await fetch(page, { headers: { cookie } })).text();
|
|
299
346
|
const csrf = /name="csrf" value="([^"]+)"/.exec(choose)?.[1];
|
|
300
|
-
if (csrf === undefined)
|
|
301
|
-
throw new Error(
|
|
347
|
+
if (csrf === undefined) {
|
|
348
|
+
throw new Error("The approval page offers this app nothing to approve: none of the stub user's plans or keys serves it. "
|
|
349
|
+
+ 'A Claude Code plan serves only an app that asks for clients: ["claude_code"].');
|
|
350
|
+
}
|
|
302
351
|
const usable = [...choose.matchAll(/name="credential_id" value="([^"]+)"/g)].map((match) => match[1]);
|
|
303
352
|
const decided = await fetch(`${baseUrl}${url.pathname}`, {
|
|
304
353
|
method: "POST",
|
|
@@ -323,9 +372,9 @@ async function driveApproval(baseUrl, cookie, authorizeUrl, options) {
|
|
|
323
372
|
const [message, targetOrigin] = JSON.parse(posted);
|
|
324
373
|
return { message, targetOrigin };
|
|
325
374
|
}
|
|
326
|
-
// A usage-limit refusal in the plan's provider protocol, resetting
|
|
327
|
-
function limitRefusal(kind) {
|
|
328
|
-
const reset = String(Math.floor(
|
|
375
|
+
// A usage-limit refusal in the plan's provider protocol, resetting at `until`.
|
|
376
|
+
function limitRefusal(kind, until) {
|
|
377
|
+
const reset = String(Math.floor(until.getTime() / 1000));
|
|
329
378
|
if (kind === "openai_codex") {
|
|
330
379
|
return Response.json({ error: { type: "usage_limit_reached", code: "usage_limit_reached", message: "The usage limit has been reached", resets_at: Number(reset) } }, { status: 429 });
|
|
331
380
|
}
|
|
@@ -430,6 +479,19 @@ async function freePort() {
|
|
|
430
479
|
await probe.stop(true);
|
|
431
480
|
return port;
|
|
432
481
|
}
|
|
482
|
+
function errorMessage(error) {
|
|
483
|
+
return error instanceof Error ? error.message : String(error);
|
|
484
|
+
}
|
|
485
|
+
// Copy the gateway's stderr to this process's, and resolve with all of it once it closes.
|
|
486
|
+
async function echo(stream) {
|
|
487
|
+
const decoder = new TextDecoder();
|
|
488
|
+
let output = "";
|
|
489
|
+
for await (const chunk of stream) {
|
|
490
|
+
process.stderr.write(chunk);
|
|
491
|
+
output += decoder.decode(chunk, { stream: true });
|
|
492
|
+
}
|
|
493
|
+
return output;
|
|
494
|
+
}
|
|
433
495
|
async function waitForLine(stream, marker) {
|
|
434
496
|
const reader = stream.getReader();
|
|
435
497
|
const decoder = new TextDecoder();
|
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
* Options: `--plans` (comma-separated
|
|
23
23
|
* `openai_codex` and `anthropic_claude_code`), `--keys` (comma-separated
|
|
24
24
|
* `anthropic`, `openai`, and `openrouter`: an API key of the plans' user for each), `--models` (the default
|
|
25
|
-
* router's models), `--key` (the gateway key), `--port` (the gateway's port),
|
|
25
|
+
* router's models), `--key` (the gateway key), `--port` (the gateway's port; 0 or none picks a free one),
|
|
26
26
|
* `--redirect-uri` (the redirect URI `app` is registered with),
|
|
27
27
|
* and `--allow-http-redirect-host` (repeatable: a host apps may register http
|
|
28
28
|
* redirect URIs on, such as `*.example.ts.net`).
|
|
@@ -132,8 +132,8 @@ export declare class SubscriptionStore {
|
|
|
132
132
|
* whether the subscription is connected.
|
|
133
133
|
*/
|
|
134
134
|
holdModel(id: string, model: string, until: Date, reason: string, now?: Date): boolean;
|
|
135
|
-
/** Clear a subscription's usage-limit holds. Null when it is not connected. */
|
|
136
|
-
markAvailable(name: string, now?: Date): SubscriptionCredential | null;
|
|
135
|
+
/** Clear a subscription's usage-limit holds (a Dari Link user's with `owner`). Null when it is not connected. */
|
|
136
|
+
markAvailable(name: string, now?: Date, owner?: string | null): SubscriptionCredential | null;
|
|
137
137
|
createSession(session: Omit<PendingOAuthSession, "token">, now?: Date): PendingOAuthSession;
|
|
138
138
|
/** A pending session, including an expired one so callers can say it expired. */
|
|
139
139
|
getSession(token: string): PendingOAuthSession | null;
|
|
@@ -368,9 +368,9 @@ export class SubscriptionStore {
|
|
|
368
368
|
}
|
|
369
369
|
return true;
|
|
370
370
|
}
|
|
371
|
-
/** Clear a subscription's usage-limit holds. Null when it is not connected. */
|
|
372
|
-
markAvailable(name, now = new Date()) {
|
|
373
|
-
const credential = this.getByName(name);
|
|
371
|
+
/** Clear a subscription's usage-limit holds (a Dari Link user's with `owner`). Null when it is not connected. */
|
|
372
|
+
markAvailable(name, now = new Date(), owner = null) {
|
|
373
|
+
const credential = this.getByName(name, owner);
|
|
374
374
|
if (credential === null)
|
|
375
375
|
return null;
|
|
376
376
|
this.db.run(`UPDATE subscription_credentials SET unavailable_until = NULL, unavailable_reason = NULL, model_holds = NULL,
|
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.344",
|
|
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.344",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.3"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|