@mupt-ai/dari-gateway 1.0.366 → 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 (41) hide show
  1. package/dist/activity/conversation_detail.js +8 -0
  2. package/dist/link/endpoints.js +5 -25
  3. package/dist/link/service.d.ts +1 -3
  4. package/dist/link/service.js +0 -1
  5. package/dist/platform/platform.d.ts +1 -11
  6. package/dist/protocol/input/anthropic_messages.js +3 -4
  7. package/dist/providers/execution.js +1 -0
  8. package/dist/providers/provider_call.d.ts +1 -0
  9. package/dist/providers/provider_call.js +1 -0
  10. package/dist/runtime/runtime_reporter.d.ts +1 -0
  11. package/dist/runtime/runtime_reporter.js +1 -0
  12. package/dist/self_host/connected.d.ts +5 -4
  13. package/dist/self_host/hosted_sync.d.ts +14 -23
  14. package/dist/self_host/hosted_sync.js +56 -120
  15. package/dist/self_host/main.js +0 -3
  16. package/dist/self_host/platform.js +2 -0
  17. package/dist/self_host/resolve.js +2 -1
  18. package/dist/self_host/subscriptions/index.d.ts +1 -1
  19. package/dist/self_host/subscriptions/index.js +1 -1
  20. package/dist/self_host/subscriptions/store.d.ts +8 -6
  21. package/dist/self_host/subscriptions/store.js +8 -16
  22. package/dist/telemetry/report.js +8 -1
  23. package/dist/types.d.ts +1 -0
  24. package/package.json +2 -2
  25. package/src/activity/conversation_detail.ts +8 -0
  26. package/src/link/endpoints.ts +4 -29
  27. package/src/link/service.ts +0 -4
  28. package/src/platform/platform.ts +2 -9
  29. package/src/protocol/input/anthropic_messages.ts +3 -9
  30. package/src/providers/execution.ts +1 -0
  31. package/src/providers/provider_call.ts +3 -0
  32. package/src/runtime/runtime_reporter.ts +3 -1
  33. package/src/self_host/connected.ts +5 -4
  34. package/src/self_host/hosted_sync.ts +51 -121
  35. package/src/self_host/main.ts +0 -3
  36. package/src/self_host/platform.ts +2 -1
  37. package/src/self_host/resolve.ts +2 -0
  38. package/src/self_host/subscriptions/index.ts +1 -0
  39. package/src/self_host/subscriptions/store.ts +14 -18
  40. package/src/telemetry/report.ts +8 -1
  41. package/src/types.ts +3 -0
@@ -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.366",
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.366",
55
+ "@mupt-ai/dari-router": "1.0.367",
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,
@@ -1324,32 +1324,9 @@ async function homePage(approval: LinkApprovalPage, authorize: AuthorizeRequest,
1324
1324
  if (current instanceof Response) return current;
1325
1325
  if (session === null) return introPage(approval, authorize);
1326
1326
  const subscriptions = await approval.subscriptions(session.subject);
1327
- const onComputers = await plansOnComputersNote(approval, authorize, session.subject, subscriptions);
1328
1327
  return shareable(authorize, subscriptions).length > 0
1329
- ? choosePage(authorize, session, subscriptions, current, undefined, onComputers)
1330
- : introPage(approval, authorize, onComputers);
1331
- }
1332
-
1333
- // Where the user keeps a plan the app could use on one of their computers,
1334
- // for each kind they have no plan of here: apps reach only the platform's.
1335
- async function plansOnComputersNote(
1336
- approval: LinkApprovalPage,
1337
- authorize: AuthorizeRequest,
1338
- subject: string,
1339
- subscriptions: LinkSubscription[],
1340
- ): Promise<string> {
1341
- if (approval.plansOnComputers === undefined) return "";
1342
- const here = new Set(subscriptions.map((subscription) => subscription.provider));
1343
- const usable = new Set(connectKinds(approval, authorize));
1344
- const computers = new Map<SubscriptionKind, string[]>();
1345
- for (const plan of await approval.plansOnComputers(subject)) {
1346
- if (here.has(plan.provider) || !usable.has(plan.provider)) continue;
1347
- const names = computers.get(plan.provider) ?? [];
1348
- if (!names.includes(plan.computer)) names.push(plan.computer);
1349
- computers.set(plan.provider, names);
1350
- }
1351
- return [...computers].map(([kind, names]) =>
1352
- `<p class="hint">Your ${KINDS[kind].name} plan is on ${escapeHtml(names.join(" and "))}. Apps can only use plans on Dari.</p>`).join("\n");
1328
+ ? choosePage(authorize, session, subscriptions, current)
1329
+ : introPage(approval, authorize);
1353
1330
  }
1354
1331
 
1355
1332
  // In update mode, the grant being changed. A grant this browser's user does
@@ -1887,7 +1864,7 @@ const KINDS: Record<SubscriptionKind, { name: string; plan: string; at: string;
1887
1864
  };
1888
1865
 
1889
1866
  // The first page a new user sees: what connecting means, and one button.
