@mupt-ai/dari-gateway 1.0.366 → 1.0.368
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 +4 -3
- package/dist/activity/conversation_detail.js +8 -0
- package/dist/link/client.d.ts +3 -1
- package/dist/link/client.js +4 -1
- package/dist/link/endpoints.js +38 -30
- package/dist/link/service.d.ts +1 -3
- package/dist/link/service.js +0 -1
- package/dist/platform/platform.d.ts +1 -11
- package/dist/protocol/input/anthropic_messages.js +3 -4
- package/dist/protocol/input/chat_completions.js +9 -13
- package/dist/protocol/input/chat_completions_validation.js +2 -7
- package/dist/protocol/input/openai_responses.js +3 -3
- package/dist/providers/execution.js +1 -0
- package/dist/providers/provider_call.d.ts +1 -0
- package/dist/providers/provider_call.js +1 -0
- package/dist/runtime/runtime_reporter.d.ts +1 -0
- package/dist/runtime/runtime_reporter.js +1 -0
- package/dist/self_host/connected.d.ts +5 -4
- package/dist/self_host/hosted_sync.d.ts +14 -23
- package/dist/self_host/hosted_sync.js +56 -120
- package/dist/self_host/main.js +0 -3
- package/dist/self_host/platform.js +2 -0
- package/dist/self_host/resolve.js +2 -1
- package/dist/self_host/stub_gateway.d.ts +1 -0
- package/dist/self_host/stub_gateway.js +7 -6
- package/dist/self_host/stub_main.js +1 -1
- package/dist/self_host/subscriptions/index.d.ts +1 -1
- package/dist/self_host/subscriptions/index.js +1 -1
- package/dist/self_host/subscriptions/store.d.ts +8 -6
- package/dist/self_host/subscriptions/store.js +8 -16
- package/dist/telemetry/report.js +8 -1
- package/dist/types.d.ts +1 -0
- package/package.json +2 -2
- package/src/activity/conversation_detail.ts +8 -0
- package/src/link/client.ts +7 -1
- package/src/link/endpoints.ts +42 -34
- package/src/link/service.ts +0 -4
- package/src/platform/platform.ts +2 -9
- package/src/protocol/input/anthropic_messages.ts +3 -9
- package/src/protocol/input/chat_completions.ts +8 -18
- package/src/protocol/input/chat_completions_validation.ts +2 -9
- package/src/protocol/input/openai_responses.ts +3 -8
- package/src/providers/execution.ts +1 -0
- package/src/providers/provider_call.ts +3 -0
- package/src/runtime/runtime_reporter.ts +3 -1
- package/src/self_host/connected.ts +5 -4
- package/src/self_host/hosted_sync.ts +51 -121
- package/src/self_host/main.ts +0 -3
- package/src/self_host/platform.ts +2 -1
- package/src/self_host/resolve.ts +2 -0
- package/src/self_host/stub_gateway.ts +12 -7
- package/src/self_host/stub_main.ts +1 -1
- package/src/self_host/subscriptions/index.ts +1 -0
- package/src/self_host/subscriptions/store.ts +14 -18
- package/src/telemetry/report.ts +8 -1
- package/src/types.ts +3 -0
|
@@ -1,25 +1,21 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { SUBSCRIPTION_PROVIDERS, } from "./subscriptions/index.js";
|
|
2
2
|
// Hosted Dari's per-call limit, and a size that stays well under its body cap.
|
|
3
3
|
const MAX_BATCH_ROWS = 16;
|
|
4
4
|
const MAX_BATCH_BYTES = 8 * 1024 * 1024;
|
|
5
5
|
// A row past this sheds its request and response bodies, as hosted ingest does.
|
|
6
6
|
const MAX_ROW_BYTES = 4 * 1024 * 1024;
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
const USAGE_INTERVAL_MS = 60_000;
|
|
10
|
-
// Plans are reported at least this often, so hosted can tell a computer that
|
|
11
|
-
// is gone (its plans stop counting as connected after a day) from a quiet one.
|
|
12
|
-
const HEARTBEAT_MS = 60 * 60_000;
|
|
7
|
+
// How often this computer's plans are checked against the accounts on Dari.
|
|
8
|
+
const ACCOUNTS_CHECK_MS = 60 * 60_000;
|
|
13
9
|
const RETRY_BASE_MS = 5_000;
|
|
14
10
|
const RETRY_MAX_MS = 15 * 60_000;
|
|
15
11
|
const DRAIN_INTERVAL_MS = 2_000;
|
|
16
12
|
/**
|
|
17
|
-
* What a gateway connected to hosted Dari tells it:
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
13
|
+
* What a gateway connected to hosted Dari tells it: the requests it served,
|
|
14
|
+
* for Activity, `POST /v1/gateway/requests`. Rows wait in a SQLite outbox,
|
|
15
|
+
* sent in batches with backoff until hosted takes them. Requests a private
|
|
16
|
+
* plan served are never queued. This computer's plans themselves never leave
|
|
17
|
+
* it; it only reads the accounts on Dari (`GET /v1/gateway/accounts`), to drop
|
|
18
|
+
* a plan whose account was since connected there.
|
|
23
19
|
*/
|
|
24
20
|
export class HostedSync {
|
|
25
21
|
db;
|
|
@@ -27,12 +23,8 @@ export class HostedSync {
|
|
|
27
23
|
hosted;
|
|
28
24
|
fetch;
|
|
29
25
|
now;
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
snapshotFailures = 0;
|
|
33
|
-
// Snapshots go one at a time, so an older one never lands after a newer one.
|
|
34
|
-
snapshots = Promise.resolve();
|
|
35
|
-
lastSnapshotAt = 0;
|
|
26
|
+
accountsTimer = null;
|
|
27
|
+
accountsFailures = 0;
|
|
36
28
|
drainTimer = null;
|
|
37
29
|
draining = null;
|
|
38
30
|
drainFailures = 0;
|
|
@@ -49,29 +41,21 @@ export class HostedSync {
|
|
|
49
41
|
queued_at INTEGER NOT NULL
|
|
50
42
|
)`);
|
|
51
43
|
}
|
|
52
|
-
/**
|
|
44
|
+
/** Check the accounts on Dari and send waiting requests now, then keep at it. */
|
|
53
45
|
start() {
|
|
54
|
-
this.
|
|
46
|
+
this.scheduleAccountsCheck(0);
|
|
55
47
|
this.drainTimer = setInterval(() => void this.drain(), DRAIN_INTERVAL_MS);
|
|
56
48
|
this.drainTimer.unref?.();
|
|
57
49
|
void this.drain();
|
|
58
50
|
}
|
|
59
51
|
stop() {
|
|
60
|
-
if (this.
|
|
61
|
-
clearTimeout(this.
|
|
52
|
+
if (this.accountsTimer !== null)
|
|
53
|
+
clearTimeout(this.accountsTimer);
|
|
62
54
|
if (this.drainTimer !== null)
|
|
63
55
|
clearInterval(this.drainTimer);
|
|
64
|
-
this.
|
|
56
|
+
this.accountsTimer = null;
|
|
65
57
|
this.drainTimer = null;
|
|
66
58
|
}
|
|
67
|
-
/** A plan was connected, removed, renamed, moved, held, or released. */
|
|
68
|
-
plansChanged() {
|
|
69
|
-
this.scheduleSnapshot(PLANS_DEBOUNCE_MS);
|
|
70
|
-
}
|
|
71
|
-
/** A plan reported usage or served a turn. */
|
|
72
|
-
usageChanged() {
|
|
73
|
-
this.scheduleSnapshot(Math.max(PLANS_DEBOUNCE_MS, this.lastSnapshotAt + USAGE_INTERVAL_MS - this.now()));
|
|
74
|
-
}
|
|
75
59
|
/** Queue a served request's log row for hosted Activity. */
|
|
76
60
|
enqueue(row) {
|
|
77
61
|
let json = JSON.stringify(row);
|
|
@@ -85,59 +69,35 @@ export class HostedSync {
|
|
|
85
69
|
}
|
|
86
70
|
this.db.run("INSERT INTO hosted_request_outbox (row_json, queued_at) VALUES (?, ?)", [json, this.now()]);
|
|
87
71
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
return {
|
|
92
|
-
gateway_id: this.hosted.gatewayId,
|
|
93
|
-
gateway_name: this.hosted.gatewayName,
|
|
94
|
-
subscriptions: this.subscriptions.list().filter((plan) => !plan.private).map((plan) => planReport(plan, now)),
|
|
95
|
-
};
|
|
96
|
-
}
|
|
97
|
-
// Keeps the earliest of the snapshots asked for.
|
|
98
|
-
scheduleSnapshot(delayMs) {
|
|
99
|
-
const dueAt = this.now() + delayMs;
|
|
100
|
-
if (this.snapshotTimer !== null && this.snapshotDueAt <= dueAt)
|
|
101
|
-
return;
|
|
102
|
-
if (this.snapshotTimer !== null)
|
|
103
|
-
clearTimeout(this.snapshotTimer);
|
|
104
|
-
this.snapshotDueAt = dueAt;
|
|
105
|
-
this.snapshotTimer = setTimeout(() => {
|
|
106
|
-
this.snapshotTimer = null;
|
|
107
|
-
this.snapshotDueAt = Infinity;
|
|
108
|
-
this.snapshots = this.snapshots.then(() => this.putSnapshot());
|
|
109
|
-
}, delayMs);
|
|
110
|
-
this.snapshotTimer.unref?.();
|
|
72
|
+
scheduleAccountsCheck(delayMs) {
|
|
73
|
+
this.accountsTimer = setTimeout(() => void this.checkAccounts(), delayMs);
|
|
74
|
+
this.accountsTimer.unref?.();
|
|
111
75
|
}
|
|
112
|
-
|
|
113
|
-
|
|
76
|
+
// A plan here whose account was connected on Dari after it was connected
|
|
77
|
+
// here: Dari's plan serves this computer too, so the copy here goes. Only
|
|
78
|
+
// the account id matches, never the email alone: one email can hold several
|
|
79
|
+
// ChatGPT workspaces or Claude organizations.
|
|
80
|
+
async checkAccounts() {
|
|
114
81
|
try {
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
82
|
+
const onDari = await readHostedAccounts(this.hosted, this.fetch);
|
|
83
|
+
this.accountsFailures = 0;
|
|
84
|
+
for (const plan of this.subscriptions.list()) {
|
|
85
|
+
if (plan.owner !== null || plan.private || plan.accountId === null)
|
|
86
|
+
continue;
|
|
87
|
+
const moved = onDari.some((account) => account.provider === plan.provider
|
|
88
|
+
&& account.accountId === plan.accountId
|
|
89
|
+
&& account.connectedAt !== undefined && account.connectedAt > plan.createdAt);
|
|
90
|
+
if (!moved)
|
|
91
|
+
continue;
|
|
92
|
+
this.subscriptions.disconnect(plan.name);
|
|
93
|
+
console.error(`${plan.name} is now connected on Dari; removed it from this computer`);
|
|
94
|
+
}
|
|
95
|
+
this.scheduleAccountsCheck(ACCOUNTS_CHECK_MS);
|
|
122
96
|
}
|
|
123
97
|
catch (error) {
|
|
124
|
-
this.
|
|
125
|
-
console.error("hosted
|
|
126
|
-
this.
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
// Hosted Dari names the reported plans whose account was since connected on
|
|
130
|
-
// Dari. Dari's plan serves this computer too, so the copy here goes, and
|
|
131
|
-
// disconnecting it reports the plans again.
|
|
132
|
-
dropPlansOnDari(localIds) {
|
|
133
|
-
if (!Array.isArray(localIds))
|
|
134
|
-
return;
|
|
135
|
-
for (const id of localIds) {
|
|
136
|
-
const plan = typeof id === "string" ? this.subscriptions.get(id) : null;
|
|
137
|
-
if (plan === null || plan.owner !== null || plan.private)
|
|
138
|
-
continue;
|
|
139
|
-
this.subscriptions.disconnect(plan.name);
|
|
140
|
-
console.error(`${plan.name} is now connected on Dari; removed it from this computer`);
|
|
98
|
+
this.accountsFailures += 1;
|
|
99
|
+
console.error("hosted accounts check failed", error instanceof Error ? error.message : String(error));
|
|
100
|
+
this.scheduleAccountsCheck(backoff(this.accountsFailures));
|
|
141
101
|
}
|
|
142
102
|
}
|
|
143
103
|
/** Send the queued request rows a batch at a time, unless hosted failed lately. */
|
|
@@ -203,8 +163,9 @@ export class HostedSync {
|
|
|
203
163
|
}
|
|
204
164
|
/**
|
|
205
165
|
* The user's plans on hosted Dari, for the check before a sign-in connects an
|
|
206
|
-
* account
|
|
207
|
-
*
|
|
166
|
+
* account and for dropping a plan here that moved there: `GET
|
|
167
|
+
* /v1/gateway/accounts` returns each one's provider, account identity, name,
|
|
168
|
+
* and when it was connected, never a token. Other computers may hold the same
|
|
208
169
|
* account, so only Dari's plans count.
|
|
209
170
|
*/
|
|
210
171
|
export async function readHostedAccounts(hosted, fetchImpl) {
|
|
@@ -225,9 +186,9 @@ export async function readHostedAccounts(hosted, fetchImpl) {
|
|
|
225
186
|
// Hosted Dari before this release also listed other computers' plans.
|
|
226
187
|
if (entry.where !== "dari")
|
|
227
188
|
continue;
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
189
|
+
// A provider this gateway does not know holds no account of a plan here.
|
|
190
|
+
if (!SUBSCRIPTION_PROVIDERS.includes(entry.provider))
|
|
191
|
+
continue;
|
|
231
192
|
let accountId = null;
|
|
232
193
|
if (typeof entry.account_id === "string")
|
|
233
194
|
accountId = entry.account_id;
|
|
@@ -237,43 +198,18 @@ export async function readHostedAccounts(hosted, fetchImpl) {
|
|
|
237
198
|
let name = null;
|
|
238
199
|
if (typeof entry.name === "string")
|
|
239
200
|
name = entry.name;
|
|
240
|
-
|
|
201
|
+
const connectedAt = typeof entry.connected_at === "string" ? new Date(entry.connected_at) : undefined;
|
|
202
|
+
accounts.push({
|
|
203
|
+
provider: entry.provider,
|
|
204
|
+
accountId,
|
|
205
|
+
accountEmail,
|
|
206
|
+
place: "dari",
|
|
207
|
+
name,
|
|
208
|
+
...(connectedAt === undefined || Number.isNaN(connectedAt.getTime()) ? {} : { connectedAt }),
|
|
209
|
+
});
|
|
241
210
|
}
|
|
242
211
|
return accounts;
|
|
243
212
|
}
|
|
244
213
|
function backoff(failures) {
|
|
245
214
|
return Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** Math.max(0, failures - 1));
|
|
246
215
|
}
|
|
247
|
-
// One plan as `PUT /v1/gateway/subscriptions` takes it. Usage uses the keys
|
|
248
|
-
// and formats hosted subscriptions keep in their metadata.
|
|
249
|
-
function planReport(plan, now) {
|
|
250
|
-
const held = isHeld(plan, now);
|
|
251
|
-
const usage = plan.usage;
|
|
252
|
-
return {
|
|
253
|
-
local_id: plan.id,
|
|
254
|
-
provider: plan.provider,
|
|
255
|
-
label: plan.label,
|
|
256
|
-
account_email: plan.accountEmail,
|
|
257
|
-
account_id: plan.accountId,
|
|
258
|
-
plan: null,
|
|
259
|
-
connected_at: plan.createdAt.toISOString(),
|
|
260
|
-
last_used_at: plan.lastUsedAt?.toISOString() ?? null,
|
|
261
|
-
unavailable_until: held ? plan.unavailableUntil.toISOString() : null,
|
|
262
|
-
unavailable_reason: held ? plan.unavailableReason : null,
|
|
263
|
-
model_holds: Object.fromEntries(activeModelHolds(plan, now).map((hold) => [
|
|
264
|
-
hold.model,
|
|
265
|
-
{ until: hold.until.toISOString(), reason: hold.reason },
|
|
266
|
-
])),
|
|
267
|
-
usage: usage === null ? {} : {
|
|
268
|
-
usage_utilization: usage.utilization.toFixed(4),
|
|
269
|
-
usage_resets_at: usage.resetsAt.toISOString(),
|
|
270
|
-
usage_windows: JSON.stringify(usage.windows.map((window) => ({
|
|
271
|
-
...(window.modelFamily === undefined ? {} : { model_family: window.modelFamily }),
|
|
272
|
-
minutes: window.minutes,
|
|
273
|
-
utilization: Math.round(window.utilization * 10_000) / 10_000,
|
|
274
|
-
resets_at: window.resetsAt.toISOString(),
|
|
275
|
-
}))),
|
|
276
|
-
usage_observed_at: usage.observedAt.toISOString(),
|
|
277
|
-
},
|
|
278
|
-
};
|
|
279
|
-
}
|
package/dist/self_host/main.js
CHANGED
|
@@ -106,9 +106,6 @@ export async function startSelfHostedGateway(env = process.env) {
|
|
|
106
106
|
// The hosted router, read once a minute, for both serving and routing calls.
|
|
107
107
|
const hostedRouter = hosted === null ? null : hostedRouters(hosted, fetch);
|
|
108
108
|
const baseUrls = providerBaseUrls(config.providers);
|
|
109
|
-
if (sync !== null) {
|
|
110
|
-
subscriptions.onChange = (change) => change === "usage" ? sync.usageChanged() : sync.plansChanged();
|
|
111
|
-
}
|
|
112
109
|
const platformDeps = {
|
|
113
110
|
activity,
|
|
114
111
|
config,
|
|
@@ -6,6 +6,7 @@ import { subscriptionOAuthProviderFor } from "../providers/subscription_limits.j
|
|
|
6
6
|
import { SELF_HOSTED_BLOB_BUCKET } from "./activity_store.js";
|
|
7
7
|
import { servedRouter } from "./router_specs.js";
|
|
8
8
|
import { gatewayKeyIndex, resolveSelfHostedRouter, SELF_HOSTED_ORGANIZATION_ID, } from "./resolve.js";
|
|
9
|
+
import { planAccount } from "./subscriptions/index.js";
|
|
9
10
|
import { refreshedAccessToken } from "./subscriptions/access.js";
|
|
10
11
|
import { hasBankedResets, providerBaseUrls, recoverHeldPlans } from "./subscriptions/resets.js";
|
|
11
12
|
/**
|
|
@@ -46,6 +47,7 @@ export function createSelfHostedPlatform(deps) {
|
|
|
46
47
|
return undefined;
|
|
47
48
|
return {
|
|
48
49
|
credentialId: next.id,
|
|
50
|
+
...planAccount(next),
|
|
49
51
|
apiKey: await refreshedAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
|
|
50
52
|
};
|
|
51
53
|
},
|
|
@@ -15,7 +15,7 @@ import { linkSubscription } from "../link/self_hosted.js";
|
|
|
15
15
|
import { linkTokenGrant } from "../link/service.js";
|
|
16
16
|
import { servedRouter } from "./router_specs.js";
|
|
17
17
|
import { refreshedAccessToken } from "./subscriptions/access.js";
|
|
18
|
-
import { activeModelHolds, freshAccessToken, } from "./subscriptions/index.js";
|
|
18
|
+
import { activeModelHolds, freshAccessToken, planAccount, } from "./subscriptions/index.js";
|
|
19
19
|
// A self-hosted gateway is one tenant; these stand in for the hosted
|
|
20
20
|
// organization and the user a personal subscription belongs to.
|
|
21
21
|
export const SELF_HOSTED_ORGANIZATION_ID = "self-hosted";
|
|
@@ -221,6 +221,7 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
221
221
|
apiKey: await planToken(first.plan),
|
|
222
222
|
subscription: first.plan.provider,
|
|
223
223
|
credentialId: first.plan.id,
|
|
224
|
+
...planAccount(first.plan),
|
|
224
225
|
};
|
|
225
226
|
}
|
|
226
227
|
else {
|
|
@@ -22,12 +22,12 @@
|
|
|
22
22
|
* `gateway.connect()` (or `POST <controlUrl>/connect`) is its user approving
|
|
23
23
|
* it: it resolves with what `DariLink.open` hands your page, `{code,
|
|
24
24
|
* codeVerifier, state}`, or rejects with the `LinkError` it would (`deny`).
|
|
25
|
-
* `clients`, `plans`, `keyProviders`, and `grantId` are `DariLink.open`'s.
|
|
25
|
+
* `clients`, `plans`, `keyProviders`, `allowPooling`, and `grantId` are `DariLink.open`'s.
|
|
26
26
|
*
|
|
27
27
|
* To drive an approval for an app you registered yourself:
|
|
28
28
|
* `gateway.approve(authorizeUrl)` (or `POST <controlUrl>/approve` with
|
|
29
29
|
* `{"url"}`) opens the approval page as the user who connected the stand-in
|
|
30
|
-
* plans,
|
|
30
|
+
* plans, keeps the plans the page ticks (or ticks `credentialIds`), approves (or
|
|
31
31
|
* denies with `deny`), and returns what the page hands the app:
|
|
32
32
|
* `{message, targetOrigin}`, the `web_message` post or the redirect's query.
|
|
33
33
|
* Each lands in `gateway.messages` and `GET <controlUrl>/messages`.
|
|
@@ -123,6 +123,7 @@ export async function startStubGateway(options = {}) {
|
|
|
123
123
|
...(body.clients ? { clients: body.clients } : {}),
|
|
124
124
|
...(body.plans ? { plans: body.plans } : {}),
|
|
125
125
|
...(body.key_providers ? { keyProviders: body.key_providers } : {}),
|
|
126
|
+
...(body.allow_pooling ? { allowPooling: true } : {}),
|
|
126
127
|
...(body.grant_id ? { grantId: body.grant_id } : {}),
|
|
127
128
|
});
|
|
128
129
|
return Response.json({ code: result.code, code_verifier: result.codeVerifier, state: result.state });
|
|
@@ -336,8 +337,8 @@ ${keys.filter((key) => key === "openrouter").map((key) => ` ${key}:\n baseUr
|
|
|
336
337
|
},
|
|
337
338
|
};
|
|
338
339
|
}
|
|
339
|
-
// The approval page as the plans' user goes through it:
|
|
340
|
-
// approve or deny; then what the page hands the app.
|
|
340
|
+
// The approval page as the plans' user goes through it: keep the plans it
|
|
341
|
+
// ticks (or tick the given ones), approve or deny; then what the page hands the app.
|
|
341
342
|
async function driveApproval(baseUrl, cookie, authorizeUrl, options) {
|
|
342
343
|
const url = new URL(authorizeUrl);
|
|
343
344
|
const page = `${baseUrl}${url.pathname}${url.search}`;
|
|
@@ -348,7 +349,7 @@ async function driveApproval(baseUrl, cookie, authorizeUrl, options) {
|
|
|
348
349
|
throw new Error("The approval page offers this app nothing to approve: none of the stub user's plans or keys serves it. "
|
|
349
350
|
+ 'A Claude Code plan serves only an app that asks for clients: ["claude_code"].');
|
|
350
351
|
}
|
|
351
|
-
const
|
|
352
|
+
const ticked = [...choose.matchAll(/name="credential_id" value="([^"]+)"[^>]* checked>/g)].map((match) => match[1]);
|
|
352
353
|
const decided = await fetch(`${baseUrl}${url.pathname}`, {
|
|
353
354
|
method: "POST",
|
|
354
355
|
redirect: "manual",
|
|
@@ -357,7 +358,7 @@ async function driveApproval(baseUrl, cookie, authorizeUrl, options) {
|
|
|
357
358
|
...params,
|
|
358
359
|
["csrf", csrf],
|
|
359
360
|
["decision", options.deny ? "deny" : "approve"],
|
|
360
|
-
...(options.credentialIds ??
|
|
361
|
+
...(options.credentialIds ?? ticked).map((id) => ["credential_id", id]),
|
|
361
362
|
]),
|
|
362
363
|
});
|
|
363
364
|
const location = decided.headers.get("location");
|
|
@@ -11,7 +11,7 @@
|
|
|
11
11
|
* page's user's: `userCookie` is the `Cookie` header that opens the page as them. `app` is a server
|
|
12
12
|
* app registered on the gateway (`gatewayUrl`, `clientId`, `clientSecret`, `redirectUri`), and
|
|
13
13
|
* `POST <controlUrl>/connect` (with `{"credential_ids"?, "deny"?, "clients"?, "plans"?,
|
|
14
|
-
* "key_providers"?, "grant_id"?}`, all optional) is its user approving it: it answers
|
|
14
|
+
* "key_providers"?, "allow_pooling"?, "grant_id"?}`, all optional) is its user approving it: it answers
|
|
15
15
|
* `{"code", "code_verifier", "state"}`, what Connect with Dari hands your page. `GET <controlUrl>/served`
|
|
16
16
|
* answers `{"calls": [...]}`: every provider call so far, with its path,
|
|
17
17
|
* model, thinking, and client headers. For an app you registered yourself, `POST <controlUrl>/approve` with
|
|
@@ -27,4 +27,4 @@
|
|
|
27
27
|
export { freshAccessToken } from "./access.js";
|
|
28
28
|
export { handleSubscriptionRequest, type SubscriptionHttpDeps } from "./http.js";
|
|
29
29
|
export { CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, XAI_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, parseAuthorizationResponse, refreshOAuth, startOAuth, type OAuthAuthorization, type OAuthFetch, type OAuthOptions, type OAuthTokens, type SubscriptionProvider, } from "./oauth.js";
|
|
30
|
-
export { SubscriptionAccountConnectedError, SubscriptionStore, activeModelHolds, currentUsage, isHeld, sameConnectedAccount, type AccountRef, type ConnectedAccount, type PendingOAuthSession, type SubscriptionCredential, type SubscriptionModelHold, } from "./store.js";
|
|
30
|
+
export { SubscriptionAccountConnectedError, SubscriptionStore, activeModelHolds, currentUsage, isHeld, planAccount, sameConnectedAccount, type AccountRef, type ConnectedAccount, type PendingOAuthSession, type SubscriptionCredential, type SubscriptionModelHold, } from "./store.js";
|
|
@@ -27,4 +27,4 @@
|
|
|
27
27
|
export { freshAccessToken } from "./access.js";
|
|
28
28
|
export { handleSubscriptionRequest } from "./http.js";
|
|
29
29
|
export { CODEX_APPROVAL_PENDING, META_APPROVAL_PENDING, OPENCODE_APPROVAL_PENDING, XAI_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, parseAuthorizationResponse, refreshOAuth, startOAuth, } from "./oauth.js";
|
|
30
|
-
export { SubscriptionAccountConnectedError, SubscriptionStore, activeModelHolds, currentUsage, isHeld, sameConnectedAccount, } from "./store.js";
|
|
30
|
+
export { SubscriptionAccountConnectedError, SubscriptionStore, activeModelHolds, currentUsage, isHeld, planAccount, sameConnectedAccount, } from "./store.js";
|
|
@@ -67,6 +67,13 @@ export type PendingOAuthSession = {
|
|
|
67
67
|
movingFrom: string | null;
|
|
68
68
|
expiresAt: Date;
|
|
69
69
|
};
|
|
70
|
+
/**
|
|
71
|
+
* A plan's name, as Activity shows the request it served: the user's label,
|
|
72
|
+
* else its account's email; none when it has neither.
|
|
73
|
+
*/
|
|
74
|
+
export declare function planAccount(plan: Pick<SubscriptionCredential, "label" | "accountEmail">): {
|
|
75
|
+
account?: string;
|
|
76
|
+
};
|
|
70
77
|
/** The parts of a plan that say which provider account it is. */
|
|
71
78
|
export type AccountRef = {
|
|
72
79
|
provider: SubscriptionProvider;
|
|
@@ -81,6 +88,7 @@ export type AccountRef = {
|
|
|
81
88
|
export type ConnectedAccount = AccountRef & {
|
|
82
89
|
place: "dari" | "this_computer" | "private";
|
|
83
90
|
name: string | null;
|
|
91
|
+
connectedAt?: Date;
|
|
84
92
|
};
|
|
85
93
|
/** Connecting an account the same user already has connected; the message says where it lives and how to move it. */
|
|
86
94
|
export declare class SubscriptionAccountConnectedError extends Error {
|
|
@@ -93,12 +101,6 @@ export declare function sameConnectedAccount(a: AccountRef, b: AccountRef): bool
|
|
|
93
101
|
export declare class SubscriptionStore {
|
|
94
102
|
private readonly db;
|
|
95
103
|
private readonly box;
|
|
96
|
-
/**
|
|
97
|
-
* Told of each change hosted Dari's copy of the plans would show: `plans`
|
|
98
|
-
* for a plan connected, removed, renamed, moved, held, or released, and
|
|
99
|
-
* `usage` for reported usage or use.
|
|
100
|
-
*/
|
|
101
|
-
onChange: ((change: "plans" | "usage") => void) | undefined;
|
|
102
104
|
constructor(db: Database, box?: SecretBox | null);
|
|
103
105
|
/** Whether stored tokens are encrypted. */
|
|
104
106
|
get encrypted(): boolean;
|
|
@@ -6,6 +6,14 @@ import { openWithoutKey } from "../secret_box.js";
|
|
|
6
6
|
export const SWITCH_AT_UTILIZATION = 0.95;
|
|
7
7
|
// A conversation idle this long is forgotten; its next turn starts over.
|
|
8
8
|
const CONVERSATION_PIN_TTL_MS = 7 * 24 * 60 * 60_000;
|
|
9
|
+
/**
|
|
10
|
+
* A plan's name, as Activity shows the request it served: the user's label,
|
|
11
|
+
* else its account's email; none when it has neither.
|
|
12
|
+
*/
|
|
13
|
+
export function planAccount(plan) {
|
|
14
|
+
const account = plan.label ?? plan.accountEmail;
|
|
15
|
+
return account ? { account } : {};
|
|
16
|
+
}
|
|
9
17
|
/** Connecting an account the same user already has connected; the message says where it lives and how to move it. */
|
|
10
18
|
export class SubscriptionAccountConnectedError extends Error {
|
|
11
19
|
}
|
|
@@ -61,12 +69,6 @@ const ADDED_COLUMNS = {
|
|
|
61
69
|
export class SubscriptionStore {
|
|
62
70
|
db;
|
|
63
71
|
box;
|
|
64
|
-
/**
|
|
65
|
-
* Told of each change hosted Dari's copy of the plans would show: `plans`
|
|
66
|
-
* for a plan connected, removed, renamed, moved, held, or released, and
|
|
67
|
-
* `usage` for reported usage or use.
|
|
68
|
-
*/
|
|
69
|
-
onChange;
|
|
70
72
|
constructor(db, box = null) {
|
|
71
73
|
this.db = db;
|
|
72
74
|
this.box = box;
|
|
@@ -254,7 +256,6 @@ export class SubscriptionStore {
|
|
|
254
256
|
}
|
|
255
257
|
this.db.run(`UPDATE subscription_credentials SET usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?,
|
|
256
258
|
usage_windows = ? WHERE id = ?`, [usage.utilization, usage.resetsAt.getTime(), now.getTime(), windowsJson(usage), id]);
|
|
257
|
-
this.onChange?.("usage");
|
|
258
259
|
}
|
|
259
260
|
// A pin idle past CONVERSATION_PIN_TTL_MS is forgotten: the conversation is
|
|
260
261
|
// assigned like a new one.
|
|
@@ -343,8 +344,6 @@ export class SubscriptionStore {
|
|
|
343
344
|
]);
|
|
344
345
|
return this.get(id);
|
|
345
346
|
})();
|
|
346
|
-
if (connected !== null)
|
|
347
|
-
this.onChange?.("plans");
|
|
348
347
|
return connected;
|
|
349
348
|
}
|
|
350
349
|
// Throws when the owner's other plans, or `elsewhere`, already hold this
|
|
@@ -378,7 +377,6 @@ export class SubscriptionStore {
|
|
|
378
377
|
}
|
|
379
378
|
touch(id, now = new Date()) {
|
|
380
379
|
this.db.run("UPDATE subscription_credentials SET last_used_at = ? WHERE id = ?", [now.getTime(), id]);
|
|
381
|
-
this.onChange?.("usage");
|
|
382
380
|
}
|
|
383
381
|
/** An empty label clears it. Null when the subscription is not connected. */
|
|
384
382
|
rename(name, label, now = new Date()) {
|
|
@@ -394,7 +392,6 @@ export class SubscriptionStore {
|
|
|
394
392
|
now.getTime(),
|
|
395
393
|
credential.id,
|
|
396
394
|
]);
|
|
397
|
-
this.onChange?.("plans");
|
|
398
395
|
return this.get(credential.id);
|
|
399
396
|
}
|
|
400
397
|
/** Make the gateway owner's subscription private, or not. Null when it is not connected. */
|
|
@@ -407,7 +404,6 @@ export class SubscriptionStore {
|
|
|
407
404
|
now.getTime(),
|
|
408
405
|
credential.id,
|
|
409
406
|
]);
|
|
410
|
-
this.onChange?.("plans");
|
|
411
407
|
return this.get(credential.id);
|
|
412
408
|
}
|
|
413
409
|
/** Remove a subscription. Returns what was removed, or null when it was not connected. */
|
|
@@ -417,7 +413,6 @@ export class SubscriptionStore {
|
|
|
417
413
|
return null;
|
|
418
414
|
this.db.run("DELETE FROM subscription_credentials WHERE id = ?", [credential.id]);
|
|
419
415
|
this.db.run("DELETE FROM subscription_conversation_pins WHERE credential_id = ?", [credential.id]);
|
|
420
|
-
this.onChange?.("plans");
|
|
421
416
|
return credential;
|
|
422
417
|
}
|
|
423
418
|
/**
|
|
@@ -431,7 +426,6 @@ export class SubscriptionStore {
|
|
|
431
426
|
return false;
|
|
432
427
|
if (!isHeld(credential, now) || until > credential.unavailableUntil) {
|
|
433
428
|
this.db.run("UPDATE subscription_credentials SET unavailable_until = ?, unavailable_reason = ?, updated_at = ? WHERE id = ?", [until.getTime(), reason, now.getTime(), id]);
|
|
434
|
-
this.onChange?.("plans");
|
|
435
429
|
}
|
|
436
430
|
return this.activeCredential(credential.provider, now) !== null;
|
|
437
431
|
}
|
|
@@ -453,7 +447,6 @@ export class SubscriptionStore {
|
|
|
453
447
|
now.getTime(),
|
|
454
448
|
id,
|
|
455
449
|
]);
|
|
456
|
-
this.onChange?.("plans");
|
|
457
450
|
}
|
|
458
451
|
return true;
|
|
459
452
|
}
|
|
@@ -464,7 +457,6 @@ export class SubscriptionStore {
|
|
|
464
457
|
return null;
|
|
465
458
|
this.db.run(`UPDATE subscription_credentials SET unavailable_until = NULL, unavailable_reason = NULL, model_holds = NULL,
|
|
466
459
|
updated_at = ? WHERE id = ?`, [now.getTime(), credential.id]);
|
|
467
|
-
this.onChange?.("plans");
|
|
468
460
|
return this.get(credential.id);
|
|
469
461
|
}
|
|
470
462
|
createSession(session, now = new Date()) {
|
package/dist/telemetry/report.js
CHANGED
|
@@ -339,6 +339,11 @@ export class RequestReporter {
|
|
|
339
339
|
: selectedProvider ? a.credentials.link_key_credential_ids?.[selectedProvider] ?? null : null,
|
|
340
340
|
}
|
|
341
341
|
: undefined;
|
|
342
|
+
// The plan that served the request, by name, so Activity says which;
|
|
343
|
+
// ingest refuses metadata with a longer one.
|
|
344
|
+
const subscriptionAccount = keySource === "subscription"
|
|
345
|
+
? outcome.providerExecution?.subscriptionAccount?.slice(0, 320)
|
|
346
|
+
: undefined;
|
|
342
347
|
const ingestPayload = {
|
|
343
348
|
request_id: this.args.requestId,
|
|
344
349
|
client_request_id: a.clientRequestId,
|
|
@@ -363,7 +368,9 @@ export class RequestReporter {
|
|
|
363
368
|
prefix_warm_tokens: selectedEstimate?.warm_tokens ?? null,
|
|
364
369
|
message_count: observability.messageCount,
|
|
365
370
|
has_tools: observability.hasTools,
|
|
366
|
-
request_metadata:
|
|
371
|
+
request_metadata: subscriptionAccount === undefined
|
|
372
|
+
? observability.metadata
|
|
373
|
+
: { ...observability.metadata, subscription_account: subscriptionAccount },
|
|
367
374
|
selected_model: selectedModel,
|
|
368
375
|
selected_provider: selectedProvider,
|
|
369
376
|
provider_key_source: keySource,
|
package/dist/types.d.ts
CHANGED
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.368",
|
|
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.368",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.3"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
@@ -55,6 +55,13 @@ function agentContext(record: ConversationRecord): AgentContext {
|
|
|
55
55
|
};
|
|
56
56
|
}
|
|
57
57
|
|
|
58
|
+
/** The name of the plan that served the request, when one did. */
|
|
59
|
+
function subscriptionAccount(record: ConversationRecord): string | null {
|
|
60
|
+
const metadata = record.requestMetadata;
|
|
61
|
+
if (metadata === null || typeof metadata !== "object" || Array.isArray(metadata)) return null;
|
|
62
|
+
return readOptionalString((metadata as Record<string, unknown>).subscription_account);
|
|
63
|
+
}
|
|
64
|
+
|
|
58
65
|
function routePath(records: readonly ConversationRecord[]) {
|
|
59
66
|
const path: Array<{ model: string; thinking_level: string | null }> = [];
|
|
60
67
|
for (const record of records) {
|
|
@@ -211,6 +218,7 @@ function conversationStep(record: ConversationRecord, organizationId: string, cu
|
|
|
211
218
|
selected_model: record.selectedModel,
|
|
212
219
|
selected_reasoning_effort: effort,
|
|
213
220
|
selected_provider: record.selectedProvider,
|
|
221
|
+
subscription_account: subscriptionAccount(record),
|
|
214
222
|
provider_input_tokens: record.providerInputTokens,
|
|
215
223
|
provider_cache_read_tokens: record.providerCacheReadTokens,
|
|
216
224
|
provider_cache_write_tokens: record.providerCacheWriteTokens,
|
package/src/link/client.ts
CHANGED
|
@@ -182,7 +182,8 @@ export async function registerClient(
|
|
|
182
182
|
* `clients` names the clients the app runs, such as `claude_code`, so the
|
|
183
183
|
* user can grant plans that serve only those. `plans` limits the page to
|
|
184
184
|
* those plan kinds, such as `openai_codex`, or `"supported"`. `purposes` says what the app does
|
|
185
|
-
* with each audience's plans, shown beside them.
|
|
185
|
+
* with each audience's plans, shown beside them. The user shares at most one
|
|
186
|
+
* account per provider unless `allowPooling`. `grantId` (update mode)
|
|
186
187
|
* opens the page on that existing grant: the user changes its plans in place,
|
|
187
188
|
* its id and tokens stay, and the new code redeems for more tokens of it.
|
|
188
189
|
*/
|
|
@@ -213,6 +214,7 @@ export async function createLinkToken(
|
|
|
213
214
|
...(args.clients?.length ? { client: args.clients } : {}),
|
|
214
215
|
...(args.keyProviders?.length ? { key_providers: args.keyProviders } : {}),
|
|
215
216
|
...(args.purposes ? { purposes: args.purposes } : {}),
|
|
217
|
+
...(args.allowPooling ? { allow_pooling: true } : {}),
|
|
216
218
|
...(args.grantId ? { grant_id: args.grantId } : {}),
|
|
217
219
|
}),
|
|
218
220
|
});
|
|
@@ -233,6 +235,9 @@ export type AuthorizeOptions = {
|
|
|
233
235
|
// ["anthropic", "openrouter"]; omit to offer every one.
|
|
234
236
|
keyProviders?: string[];
|
|
235
237
|
purposes?: { any_app?: string; claude_code?: string; muse_code?: string };
|
|
238
|
+
// Let the user share several accounts of one provider, such as two Claude
|
|
239
|
+
// plans, which Dari pools; by default they share at most one per provider.
|
|
240
|
+
allowPooling?: boolean;
|
|
236
241
|
grantId?: string;
|
|
237
242
|
// `web_message` posts the result to the window that opened the page.
|
|
238
243
|
responseMode?: "query" | "web_message";
|
|
@@ -264,6 +269,7 @@ function authorizationUrl(args: AuthorizeOptions & { codeChallenge: string; stat
|
|
|
264
269
|
...(args.clients?.length ? { client: args.clients.join(" ") } : {}),
|
|
265
270
|
...(args.plans?.length ? { plans: [args.plans].flat().join(" ") } : {}),
|
|
266
271
|
...(args.keyProviders?.length ? { key_providers: args.keyProviders.join(" ") } : {}),
|
|
272
|
+
...(args.allowPooling ? { allow_pooling: "true" } : {}),
|
|
267
273
|
...(args.grantId ? { grant_id: args.grantId } : {}),
|
|
268
274
|
...Object.fromEntries(
|
|
269
275
|
Object.entries(args.purposes ?? {}).flatMap(([audience, purpose]) => purpose ? [[`purpose_${audience}`, purpose]] : []),
|