@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,11 +2,8 @@ import type { Database } from "bun:sqlite";
2
2
 
3
3
  import type { HostedConnection } from "./connected.js";
4
4
  import {
5
- activeModelHolds,
6
- isHeld,
7
5
  SUBSCRIPTION_PROVIDERS,
8
6
  type ConnectedAccount,
9
- type SubscriptionCredential,
10
7
  type SubscriptionProvider,
11
8
  type SubscriptionStore,
12
9
  } from "./subscriptions/index.js";
@@ -16,12 +13,8 @@ const MAX_BATCH_ROWS = 16;
16
13
  const MAX_BATCH_BYTES = 8 * 1024 * 1024;
17
14
  // A row past this sheds its request and response bodies, as hosted ingest does.
18
15
  const MAX_ROW_BYTES = 4 * 1024 * 1024;
19
- const PLANS_DEBOUNCE_MS = 1_000;
20
- // Usage and last use change on every turn; they reach hosted at most this often.
21
- const USAGE_INTERVAL_MS = 60_000;
22
- // Plans are reported at least this often, so hosted can tell a computer that
23
- // is gone (its plans stop counting as connected after a day) from a quiet one.
24
- const HEARTBEAT_MS = 60 * 60_000;
16
+ // How often this computer's plans are checked against the accounts on Dari.
17
+ const ACCOUNTS_CHECK_MS = 60 * 60_000;
25
18
  const RETRY_BASE_MS = 5_000;
26
19
  const RETRY_MAX_MS = 15 * 60_000;
27
20
  const DRAIN_INTERVAL_MS = 2_000;
@@ -29,20 +22,16 @@ const DRAIN_INTERVAL_MS = 2_000;
29
22
  type OutboxRow = { id: number; row_json: string };
30
23
 
31
24
  /**
32
- * What a gateway connected to hosted Dari tells it: its plans (metadata, never
33
- * tokens) as one snapshot `PUT /v1/gateway/subscriptions` replaces, and the
34
- * requests it served, for Activity, `POST /v1/gateway/requests`. Snapshots go
35
- * a moment after a plan changes and at most once a minute for usage; request
36
- * rows wait in a SQLite outbox, sent in batches with backoff until hosted
37
- * takes them. Private plans are never reported.
25
+ * What a gateway connected to hosted Dari tells it: the requests it served,
26
+ * for Activity, `POST /v1/gateway/requests`. Rows wait in a SQLite outbox,
27
+ * sent in batches with backoff until hosted takes them. Requests a private
28
+ * plan served are never queued. This computer's plans themselves never leave
29
+ * it; it only reads the accounts on Dari (`GET /v1/gateway/accounts`), to drop
30
+ * a plan whose account was since connected there.
38
31
  */
