@mupt-ai/dari-gateway 1.0.365 → 1.0.367

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +1 -1
  2. package/dist/activity/conversation_detail.js +8 -0
  3. package/dist/link/endpoints.js +5 -25
  4. package/dist/link/service.d.ts +1 -3
  5. package/dist/link/service.js +0 -1
  6. package/dist/models/canonical.d.ts +7 -1
  7. package/dist/models/canonical.js +9 -1
  8. package/dist/models/canonical_models.json +151 -0
  9. package/dist/models/provider_models.json +476 -0
  10. package/dist/platform/platform.d.ts +1 -11
  11. package/dist/protocol/input/anthropic_messages.js +3 -4
  12. package/dist/providers/execution.js +1 -0
  13. package/dist/providers/provider_call.d.ts +1 -0
  14. package/dist/providers/provider_call.js +1 -0
  15. package/dist/runtime/runtime_reporter.d.ts +1 -0
  16. package/dist/runtime/runtime_reporter.js +1 -0
  17. package/dist/self_host/config.d.ts +5 -0
  18. package/dist/self_host/config.js +8 -1
  19. package/dist/self_host/connected.d.ts +5 -4
  20. package/dist/self_host/hosted_sync.d.ts +14 -23
  21. package/dist/self_host/hosted_sync.js +56 -120
  22. package/dist/self_host/main.js +2 -5
  23. package/dist/self_host/platform.js +2 -0
  24. package/dist/self_host/resolve.js +24 -12
  25. package/dist/self_host/subscriptions/index.d.ts +1 -1
  26. package/dist/self_host/subscriptions/index.js +1 -1
  27. package/dist/self_host/subscriptions/store.d.ts +8 -6
  28. package/dist/self_host/subscriptions/store.js +8 -16
  29. package/dist/telemetry/report.js +8 -1
  30. package/dist/types.d.ts +1 -0
  31. package/package.json +2 -2
  32. package/src/activity/conversation_detail.ts +8 -0
  33. package/src/link/endpoints.ts +4 -29
  34. package/src/link/service.ts +0 -4
  35. package/src/models/canonical.ts +15 -1
  36. package/src/models/canonical_models.json +151 -0
  37. package/src/models/provider_models.json +476 -0
  38. package/src/platform/platform.ts +2 -9
  39. package/src/protocol/input/anthropic_messages.ts +3 -9
  40. package/src/providers/execution.ts +1 -0
  41. package/src/providers/provider_call.ts +3 -0
  42. package/src/runtime/runtime_reporter.ts +3 -1
  43. package/src/self_host/config.ts +9 -1
  44. package/src/self_host/connected.ts +5 -4
  45. package/src/self_host/hosted_sync.ts +51 -121
  46. package/src/self_host/main.ts +2 -5
  47. package/src/self_host/platform.ts +2 -1
  48. package/src/self_host/resolve.ts +19 -7
  49. package/src/self_host/subscriptions/index.ts +1 -0
  50. package/src/self_host/subscriptions/store.ts +14 -18
  51. package/src/telemetry/report.ts +8 -1
  52. package/src/types.ts +3 -0
@@ -2,12 +2,12 @@ import type { Database } from "bun:sqlite";
2
2
  import type { HostedConnection } from "./connected.js";
3
3
  import { type ConnectedAccount, type SubscriptionStore } from "./subscriptions/index.js";
4
4
  /**
5
- * What a gateway connected to hosted Dari tells it: its plans (metadata, never
6
- * tokens) as one snapshot `PUT /v1/gateway/subscriptions` replaces, and the
7
- * requests it served, for Activity, `POST /v1/gateway/requests`. Snapshots go
8
- * a moment after a plan changes and at most once a minute for usage; request
9
- * rows wait in a SQLite outbox, sent in batches with backoff until hosted
10
- * takes them. Private plans are never reported.
5
+ * What a gateway connected to hosted Dari tells it: the requests it served,
6
+ * for Activity, `POST /v1/gateway/requests`. Rows wait in a SQLite outbox,
7
+ * sent in batches with backoff until hosted takes them. Requests a private
8
+ * plan served are never queued. This computer's plans themselves never leave
9
+ * it; it only reads the accounts on Dari (`GET /v1/gateway/accounts`), to drop
10
+ * a plan whose account was since connected there.
11
11
  */