1890
- function introPage(approval: LinkApprovalPage, authorize: AuthorizeRequest, onComputers = ""): Response {
1867
+ function introPage(approval: LinkApprovalPage, authorize: AuthorizeRequest): Response {
1891
1868
  const app = escapeHtml(authorize.app.name);
1892
1869
  const kinds = connectKinds(approval, authorize);
1893
1870
  const keys = keyProviders(approval, authorize);
@@ -1909,7 +1886,7 @@ function introPage(approval: LinkApprovalPage, authorize: AuthorizeRequest, onCo
1909
1886
  <ul class="points">
1910
1887
  <li>${ICONS.zap}<div><strong>Connect In Seconds</strong><p>${kinds.length > 0 ? `Use what you already pay for: ${escapeHtml(ways)}.` : "Add the API key you already have."}</p></div></li>
1911
1888
  <li>${ICONS.shield}<div><strong>You Stay In Control</strong><p>${app} can only send model requests on what you share. It sees each shared plan's account email, never a key or your other plans, and you can disconnect it any time.</p></div></li>
1912
- </ul>${onComputers}`,
1889
+ </ul>`,
1913
1890
  footer: `<button class="btn primary" type="submit" name="decision" value="select">Continue</button>`,
1914
1891
  });
1915
1892
  }