39
32
  export class HostedSync {
40
- private snapshotTimer: ReturnType<typeof setTimeout> | null = null;
41
- private snapshotDueAt = Infinity;
42
- private snapshotFailures = 0;
43
- // Snapshots go one at a time, so an older one never lands after a newer one.
44
- private snapshots: Promise<void> = Promise.resolve();
45
- private lastSnapshotAt = 0;
33
+ private accountsTimer: ReturnType<typeof setTimeout> | null = null;
34
+ private accountsFailures = 0;
46
35
  private drainTimer: ReturnType<typeof setInterval> | null = null;
47
36
  private draining: Promise<void> | null = null;
48
37
  private drainFailures = 0;
@@ -62,31 +51,21 @@ export class HostedSync {
62
51
  )`);
63
52
  }
64
53
 
65
- /** Report the plans now and send waiting requests, then keep at it. */
54
+ /** Check the accounts on Dari and send waiting requests now, then keep at it. */
66
55
  start(): void {
67
- this.scheduleSnapshot(0);
56
+ this.scheduleAccountsCheck(0);
68
57
  this.drainTimer = setInterval(() => void this.drain(), DRAIN_INTERVAL_MS);
69
58
  this.drainTimer.unref?.();
70
59
  void this.drain();
71
60
  }
72
61
 
73
62
  stop(): void {
74
- if (this.snapshotTimer !== null) clearTimeout(this.snapshotTimer);
63
+ if (this.accountsTimer !== null) clearTimeout(this.accountsTimer);
75
64
  if (this.drainTimer !== null) clearInterval(this.drainTimer);
76
- this.snapshotTimer = null;
65
+ this.accountsTimer = null;
77
66
  this.drainTimer = null;
78
67
  }
79
68
 
80
- /** A plan was connected, removed, renamed, moved, held, or released. */
81
- plansChanged(): void {
82
- this.scheduleSnapshot(PLANS_DEBOUNCE_MS);
83
- }
84
-
85
- /** A plan reported usage or served a turn. */
86
- usageChanged(): void {
87
- this.scheduleSnapshot(Math.max(PLANS_DEBOUNCE_MS, this.lastSnapshotAt + USAGE_INTERVAL_MS - this.now()));
88
- }
89
-
90
69
  /** Queue a served request's log row for hosted Activity. */
91
70
  enqueue(row: Record<string, unknown>): void {
92
71
  let json = JSON.stringify(row);
@@ -101,56 +80,33 @@ export class HostedSync {
101
80
  this.db.run("INSERT INTO hosted_request_outbox (row_json, queued_at) VALUES (?, ?)", [json, this.now()]);
102
81
  }
103
82
 
104
- /** The plans hosted Dari shows for this gateway. */
105
- snapshot(): Record<string, unknown> {
106
- const now = new Date(this.now());
107
- return {
108
- gateway_id: this.hosted.gatewayId,
109
- gateway_name: this.hosted.gatewayName,
110
- subscriptions: this.subscriptions.list().filter((plan) => !plan.private).map((plan) => planReport(plan, now)),
111
- };
83
+ private scheduleAccountsCheck(delayMs: number): void {
84
+ this.accountsTimer = setTimeout(() => void this.checkAccounts(), delayMs);
85
+ this.accountsTimer.unref?.();
112
86
  }
113
87
 
114
- // Keeps the earliest of the snapshots asked for.
115
- private scheduleSnapshot(delayMs: number): void {
116
- const dueAt = this.now() + delayMs;
117
- if (this.snapshotTimer !== null && this.snapshotDueAt <= dueAt) return;
118
- if (this.snapshotTimer !== null) clearTimeout(this.snapshotTimer);
119
- this.snapshotDueAt = dueAt;
120
- this.snapshotTimer = setTimeout(() => {
121
- this.snapshotTimer = null;
122
- this.snapshotDueAt = Infinity;
123
- this.snapshots = this.snapshots.then(() => this.putSnapshot());
124
- }, delayMs);
125
- this.snapshotTimer.unref?.();
126
- }
127
-
128
- private async putSnapshot(): Promise<void> {
129
- this.lastSnapshotAt = this.now();
88
+ // A plan here whose account was connected on Dari after it was connected
89
+ // here: Dari's plan serves this computer too, so the copy here goes. Only
90
+ // the account id matches, never the email alone: one email can hold several
91
+ // ChatGPT workspaces or Claude organizations.
92
+ private async checkAccounts(): Promise<void> {
130
93
  try {
131
- const response = await this.call("PUT", "/v1/gateway/subscriptions", this.snapshot());
132
- if (!response.ok) throw new Error(`HTTP ${response.status}: ${(await response.text()).slice(0, 300)}`);
133
- const body = await response.json() as { on_dari?: unknown };
134
- this.snapshotFailures = 0;
135
- this.scheduleSnapshot(HEARTBEAT_MS);
136
- this.dropPlansOnDari(body.on_dari);
94
+ const onDari = await readHostedAccounts(this.hosted, this.fetch);
95
+ this.accountsFailures = 0;
96
+ for (const plan of this.subscriptions.list()) {
97
+ if (plan.owner !== null || plan.private || plan.accountId === null) continue;
98
+ const moved = onDari.some((account) => account.provider === plan.provider
99
+ && account.accountId === plan.accountId
100
+ && account.connectedAt !== undefined && account.connectedAt > plan.createdAt);
101
+ if (!moved) continue;
102
+ this.subscriptions.disconnect(plan.name);
103
+ console.error(`${plan.name} is now connected on Dari; removed it from this computer`);
104
+ }
105
+ this.scheduleAccountsCheck(ACCOUNTS_CHECK_MS);
137
106
  } catch (error) {
138
- this.snapshotFailures += 1;
139
- console.error("hosted plan sync failed", error instanceof Error ? error.message : String(error));
140
- this.scheduleSnapshot(backoff(this.snapshotFailures));
141
- }
142
- }
143
-
144
- // Hosted Dari names the reported plans whose account was since connected on
145
- // Dari. Dari's plan serves this computer too, so the copy here goes, and
146
- // disconnecting it reports the plans again.
147
- private dropPlansOnDari(localIds: unknown): void {
148
- if (!Array.isArray(localIds)) return;
149
- for (const id of localIds) {
150
- const plan = typeof id === "string" ? this.subscriptions.get(id) : null;
151
- if (plan === null || plan.owner !== null || plan.private) continue;
152
- this.subscriptions.disconnect(plan.name);
153
- console.error(`${plan.name} is now connected on Dari; removed it from this computer`);
107
+ this.accountsFailures += 1;
108
+ console.error("hosted accounts check failed", error instanceof Error ? error.message : String(error));
109
+ this.scheduleAccountsCheck(backoff(this.accountsFailures));
154
110
  }
155
111
  }
156
112
 
@@ -217,8 +173,9 @@ export class HostedSync {
217
173
 
218
174
  /**
219
175
  * The user's plans on hosted Dari, for the check before a sign-in connects an
220
- * account: `GET /v1/gateway/accounts` returns each one's provider, account
221
- * identity, and name, never a token. Other computers may hold the same
176
+ * account and for dropping a plan here that moved there: `GET
177
+ * /v1/gateway/accounts` returns each one's provider, account identity, name,
178
+ * and when it was connected, never a token. Other computers may hold the same
222
179
  * account, so only Dari's plans count.
223
180
  */
224
181
  export async function readHostedAccounts(
@@ -241,16 +198,23 @@ export async function readHostedAccounts(
241
198
  for (const entry of body.accounts as Array<Record<string, unknown>>) {
242
199
  // Hosted Dari before this release also listed other computers' plans.
243
200
  if (entry.where !== "dari") continue;
244
- if (!SUBSCRIPTION_PROVIDERS.includes(entry.provider as SubscriptionProvider)) {
245
- throw new Error(`hosted accounts response names an unknown provider ${JSON.stringify(entry.provider)}`);
246
- }
201
+ // A provider this gateway does not know holds no account of a plan here.
202
+ if (!SUBSCRIPTION_PROVIDERS.includes(entry.provider as SubscriptionProvider)) continue;
247
203
  let accountId: string | null = null;
248
204
  if (typeof entry.account_id === "string") accountId = entry.account_id;
249
205
  let accountEmail: string | null = null;
250
206
  if (typeof entry.account_email === "string") accountEmail = entry.account_email;
251
207
  let name: string | null = null;
252
208
  if (typeof entry.name === "string") name = entry.name;
253
- accounts.push({ provider: entry.provider as SubscriptionProvider, accountId, accountEmail, place: "dari", name });
209
+ const connectedAt = typeof entry.connected_at === "string" ? new Date(entry.connected_at) : undefined;
210
+ accounts.push({
211
+ provider: entry.provider as SubscriptionProvider,
212
+ accountId,
213
+ accountEmail,
214
+ place: "dari",
215
+ name,
216
+ ...(connectedAt === undefined || Number.isNaN(connectedAt.getTime()) ? {} : { connectedAt }),
217
+ });
254
218
  }
255
219
  return accounts;
256
220
  }
@@ -258,37 +222,3 @@ export async function readHostedAccounts(
258
222
  function backoff(failures: number): number {
259
223
  return Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** Math.max(0, failures - 1));
260
224
  }
261
-
262
- // One plan as `PUT /v1/gateway/subscriptions` takes it. Usage uses the keys
263
- // and formats hosted subscriptions keep in their metadata.
264
- function planReport(plan: SubscriptionCredential, now: Date): Record<string, unknown> {
265
- const held = isHeld(plan, now);
266
- const usage = plan.usage;
267
- return {
268
- local_id: plan.id,
269
- provider: plan.provider,
270
- label: plan.label,
271
- account_email: plan.accountEmail,
272
- account_id: plan.accountId,
273
- plan: null,
274
- connected_at: plan.createdAt.toISOString(),
275
- last_used_at: plan.lastUsedAt?.toISOString() ?? null,
276
- unavailable_until: held ? plan.unavailableUntil!.toISOString() : null,
277
- unavailable_reason: held ? plan.unavailableReason : null,
278
- model_holds: Object.fromEntries(activeModelHolds(plan, now).map((hold) => [
279
- hold.model,
280
- { until: hold.until.toISOString(), reason: hold.reason },
281
- ])),
282
- usage: usage === null ? {} : {
283
- usage_utilization: usage.utilization.toFixed(4),
284
- usage_resets_at: usage.resetsAt.toISOString(),
285
- usage_windows: JSON.stringify(usage.windows.map((window) => ({
286
- ...(window.modelFamily === undefined ? {} : { model_family: window.modelFamily }),
287
- minutes: window.minutes,
288
- utilization: Math.round(window.utilization * 10_000) / 10_000,
289
- resets_at: window.resetsAt.toISOString(),
290
- }))),
291
- usage_observed_at: usage.observedAt.toISOString(),
292
- },
293
- };
294
- }
@@ -16,7 +16,7 @@ import { HostedSync, readHostedAccounts } from "./hosted_sync.js";
16
16
  import { createSelfHostedPlatform } from "./platform.js";
17
17
  import { checkProviderKey } from "../providers/key_check.js";
18
18
  import { CANONICAL_MODELS } from "../models/canonical.js";
19
- import { allRouterModels, loadGatewayConfig, modelProvider, type GatewayConfig, type RouterConfig } from "./config.js";
19
+ import { allRouterModels, keyProviders, loadGatewayConfig, type GatewayConfig, type RouterConfig } from "./config.js";
20
20
  import {
21
21
  configuredProviderApiKey,
22
22
  gatewayKeyIndex,
@@ -129,9 +129,6 @@ export async function startSelfHostedGateway(env: Record<string, string> = proce
129
129
  // The hosted router, read once a minute, for both serving and routing calls.
130
130
  const hostedRouter = hosted === null ? null : hostedRouters(hosted, fetch);
131
131
  const baseUrls = providerBaseUrls(config.providers);
132
- if (sync !== null) {
133
- subscriptions.onChange = (change) => change === "usage" ? sync.usageChanged() : sync.plansChanged();
134
- }
135
132
  const platformDeps = {
136
133
  activity,
137
134
  config,
@@ -261,7 +258,7 @@ async function checkConfiguredProviderKeys(
261
258
  providerApiKey: (provider: string) => Promise<string | undefined>,
262
259
  ): Promise<void> {
263
260
  const providers = new Set(
264
- routers.flatMap((router) => allRouterModels(router).map(modelProvider)),
261
+ routers.flatMap((router) => allRouterModels(router).flatMap(keyProviders)),
265
262
  );
266
263
  const checks = await Promise.all([...providers].map(async (provider) => {
267
264
  const endpoint = config.providers[provider];
@@ -14,7 +14,7 @@ import {
14
14
  SELF_HOSTED_ORGANIZATION_ID,
15
15
  type SelfHostedResolverDeps,
16
16
  } from "./resolve.js";
17
- import { type SubscriptionStore } from "./subscriptions/index.js";
17
+ import { planAccount, type SubscriptionStore } from "./subscriptions/index.js";
18
18
  import { refreshedAccessToken } from "./subscriptions/access.js";
19
19
  import { hasBankedResets, providerBaseUrls, recoverHeldPlans } from "./subscriptions/resets.js";
20
20
 
@@ -60,6 +60,7 @@ export function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "pre
60
60
  if (next === null) return undefined;
61
61
  return {
62
62
  credentialId: next.id,
63
+ ...planAccount(next),
63
64
  apiKey: await refreshedAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
64
65
  };
65
66
  },
@@ -32,6 +32,7 @@ import type {
32
32
  } from "../types.js";
33
33
  import {
34
34
  allRouterModels,
35
+ keyProviders,
35
36
  modelProvider,
36
37
  routerModelsFor,
37
38
  type GatewayConfig,
@@ -49,6 +50,7 @@ import { refreshedAccessToken } from "./subscriptions/access.js";
49
50
  import {
50
51
  activeModelHolds,
51
52
  freshAccessToken,
53
+ planAccount,
52
54
  type OAuthFetch,
53
55
  type SubscriptionCredential,
54
56
  type SubscriptionProvider,
@@ -234,10 +236,15 @@ export async function resolveSelfHostedRouter(
234
236
  },
235
237
  });
236
238
  }
239
+ // The first provider with a key serves: the one the spec names, else any
240
+ // the catalog runs the model on. A grant's keys serve as grantModels set.
241
+ const keyed = grant === null ? keyProviders(model) : [base];
237
242
  let keyCandidate = async (): Promise<Candidate | null> => {
238
- const key = await apiKey(base);
239
- if (key === undefined) return null;
240
- return { provider: base, key };
243
+ for (const provider of keyed) {
244
+ const key = await apiKey(provider);
245
+ if (key !== undefined) return { provider, key };
246
+ }
247
+ return null;
241
248
  };
242
249
  // A self-hosted gateway has no managed keys.
243
250
  let managedCandidate = async (): Promise<Candidate | null> => null;
@@ -259,7 +266,7 @@ export async function resolveSelfHostedRouter(
259
266
 
260
267
  if (candidates.length === 0) {
261
268
  for (const kind of heldKinds) exhausted.add(kind);
262
- unserved.add(base);
269
+ for (const provider of keyed) unserved.add(provider);
263
270
  // A granted plan may serve another maker's model: name the plan's provider too.
264
271
  if (grant !== null) for (const kind of heldKinds) unserved.add(subscriptionModelProvider(kind));
265
272
  if (modelHolds.length > 0) {
@@ -279,6 +286,7 @@ export async function resolveSelfHostedRouter(
279
286
  apiKey: await planToken(first.plan),
280
287
  subscription: first.plan.provider,
281
288
  credentialId: first.plan.id,
289
+ ...planAccount(first.plan),
282
290
  };
283
291
  } else {
284
292
  resolved.provider_keys[first!.provider] = first!.key;
@@ -536,12 +544,16 @@ export async function providersWithoutCredentials(
536
544
  ): Promise<string[]> {
537
545
  const missing = new Set<string>();
538
546
  for (const model of allRouterModels(router)) {
539
- const provider = modelProvider(model);
540
- if (missing.has(provider)) continue;
541
547
  const sources = model.sources ?? SELF_HOSTED_DEFAULT_SOURCES;
542
548
  const plans = sources.includes("plan") ? modelSubscriptions(model.id) : [];
543
549
  if (plans.some((plan) => deps.subscriptions.list(plan).length > 0)) continue;
544
- if (await configuredProviderApiKey(deps, provider) === undefined) missing.add(provider);
550
+ // Any of its key providers serves it, so each is named when none can.
551
+ const providers = keyProviders(model);
552
+ let keyed = false;
553
+ for (const provider of providers) {
554
+ if (await configuredProviderApiKey(deps, provider) !== undefined) keyed = true;
555
+ }
556
+ if (!keyed) for (const provider of providers) missing.add(provider);
545
557
  }
546
558
  return [...missing];
547
559
  }
@@ -50,6 +50,7 @@ export {
50
50
  activeModelHolds,
51
51
  currentUsage,
52
52
  isHeld,
53
+ planAccount,
53
54
  sameConnectedAccount,
54
55
  type AccountRef,
55
56
  type ConnectedAccount,
@@ -50,8 +50,8 @@ export type SubscriptionCredential = {
50
50
  // The Dari Link user who connected the plan on the approval page; null for
51
51
  // the gateway owner's own plans, which alone serve the gateway's keys.
52
52
  owner: string | null;
53
- // Kept off hosted Dari: a gateway connected to it neither serves nor
54
- // reports the plan.
53
+ // Its requests stay on this computer: a gateway connected to hosted Dari
54
+ // never sends them to Activity.
55
55
  private: boolean;
56
56
  accessToken: string;
57
57
  refreshToken: string;
@@ -90,6 +90,15 @@ export type PendingOAuthSession = {
90
90
  expiresAt: Date;
91
91
  };
92
92
 
93
+ /**
94
+ * A plan's name, as Activity shows the request it served: the user's label,
95
+ * else its account's email; none when it has neither.
96
+ */
97
+ export function planAccount(plan: Pick<SubscriptionCredential, "label" | "accountEmail">): { account?: string } {
98
+ const account = plan.label ?? plan.accountEmail;
99
+ return account ? { account } : {};
100
+ }
101
+
93
102
  /** The parts of a plan that say which provider account it is. */
94
103
  export type AccountRef = {
95
104
  provider: SubscriptionProvider;
@@ -105,6 +114,9 @@ export type AccountRef = {
105
114
  export type ConnectedAccount = AccountRef & {
106
115
  place: "dari" | "this_computer" | "private";
107
116
  name: string | null;
117
+ // When a plan on Dari was connected; hosted Dari before this release does
118
+ // not say.
119
+ connectedAt?: Date;
108
120
  };
109
121
 
110
122
  /** Connecting an account the same user already has connected; the message says where it lives and how to move it. */
@@ -200,13 +212,6 @@ type SessionRow = {
200
212
  };
201
213
 
202
214
  export class SubscriptionStore {
203
- /**
204
- * Told of each change hosted Dari's copy of the plans would show: `plans`
205
- * for a plan connected, removed, renamed, moved, held, or released, and
206
- * `usage` for reported usage or use.
207
- */
208
- onChange: ((change: "plans" | "usage") => void) | undefined;
209
-
210
215
  constructor(
211
216
  private readonly db: Database,
212
217
  private readonly box: SecretBox | null = null,
@@ -424,7 +429,6 @@ export class SubscriptionStore {
424
429
  usage_windows = ? WHERE id = ?`,
425
430
  [usage.utilization, usage.resetsAt.getTime(), now.getTime(), windowsJson(usage), id],
426
431
  );