12
12
  export declare class HostedSync {
13
13
  private readonly db;
@@ -15,30 +15,20 @@ export declare class HostedSync {
15
15
  private readonly hosted;
16
16
  private readonly fetch;
17
17
  private readonly now;
18
- private snapshotTimer;
19
- private snapshotDueAt;
20
- private snapshotFailures;
21
- private snapshots;
22
- private lastSnapshotAt;
18
+ private accountsTimer;
19
+ private accountsFailures;
23
20
  private drainTimer;
24
21
  private draining;
25
22
  private drainFailures;
26
23
  private drainPausedUntil;
27
24
  constructor(db: Database, subscriptions: SubscriptionStore, hosted: HostedConnection, fetch: typeof globalThis.fetch, now?: () => number);
28
- /** Report the plans now and send waiting requests, then keep at it. */
25
+ /** Check the accounts on Dari and send waiting requests now, then keep at it. */
29
26
  start(): void;
30
27
  stop(): void;
31
- /** A plan was connected, removed, renamed, moved, held, or released. */
32
- plansChanged(): void;
33
- /** A plan reported usage or served a turn. */
34
- usageChanged(): void;
35
28
  /** Queue a served request's log row for hosted Activity. */
36
29
  enqueue(row: Record<string, unknown>): void;
37
- /** The plans hosted Dari shows for this gateway. */
38
- snapshot(): Record<string, unknown>;
39
- private scheduleSnapshot;
40
- private putSnapshot;
41
- private dropPlansOnDari;
30
+ private scheduleAccountsCheck;
31
+ private checkAccounts;
42
32
  /** Send the queued request rows a batch at a time, unless hosted failed lately. */
43
33
  drain(): Promise<void>;
44
34
  private drainDue;
@@ -46,8 +36,9 @@ export declare class HostedSync {
46
36
  }
47
37
  /**
48
38
  * The user's plans on hosted Dari, for the check before a sign-in connects an
49
- * account: `GET /v1/gateway/accounts` returns each one's provider, account
50
- * identity, and name, never a token. Other computers may hold the same
39
+ * account and for dropping a plan here that moved there: `GET
40
+ * /v1/gateway/accounts` returns each one's provider, account identity, name,
41
+ * and when it was connected, never a token. Other computers may hold the same
51
42
  * account, so only Dari's plans count.
52
43
  */
53
44
  export declare function readHostedAccounts(hosted: HostedConnection, fetchImpl: typeof globalThis.fetch): Promise<ConnectedAccount[]>;
@@ -1,25 +1,21 @@
1
- import { activeModelHolds, isHeld, SUBSCRIPTION_PROVIDERS, } from "./subscriptions/index.js";
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
- const PLANS_DEBOUNCE_MS = 1_000;
8
- // Usage and last use change on every turn; they reach hosted at most this often.
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: its plans (metadata, never
18
- * tokens) as one snapshot `PUT /v1/gateway/subscriptions` replaces, and the
19
- * requests it served, for Activity, `POST /v1/gateway/requests`. Snapshots go
20
- * a moment after a plan changes and at most once a minute for usage; request
21
- * rows wait in a SQLite outbox, sent in batches with backoff until hosted
22
- * takes them. Private plans are never reported.
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
- snapshotTimer = null;
31
- snapshotDueAt = Infinity;
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
- /** Report the plans now and send waiting requests, then keep at it. */
44
+ /** Check the accounts on Dari and send waiting requests now, then keep at it. */
53
45
  start() {
54
- this.scheduleSnapshot(0);
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.snapshotTimer !== null)
61
- clearTimeout(this.snapshotTimer);
52
+ if (this.accountsTimer !== null)
53
+ clearTimeout(this.accountsTimer);
62
54
  if (this.drainTimer !== null)
63
55
  clearInterval(this.drainTimer);
64
- this.snapshotTimer = null;
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
- /** The plans hosted Dari shows for this gateway. */
89
- snapshot() {
90
- const now = new Date(this.now());
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
- async putSnapshot() {
113
- this.lastSnapshotAt = this.now();
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 response = await this.call("PUT", "/v1/gateway/subscriptions", this.snapshot());
116
- if (!response.ok)
117
- throw new Error(`HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`);
118
- const body = await response.json();
119
- this.snapshotFailures = 0;
120
- this.scheduleSnapshot(HEARTBEAT_MS);
121
- this.dropPlansOnDari(body.on_dari);
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.snapshotFailures += 1;
125
- console.error("hosted plan sync failed", error instanceof Error ? error.message : String(error));
126
- this.scheduleSnapshot(backoff(this.snapshotFailures));
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: `GET /v1/gateway/accounts` returns each one's provider, account
207
- * identity, and name, never a token. Other computers may hold the same
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
- if (!SUBSCRIPTION_PROVIDERS.includes(entry.provider)) {
229
- throw new Error(`hosted accounts response names an unknown provider ${JSON.stringify(entry.provider)}`);
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
- accounts.push({ provider: entry.provider, accountId, accountEmail, place: "dari", name });
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
- }
@@ -14,7 +14,7 @@ import { HostedSync, readHostedAccounts } from "./hosted_sync.js";
14
14
  import { createSelfHostedPlatform } from "./platform.js";
15
15
  import { checkProviderKey } from "../providers/key_check.js";
16
16
  import { CANONICAL_MODELS } from "../models/canonical.js";
17
- import { allRouterModels, loadGatewayConfig, modelProvider } from "./config.js";
17
+ import { allRouterModels, keyProviders, loadGatewayConfig } from "./config.js";
18
18
  import { configuredProviderApiKey, gatewayKeyIndex, providersWithoutCredentials, SELF_HOSTED_ORGANIZATION_ID, } from "./resolve.js";
19
19
  import { SqliteLinkStore } from "../link/sqlite_store.js";
20
20
  import { secretBoxFromEnv } from "./secret_box.js";
@@ -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,
@@ -230,7 +227,7 @@ export async function startSelfHostedGateway(env = process.env) {
230
227
  * provider rejects fails startup, and one no check could answer is reported.
231
228
  */
232
229
  async function checkConfiguredProviderKeys(config, routers, providerApiKey) {
233
- const providers = new Set(routers.flatMap((router) => allRouterModels(router).map(modelProvider)));
230
+ const providers = new Set(routers.flatMap((router) => allRouterModels(router).flatMap(keyProviders)));
234
231
  const checks = await Promise.all([...providers].map(async (provider) => {
235
232
  const endpoint = config.providers[provider];
236
233
  // Endpoints configured without a key variable take no key.
@@ -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
  },
@@ -10,12 +10,12 @@ import { gatewayFor } from "../models/gateways.js";
10
10
  import { candidatesFor, DEFAULT_RESET_MIN_HOURS, SELF_HOSTED_DEFAULT_SOURCES } from "../models/sources.js";
11
11
  import { linkNothingServed, plansExhausted, providersUnavailable } from "../link/errors.js";
12
12
  import { buildModel, pi, registeredModelPrice } from "../providers/pi.js";
13
- import { allRouterModels, modelProvider, routerModelsFor, } from "./config.js";
13
+ import { allRouterModels, keyProviders, modelProvider, routerModelsFor, } from "./config.js";
14
14
  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";
@@ -164,11 +164,16 @@ export async function resolveSelfHostedRouter(deps, request) {
164
164
  },
165
165
  });
166
166
  }
167
+ // The first provider with a key serves: the one the spec names, else any
168
+ // the catalog runs the model on. A grant's keys serve as grantModels set.
169
+ const keyed = grant === null ? keyProviders(model) : [base];
167
170
  let keyCandidate = async () => {
168
- const key = await apiKey(base);
169
- if (key === undefined)
170
- return null;
171
- return { provider: base, key };
171
+ for (const provider of keyed) {
172
+ const key = await apiKey(provider);
173
+ if (key !== undefined)
174
+ return { provider, key };
175
+ }
176
+ return null;
172
177
  };
173
178
  // A self-hosted gateway has no managed keys.
174
179
  let managedCandidate = async () => null;
@@ -191,7 +196,8 @@ export async function resolveSelfHostedRouter(deps, request) {
191
196
  if (candidates.length === 0) {
192
197
  for (const kind of heldKinds)
193
198
  exhausted.add(kind);
194
- unserved.add(base);
199
+ for (const provider of keyed)
200
+ unserved.add(provider);
195
201
  // A granted plan may serve another maker's model: name the plan's provider too.
196
202
  if (grant !== null)
197
203
  for (const kind of heldKinds)
@@ -215,6 +221,7 @@ export async function resolveSelfHostedRouter(deps, request) {
215
221
  apiKey: await planToken(first.plan),
216
222
  subscription: first.plan.provider,
217
223
  credentialId: first.plan.id,
224
+ ...planAccount(first.plan),
218
225
  };
219
226
  }
220
227
  else {
@@ -452,15 +459,20 @@ const SUBSCRIPTION_PLAN_NAMES = {
452
459
  export async function providersWithoutCredentials(deps, router) {
453
460
  const missing = new Set();
454
461
  for (const model of allRouterModels(router)) {
455
- const provider = modelProvider(model);
456
- if (missing.has(provider))
457
- continue;
458
462
  const sources = model.sources ?? SELF_HOSTED_DEFAULT_SOURCES;
459
463
  const plans = sources.includes("plan") ? modelSubscriptions(model.id) : [];
460
464
  if (plans.some((plan) => deps.subscriptions.list(plan).length > 0))
461
465
  continue;
462
- if (await configuredProviderApiKey(deps, provider) === undefined)
463
- missing.add(provider);
466
+ // Any of its key providers serves it, so each is named when none can.
467
+ const providers = keyProviders(model);
468
+ let keyed = false;
469
+ for (const provider of providers) {
470
+ if (await configuredProviderApiKey(deps, provider) !== undefined)
471
+ keyed = true;
472
+ }
473
+ if (!keyed)
474
+ for (const provider of providers)
475
+ missing.add(provider);
464
476
  }
465
477
  return [...missing];
466
478
  }
@@ -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()) {
@@ -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: observability.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
@@ -26,6 +26,7 @@ export type ProviderCredential = {
26
26
  headers?: Record<string, string>;
27
27
  subscription?: SubscriptionKind;
28
28
  credentialId?: string;
29
+ account?: string;
29
30
  managed?: true;
30
31
  };
31
32
  export type ProviderAuth = ResolvedProviderAuth | AwsAssumeRoleProviderAuth;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@mupt-ai/dari-gateway",
3
- "version": "1.0.365",
3
+ "version": "1.0.367",
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.365",
55
+ "@mupt-ai/dari-router": "1.0.367",
56
56
  "@mupt-ai/pi-ai": "1.5.2-mupt.3"
57
57
  },
58
58
  "devDependencies": {