@@ -2006,7 +1983,6 @@ function choosePage(
2006
1983
  subscriptions: LinkSubscription[],
2007
1984
  current: GrantToUpdate | null,
2008
1985
  error?: string,
2009
- onComputers = "",
2010
1986
  ): Response {
2011
1987
  const app = escapeHtml(authorize.app.name);
2012
1988
  const plans = shareable(authorize, subscriptions);
@@ -2021,7 +1997,6 @@ function choosePage(
2021
1997
  <!-- First in the form, so Enter in a limit field allows rather than pressing Connect Another. -->
2022
1998
  <button type="submit" name="decision" value="approve" tabindex="-1" aria-hidden="true" style="position:absolute;left:-9999px"></button>
2023
1999
  ${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
2024
- ${onComputers}
2025
2000
  <details${current?.limits.length ? " open" : ""}><summary>Set Limits</summary>
2026
2001
  ${plans.map((plan) => {
2027
2002
  const set = current?.limits.find((limit) => limit.credentialId === plan.id);
@@ -22,7 +22,6 @@ import type {
22
22
  LinkLimit,
23
23
  LinkManagedGrant,
24
24
  LinkPlanAdded,
25
- LinkPlanOnComputer,
26
25
  LinkPlatform,
27
26
  LinkSignIn,
28
27
  LinkSpend,
@@ -150,8 +149,6 @@ export type LinkUsers = {
150
149
  completeThrough(grantId: string): string | null;
151
150
  /** A user's plans and API keys, oldest first. */
152
151
  plans(subject: string): Promise<LinkSubscription[]>;
153
- /** See `LinkApprovalPage.plansOnComputers`. */
154
- plansOnComputers?(subject: string): Promise<LinkPlanOnComputer[]>;
155
152
  /** The plans and API keys with these ids, whoever added them. */
156
153
  plansWithIds(ids: readonly string[]): Promise<LinkSubscription[]>;
157
154
  /** See `LinkApprovalPage.addKey`; the provider is one of `keyProviders`. */
@@ -241,7 +238,6 @@ export function linkPlatform(store: LinkStore, users: LinkUsers): LinkPlatform {
241
238
  connectable: users.connectable,
242
239
  keyProviders: users.keyProviders,
243
240
  subscriptions: (subject) => users.plans(subject),
244
- ...(users.plansOnComputers === undefined ? {} : { plansOnComputers: users.plansOnComputers }),
245
241
  async addKey(subject, provider, apiKey) {
246
242
  if (!users.keyProviders.some((candidate) => candidate.id === provider)) {
247
243
  throw new HttpError(400, "Choose a provider to add a key for.", "invalid_request");
@@ -242,12 +242,6 @@ export type LinkApprovalPage = {
242
242
  addKey(subject: string | null, provider: string, apiKey: string): Promise<LinkPlanAdded>;
243
243
  /** The plans this user connected and the API keys they added, which an approval chooses among. */
244
244
  subscriptions(subject: string): Promise<LinkSubscription[]>;
245
- /**
246
- * The user's plans that live on one of their computers rather than on the
247
- * platform, which apps cannot use; the page says where each is. Absent on
248
- * a platform where every plan is its own.
249
- */
250
- plansOnComputers?(subject: string): Promise<LinkPlanOnComputer[]>;
251
245
  /** Start the provider's sign-in for a plan of this kind. */
252
246
  startConnect(kind: SubscriptionKind): Promise<LinkConnect>;
253
247
  /**
@@ -296,9 +290,6 @@ export type LinkSignIn = {
296
290
  redeem(ticket: string): Promise<{ subject: string; state: string; issuedAt: number } | null>;
297
291
  };
298
292
 
299
- /** A plan kept on one of the user's computers: its kind and the computer's name. */
300
- export type LinkPlanOnComputer = { provider: SubscriptionKind; computer: string };
301
-
302
293
  /** A plan or API key the user added, and who they are now. */
303
294
  export type LinkPlanAdded = { subject: string; credentialId: string };
304
295
 
@@ -592,6 +583,8 @@ export type NextSubscriptionRequest = {
592
583
 
593
584
  export type NextSubscription = {
594
585
  credentialId: string;
586
+ // The plan's name, as ProviderCredential.account.
587
+ account?: string;
595
588
  // The plan's access token, sent as the bearer credential.
596
589
  apiKey: string;
597
590
  };
@@ -384,17 +384,11 @@ function anthropicReasoningItem(
384
384
  type === "thinking" ? block.signature : block.data,
385
385
  `${param}.${type === "thinking" ? "signature" : "data"}`
386
386
  );
387
+ // A conversation begun on Anthropic directly carries raw signatures. They
388
+ // name no provider or model, so they cannot be replayed; the turn keeps its
389
+ // readable thinking and the conversation continues.
387
390
  const continuation = decodeUntrustedProviderContinuationState(encoded);
388
391
  const portable = continuation ? null : decodeUntrustedPortableReasoningState(encoded);
389
- if (!continuation && !portable) {
390
- const field = type === "thinking" ? "signature" : "data";
391
- throw new HttpError(
392
- 400,
393
- `${param}.${field} must be a Dari reasoning-state envelope; raw provider state has no recoverable provider/model provenance.`,
394
- "invalid_provider_continuation_state",
395
- `${param}.${field}`,
396
- );
397
- }
398
392
  const thinking = type === "thinking" ? requiredStringAllowEmpty(block.thinking, `${param}.thinking`) : "";
399
393
  const reasoning: Extract<InteractionItem, { type: "reasoning" }> = {
400
394
  type: "reasoning",
@@ -942,6 +942,7 @@ function onNextSubscription(choice: ProviderChoice, next: NextSubscription): Pro
942
942
  apiKey: next.apiKey,
943
943
  auth: { type: "bearer", apiKey: next.apiKey },
944
944
  subscriptionCredentialId: next.credentialId,
945
+ subscriptionAccount: next.account,
945
946
  },
946
947
  };
947
948
  }
@@ -79,6 +79,8 @@ export type ProviderExecution = ProviderCallConfig & {
79
79
  // subscriptions it is; undefined for router-owned keys.
80
80
  subscriptionUserId?: string;
81
81
  subscriptionCredentialId?: string;
82
+ // That plan's name, as ProviderCredential.account.
83
+ subscriptionAccount?: string;
82
84
  // The Dari Link grant whose subscriptions alone may serve this call.
83
85
  subscriptionLinkGrantId?: string;
84
86
  // The model's sources and the router's reset threshold, carried onto the
@@ -177,6 +179,7 @@ export function prepareProviderExecution(args: {
177
179
  ...(args.credentials.link_grant_id ? { subscriptionLinkGrantId: args.credentials.link_grant_id } : {}),
178
180
  }
179
181
  : {}),
182
+ ...(providerKeySource === "subscription" && supplied?.account ? { subscriptionAccount: supplied.account } : {}),
180
183
  thinkingLevel,
181
184
  usageContext: usageContextFor({
182
185
  billable: args.billable,
@@ -9,8 +9,9 @@ export type ReportedProviderExecution = {
9
9
  providerKeySource: ProviderKeySource;
10
10
  // The thinking the provider was sent, as X-Dari-Thinking-Level reports it.
11
11
  thinkingLevel?: string;
12
- // The user's subscription that served it.
12
+ // The user's subscription that served it, and its name.
13
13
  subscriptionCredentialId?: string;
14
+ subscriptionAccount?: string;
14
15
  };
15
16
 
16
17
  export function reportedExecution(
@@ -24,6 +25,7 @@ export function reportedExecution(
24
25
  ...(execution.subscriptionCredentialId === undefined
25
26
  ? {}
26
27
  : { subscriptionCredentialId: execution.subscriptionCredentialId }),
28
+ ...(execution.subscriptionAccount === undefined ? {} : { subscriptionAccount: execution.subscriptionAccount }),
27
29
  };
28
30
  }
29
31
 
@@ -26,10 +26,11 @@ import { gatewayKeyIndex, resolveSelfHostedRouter } from "./resolve.js";
26
26
  * Dari key (resolve.ts).
27
27
  * - Every other path the gateway does not manage itself, such as commit
28
28
  * reports, goes to hosted with the user's Dari key.
29
- * - The plans and the requests served here sync to hosted (hosted_sync.ts),
30
- * which shows them in Accounts and Activity. Private plans serve, but
31
- * neither they nor their requests sync; requests hosted Dari served are
32
- * hosted's to log. Dari Link and Activity are hosted's, not served here.
29
+ * - The requests served here sync to hosted Activity (hosted_sync.ts), each
30
+ * naming the plan that served it. The plans themselves never leave this
31
+ * computer. A private plan's requests do not sync either; requests hosted
32
+ * Dari served are hosted's to log. Dari Link and Activity are hosted's, not
33
+ * served here.
33
34
  */
34
35
  export type HostedConnection = {
35
36
  // The hosted routing service, e.g. https://routing.dari.dev.
@@ -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
- }
@@ -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,