427
- this.onChange?.("usage");
428
432
  }
429
433
 
430
434
  // A pin idle past CONVERSATION_PIN_TTL_MS is forgotten: the conversation is
@@ -539,7 +543,6 @@ export class SubscriptionStore {
539
543
  );
540
544
  return this.get(id);
541
545
  })();
542
- if (connected !== null) this.onChange?.("plans");
543
546
  return connected;
544
547
  }
545
548
 
@@ -579,7 +582,6 @@ export class SubscriptionStore {
579
582
 
580
583
  touch(id: string, now = new Date()): void {
581
584
  this.db.run("UPDATE subscription_credentials SET last_used_at = ? WHERE id = ?", [now.getTime(), id]);
582
- this.onChange?.("usage");
583
585
  }
584
586
 
585
587
  /** An empty label clears it. Null when the subscription is not connected. */
@@ -595,7 +597,6 @@ export class SubscriptionStore {
595
597
  now.getTime(),
596
598
  credential.id,
597
599
  ]);
598
- this.onChange?.("plans");
599
600
  return this.get(credential.id);
600
601
  }
601
602
 
@@ -608,7 +609,6 @@ export class SubscriptionStore {
608
609
  now.getTime(),
609
610
  credential.id,
610
611
  ]);
611
- this.onChange?.("plans");
612
612
  return this.get(credential.id);
613
613
  }
614
614
 
@@ -618,7 +618,6 @@ export class SubscriptionStore {
618
618
  if (credential === null) return null;
619
619
  this.db.run("DELETE FROM subscription_credentials WHERE id = ?", [credential.id]);
620
620
  this.db.run("DELETE FROM subscription_conversation_pins WHERE credential_id = ?", [credential.id]);
621
- this.onChange?.("plans");
622
621
  return credential;
623
622
  }
624
623
 
@@ -635,7 +634,6 @@ export class SubscriptionStore {
635
634
  "UPDATE subscription_credentials SET unavailable_until = ?, unavailable_reason = ?, updated_at = ? WHERE id = ?",
636
635
  [until.getTime(), reason, now.getTime(), id],
637
636
  );
638
- this.onChange?.("plans");
639
637
  }
640
638
  return this.activeCredential(credential.provider, now) !== null;
641
639
  }
@@ -657,7 +655,6 @@ export class SubscriptionStore {
657
655
  now.getTime(),
658
656
  id,
659
657
  ]);
660
- this.onChange?.("plans");
661
658
  }
662
659
  return true;
663
660
  }
@@ -671,7 +668,6 @@ export class SubscriptionStore {
671
668
  updated_at = ? WHERE id = ?`,
672
669
  [now.getTime(), credential.id],
673
670
  );
674
- this.onChange?.("plans");
675
671
  return this.get(credential.id);
676
672
  }
677
673
 
@@ -523,6 +523,11 @@ export class RequestReporter {
523
523
  : selectedProvider ? a.credentials.link_key_credential_ids?.[selectedProvider] ?? null : null,
524
524
  }
525
525
  : undefined;
526
+ // The plan that served the request, by name, so Activity says which;
527
+ // ingest refuses metadata with a longer one.
528
+ const subscriptionAccount = keySource === "subscription"
529
+ ? outcome.providerExecution?.subscriptionAccount?.slice(0, 320)
530
+ : undefined;
526
531
  const ingestPayload = {
527
532
  request_id: this.args.requestId,
528
533
  client_request_id: a.clientRequestId,
@@ -547,7 +552,9 @@ export class RequestReporter {
547
552
  prefix_warm_tokens: selectedEstimate?.warm_tokens ?? null,
548
553
  message_count: observability.messageCount,
549
554
  has_tools: observability.hasTools,
550
- request_metadata: observability.metadata,
555
+ request_metadata: subscriptionAccount === undefined
556
+ ? observability.metadata
557
+ : { ...observability.metadata, subscription_account: subscriptionAccount },
551
558
  selected_model: selectedModel,
552
559
  selected_provider: selectedProvider,
553
560
  provider_key_source: keySource,
package/src/types.ts CHANGED
@@ -75,6 +75,9 @@ export type ProviderCredential = {
75
75
  subscription?: SubscriptionKind;
76
76
  // A resolved personal plan: quota holds and usage belong to this credential.
77
77
  credentialId?: string;
78
+ // That plan's name, as Activity shows it: its owner's label, else its
79
+ // account's email.
80
+ account?: string;
78
81
  // Dari's managed key: billed to the organization's credits.
79
82
  managed?: true;
80
83
  };