@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.
- package/dist/activity/conversation_detail.js +8 -0
- package/dist/link/endpoints.js +5 -25
- package/dist/link/service.d.ts +1 -3
- package/dist/link/service.js +0 -1
- package/dist/platform/platform.d.ts +1 -11
- package/dist/protocol/input/anthropic_messages.js +3 -4
- package/dist/providers/execution.js +1 -0
- package/dist/providers/provider_call.d.ts +1 -0
- package/dist/providers/provider_call.js +1 -0
- package/dist/runtime/runtime_reporter.d.ts +1 -0
- package/dist/runtime/runtime_reporter.js +1 -0
- package/dist/self_host/connected.d.ts +5 -4
- package/dist/self_host/hosted_sync.d.ts +14 -23
- package/dist/self_host/hosted_sync.js +56 -120
- package/dist/self_host/main.js +0 -3
- package/dist/self_host/platform.js +2 -0
- package/dist/self_host/resolve.js +2 -1
- package/dist/self_host/subscriptions/index.d.ts +1 -1
- package/dist/self_host/subscriptions/index.js +1 -1
- package/dist/self_host/subscriptions/store.d.ts +8 -6
- package/dist/self_host/subscriptions/store.js +8 -16
- package/dist/telemetry/report.js +8 -1
- package/dist/types.d.ts +1 -0
- package/package.json +2 -2
- package/src/activity/conversation_detail.ts +8 -0
- package/src/link/endpoints.ts +4 -29
- package/src/link/service.ts +0 -4
- package/src/platform/platform.ts +2 -9
- package/src/protocol/input/anthropic_messages.ts +3 -9
- package/src/providers/execution.ts +1 -0
- package/src/providers/provider_call.ts +3 -0
- package/src/runtime/runtime_reporter.ts +3 -1
- package/src/self_host/connected.ts +5 -4
- package/src/self_host/hosted_sync.ts +51 -121
- package/src/self_host/main.ts +0 -3
- package/src/self_host/platform.ts +2 -1
- package/src/self_host/resolve.ts +2 -0
- package/src/self_host/subscriptions/index.ts +1 -0
- package/src/self_host/subscriptions/store.ts +14 -18
- package/src/telemetry/report.ts +8 -1
- package/src/types.ts +3 -0
|
@@ -30,6 +30,13 @@ function agentContext(record) {
|
|
|
30
30
|
agentType: readOptionalString(value.agentType),
|
|
31
31
|
};
|
|
32
32
|
}
|
|
33
|
+
/** The name of the plan that served the request, when one did. */
|
|
34
|
+
function subscriptionAccount(record) {
|
|
35
|
+
const metadata = record.requestMetadata;
|
|
36
|
+
if (metadata === null || typeof metadata !== "object" || Array.isArray(metadata))
|
|
37
|
+
return null;
|
|
38
|
+
return readOptionalString(metadata.subscription_account);
|
|
39
|
+
}
|
|
33
40
|
function routePath(records) {
|
|
34
41
|
const path = [];
|
|
35
42
|
for (const record of records) {
|
|
@@ -187,6 +194,7 @@ function conversationStep(record, organizationId, currentRouterZdr, skillEvents)
|
|
|
187
194
|
selected_model: record.selectedModel,
|
|
188
195
|
selected_reasoning_effort: effort,
|
|
189
196
|
selected_provider: record.selectedProvider,
|
|
197
|
+
subscription_account: subscriptionAccount(record),
|
|
190
198
|
provider_input_tokens: record.providerInputTokens,
|
|
191
199
|
provider_cache_read_tokens: record.providerCacheReadTokens,
|
|
192
200
|
provider_cache_write_tokens: record.providerCacheWriteTokens,
|
package/dist/link/endpoints.js
CHANGED
|
@@ -1183,28 +1183,9 @@ async function homePage(approval, authorize, session) {
|
|
|
1183
1183
|
if (session === null)
|
|
1184
1184
|
return introPage(approval, authorize);
|
|
1185
1185
|
const subscriptions = await approval.subscriptions(session.subject);
|
|
1186
|
-
const onComputers = await plansOnComputersNote(approval, authorize, session.subject, subscriptions);
|
|
1187
1186
|
return shareable(authorize, subscriptions).length > 0
|
|
1188
|
-
? choosePage(authorize, session, subscriptions, current
|
|
1189
|
-
: introPage(approval, authorize
|
|
1190
|
-
}
|
|
1191
|
-
// Where the user keeps a plan the app could use on one of their computers,
|
|
1192
|
-
// for each kind they have no plan of here: apps reach only the platform's.
|
|
1193
|
-
async function plansOnComputersNote(approval, authorize, subject, subscriptions) {
|
|
1194
|
-
if (approval.plansOnComputers === undefined)
|
|
1195
|
-
return "";
|
|
1196
|
-
const here = new Set(subscriptions.map((subscription) => subscription.provider));
|
|
1197
|
-
const usable = new Set(connectKinds(approval, authorize));
|
|
1198
|
-
const computers = new Map();
|
|
1199
|
-
for (const plan of await approval.plansOnComputers(subject)) {
|
|
1200
|
-
if (here.has(plan.provider) || !usable.has(plan.provider))
|
|
1201
|
-
continue;
|
|
1202
|
-
const names = computers.get(plan.provider) ?? [];
|
|
1203
|
-
if (!names.includes(plan.computer))
|
|
1204
|
-
names.push(plan.computer);
|
|
1205
|
-
computers.set(plan.provider, names);
|
|
1206
|
-
}
|
|
1207
|
-
return [...computers].map(([kind, names]) => `<p class="hint">Your ${KINDS[kind].name} plan is on ${escapeHtml(names.join(" and "))}. Apps can only use plans on Dari.</p>`).join("\n");
|
|
1187
|
+
? choosePage(authorize, session, subscriptions, current)
|
|
1188
|
+
: introPage(approval, authorize);
|
|
1208
1189
|
}
|
|
1209
1190
|
// In update mode, the grant being changed. A grant this browser's user does
|
|
1210
1191
|
// not hold (another browser, cleared cookies) starts a new connection instead,
|
|
@@ -1689,7 +1670,7 @@ const KINDS = {
|
|
|
1689
1670
|
vercel_token_pass: { name: "Vercel Token Pass", plan: "Token Pass", at: "Vercel", pastedKey: true },
|
|
1690
1671
|
};
|
|
1691
1672
|
// The first page a new user sees: what connecting means, and one button.
|
|
1692
|
-
function introPage(approval, authorize
|
|
1673
|
+
function introPage(approval, authorize) {
|
|
1693
1674
|
const app = escapeHtml(authorize.app.name);
|
|
1694
1675
|
const kinds = connectKinds(approval, authorize);
|
|
1695
1676
|
const keys = keyProviders(approval, authorize);
|
|
@@ -1707,7 +1688,7 @@ function introPage(approval, authorize, onComputers = "") {
|
|
|
1707
1688
|
<ul class="points">
|
|
1708
1689
|
<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>
|
|
1709
1690
|
<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>
|
|
1710
|
-
</ul
|
|
1691
|
+
</ul>`,
|
|
1711
1692
|
footer: `<button class="btn primary" type="submit" name="decision" value="select">Continue</button>`,
|
|
1712
1693
|
});
|
|
1713
1694
|
}
|
|
@@ -1791,7 +1772,7 @@ function providerPage(authorize, connect, error) {
|
|
|
1791
1772
|
});
|
|
1792
1773
|
}
|
|
1793
1774
|
// The user's plans and keys, ticked: one button shares them with the app.
|
|
1794
|
-
function choosePage(authorize, session, subscriptions, current, error
|
|
1775
|
+
function choosePage(authorize, session, subscriptions, current, error) {
|
|
1795
1776
|
const app = escapeHtml(authorize.app.name);
|
|
1796
1777
|
const plans = shareable(authorize, subscriptions);
|
|
1797
1778
|
// A new connection starts with every plan ticked; an update, with the plans it shares now.
|
|
@@ -1805,7 +1786,6 @@ function choosePage(authorize, session, subscriptions, current, error, onCompute
|
|
|
1805
1786
|
<!-- First in the form, so Enter in a limit field allows rather than pressing Connect Another. -->
|
|
1806
1787
|
<button type="submit" name="decision" value="approve" tabindex="-1" aria-hidden="true" style="position:absolute;left:-9999px"></button>
|
|
1807
1788
|
${plans.map((plan) => planOption(authorize, plan, ticked.has(plan.id))).join("\n")}
|
|
1808
|
-
${onComputers}
|
|
1809
1789
|
<details${current?.limits.length ? " open" : ""}><summary>Set Limits</summary>
|
|
1810
1790
|
${plans.map((plan) => {
|
|
1811
1791
|
const set = current?.limits.find((limit) => limit.credentialId === plan.id);
|
package/dist/link/service.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { LinkBudget, LinkConnect, LinkKeyProvider, LinkLimit, LinkPlanAdded,
|
|
1
|
+
import type { LinkBudget, LinkConnect, LinkKeyProvider, LinkLimit, LinkPlanAdded, LinkPlatform, LinkSignIn, LinkSubscription } from "../platform/platform.js";
|
|
2
2
|
import type { SubscriptionKind } from "../types.js";
|
|
3
3
|
import { type BudgetUse } from "./budget.js";
|
|
4
4
|
import { type ActiveLinkGrant, type LinkAppRecord, type LinkRepo, type LinkTokenIssue } from "./grants.js";
|
|
@@ -95,8 +95,6 @@ export type LinkUsers = {
|
|
|
95
95
|
completeThrough(grantId: string): string | null;
|
|
96
96
|
/** A user's plans and API keys, oldest first. */
|
|
97
97
|
plans(subject: string): Promise<LinkSubscription[]>;
|
|
98
|
-
/** See `LinkApprovalPage.plansOnComputers`. */
|
|
99
|
-
plansOnComputers?(subject: string): Promise<LinkPlanOnComputer[]>;
|
|
100
98
|
/** The plans and API keys with these ids, whoever added them. */
|
|
101
99
|
plansWithIds(ids: readonly string[]): Promise<LinkSubscription[]>;
|
|
102
100
|
/** See `LinkApprovalPage.addKey`; the provider is one of `keyProviders`. */
|
package/dist/link/service.js
CHANGED
|
@@ -81,7 +81,6 @@ export function linkPlatform(store, users) {
|
|
|
81
81
|
connectable: users.connectable,
|
|
82
82
|
keyProviders: users.keyProviders,
|
|
83
83
|
subscriptions: (subject) => users.plans(subject),
|
|
84
|
-
...(users.plansOnComputers === undefined ? {} : { plansOnComputers: users.plansOnComputers }),
|
|
85
84
|
async addKey(subject, provider, apiKey) {
|
|
86
85
|
if (!users.keyProviders.some((candidate) => candidate.id === provider)) {
|
|
87
86
|
throw new HttpError(400, "Choose a provider to add a key for.", "invalid_request");
|
|
@@ -255,12 +255,6 @@ export type LinkApprovalPage = {
|
|
|
255
255
|
addKey(subject: string | null, provider: string, apiKey: string): Promise<LinkPlanAdded>;
|
|
256
256
|
/** The plans this user connected and the API keys they added, which an approval chooses among. */
|
|
257
257
|
subscriptions(subject: string): Promise<LinkSubscription[]>;
|
|
258
|
-
/**
|
|
259
|
-
* The user's plans that live on one of their computers rather than on the
|
|
260
|
-
* platform, which apps cannot use; the page says where each is. Absent on
|
|
261
|
-
* a platform where every plan is its own.
|
|
262
|
-
*/
|
|
263
|
-
plansOnComputers?(subject: string): Promise<LinkPlanOnComputer[]>;
|
|
264
258
|
/** Start the provider's sign-in for a plan of this kind. */
|
|
265
259
|
startConnect(kind: SubscriptionKind): Promise<LinkConnect>;
|
|
266
260
|
/**
|
|
@@ -313,11 +307,6 @@ export type LinkSignIn = {
|
|
|
313
307
|
issuedAt: number;
|
|
314
308
|
} | null>;
|
|
315
309
|
};
|
|
316
|
-
/** A plan kept on one of the user's computers: its kind and the computer's name. */
|
|
317
|
-
export type LinkPlanOnComputer = {
|
|
318
|
-
provider: SubscriptionKind;
|
|
319
|
-
computer: string;
|
|
320
|
-
};
|
|
321
310
|
/** A plan or API key the user added, and who they are now. */
|
|
322
311
|
export type LinkPlanAdded = {
|
|
323
312
|
subject: string;
|
|
@@ -550,6 +539,7 @@ export type NextSubscriptionRequest = {
|
|
|
550
539
|
};
|
|
551
540
|
export type NextSubscription = {
|
|
552
541
|
credentialId: string;
|
|
542
|
+
account?: string;
|
|
553
543
|
apiKey: string;
|
|
554
544
|
};
|
|
555
545
|
export type SubscriptionUsageReport = {
|
|
@@ -352,12 +352,11 @@ function anthropicImage(value, param) {
|
|
|
352
352
|
}
|
|
353
353
|
function anthropicReasoningItem(block, type, param) {
|
|
354
354
|
const encoded = requiredString(type === "thinking" ? block.signature : block.data, `${param}.${type === "thinking" ? "signature" : "data"}`);
|
|
355
|
+
// A conversation begun on Anthropic directly carries raw signatures. They
|
|
356
|
+
// name no provider or model, so they cannot be replayed; the turn keeps its
|
|
357
|
+
// readable thinking and the conversation continues.
|
|
355
358
|
const continuation = decodeUntrustedProviderContinuationState(encoded);
|
|
356
359
|
const portable = continuation ? null : decodeUntrustedPortableReasoningState(encoded);
|
|
357
|
-
if (!continuation && !portable) {
|
|
358
|
-
const field = type === "thinking" ? "signature" : "data";
|
|
359
|
-
throw new HttpError(400, `${param}.${field} must be a Dari reasoning-state envelope; raw provider state has no recoverable provider/model provenance.`, "invalid_provider_continuation_state", `${param}.${field}`);
|
|
360
|
-
}
|
|
361
360
|
const thinking = type === "thinking" ? requiredStringAllowEmpty(block.thinking, `${param}.thinking`) : "";
|
|
362
361
|
const reasoning = {
|
|
363
362
|
type: "reasoning",
|
|
@@ -27,6 +27,7 @@ export type ProviderExecution = ProviderCallConfig & {
|
|
|
27
27
|
providerKeySource: ProviderKeySource;
|
|
28
28
|
subscriptionUserId?: string;
|
|
29
29
|
subscriptionCredentialId?: string;
|
|
30
|
+
subscriptionAccount?: string;
|
|
30
31
|
subscriptionLinkGrantId?: string;
|
|
31
32
|
subscriptionSources?: Source[];
|
|
32
33
|
subscriptionResetMinHours?: number;
|
|
@@ -62,6 +62,7 @@ export function prepareProviderExecution(args) {
|
|
|
62
62
|
...(args.credentials.link_grant_id ? { subscriptionLinkGrantId: args.credentials.link_grant_id } : {}),
|
|
63
63
|
}
|
|
64
64
|
: {}),
|
|
65
|
+
...(providerKeySource === "subscription" && supplied?.account ? { subscriptionAccount: supplied.account } : {}),
|
|
65
66
|
thinkingLevel,
|
|
66
67
|
usageContext: usageContextFor({
|
|
67
68
|
billable: args.billable,
|
|
@@ -8,6 +8,7 @@ export type ReportedProviderExecution = {
|
|
|
8
8
|
providerKeySource: ProviderKeySource;
|
|
9
9
|
thinkingLevel?: string;
|
|
10
10
|
subscriptionCredentialId?: string;
|
|
11
|
+
subscriptionAccount?: string;
|
|
11
12
|
};
|
|
12
13
|
export declare function reportedExecution(execution: ReportedProviderExecution): ReportedProviderExecution;
|
|
13
14
|
export type ReportableProviderOutcome = {
|
|
@@ -7,6 +7,7 @@ export function reportedExecution(execution) {
|
|
|
7
7
|
...(execution.subscriptionCredentialId === undefined
|
|
8
8
|
? {}
|
|
9
9
|
: { subscriptionCredentialId: execution.subscriptionCredentialId }),
|
|
10
|
+
...(execution.subscriptionAccount === undefined ? {} : { subscriptionAccount: execution.subscriptionAccount }),
|
|
10
11
|
};
|
|
11
12
|
}
|
|
12
13
|
export function createExperimentRoutedRuntimeReporter() {
|
|
@@ -16,10 +16,11 @@ import { createSelfHostedPlatform } from "./platform.js";
|
|
|
16
16
|
* Dari key (resolve.ts).
|
|
17
17
|
* - Every other path the gateway does not manage itself, such as commit
|
|
18
18
|
* reports, goes to hosted with the user's Dari key.
|
|
19
|
-
* - The
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* hosted's to log. Dari Link and Activity are hosted's, not
|
|
19
|
+
* - The requests served here sync to hosted Activity (hosted_sync.ts), each
|
|
20
|
+
* naming the plan that served it. The plans themselves never leave this
|
|
21
|
+
* computer. A private plan's requests do not sync either; requests hosted
|
|
22
|
+
* Dari served are hosted's to log. Dari Link and Activity are hosted's, not
|
|
23
|
+
* served here.
|
|
23
24
|
*/
|
|
24
25
|
export type HostedConnection = {
|
|
25
26
|
url: string;
|
|
@@ -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:
|
|
6
|
-
*
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
*
|
|
10
|
-
*
|
|
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
|
|
19
|
-
private
|
|
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
|
-
/**
|
|
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
|
-
|
|
38
|
-
|
|
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
|
|
50
|
-
*
|
|
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 {
|
|
1
|
+
import { SUBSCRIPTION_PROVIDERS, } from "./subscriptions/index.js";
|
|
2
2
|
// Hosted Dari's per-call limit, and a size that stays well under its body cap.
|
|
3
3
|
const MAX_BATCH_ROWS = 16;
|
|
4
4
|
const MAX_BATCH_BYTES = 8 * 1024 * 1024;
|
|
5
5
|
// A row past this sheds its request and response bodies, as hosted ingest does.
|
|
6
6
|
const MAX_ROW_BYTES = 4 * 1024 * 1024;
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
const USAGE_INTERVAL_MS = 60_000;
|
|
10
|
-
// Plans are reported at least this often, so hosted can tell a computer that
|
|
11
|
-
// is gone (its plans stop counting as connected after a day) from a quiet one.
|
|
12
|
-
const HEARTBEAT_MS = 60 * 60_000;
|
|
7
|
+
// How often this computer's plans are checked against the accounts on Dari.
|
|
8
|
+
const ACCOUNTS_CHECK_MS = 60 * 60_000;
|
|
13
9
|
const RETRY_BASE_MS = 5_000;
|
|
14
10
|
const RETRY_MAX_MS = 15 * 60_000;
|
|
15
11
|
const DRAIN_INTERVAL_MS = 2_000;
|
|
16
12
|
/**
|
|
17
|
-
* What a gateway connected to hosted Dari tells it:
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
13
|
+
* What a gateway connected to hosted Dari tells it: the requests it served,
|
|
14
|
+
* for Activity, `POST /v1/gateway/requests`. Rows wait in a SQLite outbox,
|
|
15
|
+
* sent in batches with backoff until hosted takes them. Requests a private
|
|
16
|
+
* plan served are never queued. This computer's plans themselves never leave
|
|
17
|
+
* it; it only reads the accounts on Dari (`GET /v1/gateway/accounts`), to drop
|
|
18
|
+
* a plan whose account was since connected there.
|
|
23
19
|
*/
|
|
24
20
|
export class HostedSync {
|
|
25
21
|
db;
|
|
@@ -27,12 +23,8 @@ export class HostedSync {
|
|
|
27
23
|
hosted;
|
|
28
24
|
fetch;
|
|
29
25
|
now;
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
snapshotFailures = 0;
|
|
33
|
-
// Snapshots go one at a time, so an older one never lands after a newer one.
|
|
34
|
-
snapshots = Promise.resolve();
|
|
35
|
-
lastSnapshotAt = 0;
|
|
26
|
+
accountsTimer = null;
|
|
27
|
+
accountsFailures = 0;
|
|
36
28
|
drainTimer = null;
|
|
37
29
|
draining = null;
|
|
38
30
|
drainFailures = 0;
|
|
@@ -49,29 +41,21 @@ export class HostedSync {
|
|
|
49
41
|
queued_at INTEGER NOT NULL
|
|
50
42
|
)`);
|
|
51
43
|
}
|
|
52
|
-
/**
|
|
44
|
+
/** Check the accounts on Dari and send waiting requests now, then keep at it. */
|
|
53
45
|
start() {
|
|
54
|
-
this.
|
|
46
|
+
this.scheduleAccountsCheck(0);
|
|
55
47
|
this.drainTimer = setInterval(() => void this.drain(), DRAIN_INTERVAL_MS);
|
|
56
48
|
this.drainTimer.unref?.();
|
|
57
49
|
void this.drain();
|
|
58
50
|
}
|
|
59
51
|
stop() {
|
|
60
|
-
if (this.
|
|
61
|
-
clearTimeout(this.
|
|
52
|
+
if (this.accountsTimer !== null)
|
|
53
|
+
clearTimeout(this.accountsTimer);
|
|
62
54
|
if (this.drainTimer !== null)
|
|
63
55
|
clearInterval(this.drainTimer);
|
|
64
|
-
this.
|
|
56
|
+
this.accountsTimer = null;
|
|
65
57
|
this.drainTimer = null;
|
|
66
58
|
}
|
|
67
|
-
/** A plan was connected, removed, renamed, moved, held, or released. */
|
|
68
|
-
plansChanged() {
|
|
69
|
-
this.scheduleSnapshot(PLANS_DEBOUNCE_MS);
|
|
70
|
-
}
|
|
71
|
-
/** A plan reported usage or served a turn. */
|
|
72
|
-
usageChanged() {
|
|
73
|
-
this.scheduleSnapshot(Math.max(PLANS_DEBOUNCE_MS, this.lastSnapshotAt + USAGE_INTERVAL_MS - this.now()));
|
|
74
|
-
}
|
|
75
59
|
/** Queue a served request's log row for hosted Activity. */
|
|
76
60
|
enqueue(row) {
|
|
77
61
|
let json = JSON.stringify(row);
|
|
@@ -85,59 +69,35 @@ export class HostedSync {
|
|
|
85
69
|
}
|
|
86
70
|
this.db.run("INSERT INTO hosted_request_outbox (row_json, queued_at) VALUES (?, ?)", [json, this.now()]);
|
|
87
71
|
}
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
return {
|
|
92
|
-
gateway_id: this.hosted.gatewayId,
|
|
93
|
-
gateway_name: this.hosted.gatewayName,
|
|
94
|
-
subscriptions: this.subscriptions.list().filter((plan) => !plan.private).map((plan) => planReport(plan, now)),
|
|
95
|
-
};
|
|
96
|
-
}
|
|
97
|
-
// Keeps the earliest of the snapshots asked for.
|
|
98
|
-
scheduleSnapshot(delayMs) {
|
|
99
|
-
const dueAt = this.now() + delayMs;
|
|
100
|
-
if (this.snapshotTimer !== null && this.snapshotDueAt <= dueAt)
|
|
101
|
-
return;
|
|
102
|
-
if (this.snapshotTimer !== null)
|
|
103
|
-
clearTimeout(this.snapshotTimer);
|
|
104
|
-
this.snapshotDueAt = dueAt;
|
|
105
|
-
this.snapshotTimer = setTimeout(() => {
|
|
106
|
-
this.snapshotTimer = null;
|
|
107
|
-
this.snapshotDueAt = Infinity;
|
|
108
|
-
this.snapshots = this.snapshots.then(() => this.putSnapshot());
|
|
109
|
-
}, delayMs);
|
|
110
|
-
this.snapshotTimer.unref?.();
|
|
72
|
+
scheduleAccountsCheck(delayMs) {
|
|
73
|
+
this.accountsTimer = setTimeout(() => void this.checkAccounts(), delayMs);
|
|
74
|
+
this.accountsTimer.unref?.();
|
|
111
75
|
}
|
|
112
|
-
|
|
113
|
-
|
|
76
|
+
// A plan here whose account was connected on Dari after it was connected
|
|
77
|
+
// here: Dari's plan serves this computer too, so the copy here goes. Only
|
|
78
|
+
// the account id matches, never the email alone: one email can hold several
|
|
79
|
+
// ChatGPT workspaces or Claude organizations.
|
|
80
|
+
async checkAccounts() {
|
|
114
81
|
try {
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
82
|
+
const onDari = await readHostedAccounts(this.hosted, this.fetch);
|
|
83
|
+
this.accountsFailures = 0;
|
|
84
|
+
for (const plan of this.subscriptions.list()) {
|
|
85
|
+
if (plan.owner !== null || plan.private || plan.accountId === null)
|
|
86
|
+
continue;
|
|
87
|
+
const moved = onDari.some((account) => account.provider === plan.provider
|
|
88
|
+
&& account.accountId === plan.accountId
|
|
89
|
+
&& account.connectedAt !== undefined && account.connectedAt > plan.createdAt);
|
|
90
|
+
if (!moved)
|
|
91
|
+
continue;
|
|
92
|
+
this.subscriptions.disconnect(plan.name);
|
|
93
|
+
console.error(`${plan.name} is now connected on Dari; removed it from this computer`);
|
|
94
|
+
}
|
|
95
|
+
this.scheduleAccountsCheck(ACCOUNTS_CHECK_MS);
|
|
122
96
|
}
|
|
123
97
|
catch (error) {
|
|
124
|
-
this.
|
|
125
|
-
console.error("hosted
|
|
126
|
-
this.
|
|
127
|
-
}
|
|
128
|
-
}
|
|
129
|
-
// Hosted Dari names the reported plans whose account was since connected on
|
|
130
|
-
// Dari. Dari's plan serves this computer too, so the copy here goes, and
|
|
131
|
-
// disconnecting it reports the plans again.
|
|
132
|
-
dropPlansOnDari(localIds) {
|
|
133
|
-
if (!Array.isArray(localIds))
|
|
134
|
-
return;
|
|
135
|
-
for (const id of localIds) {
|
|
136
|
-
const plan = typeof id === "string" ? this.subscriptions.get(id) : null;
|
|
137
|
-
if (plan === null || plan.owner !== null || plan.private)
|
|
138
|
-
continue;
|
|
139
|
-
this.subscriptions.disconnect(plan.name);
|
|
140
|
-
console.error(`${plan.name} is now connected on Dari; removed it from this computer`);
|
|
98
|
+
this.accountsFailures += 1;
|
|
99
|
+
console.error("hosted accounts check failed", error instanceof Error ? error.message : String(error));
|
|
100
|
+
this.scheduleAccountsCheck(backoff(this.accountsFailures));
|
|
141
101
|
}
|
|
142
102
|
}
|
|
143
103
|
/** Send the queued request rows a batch at a time, unless hosted failed lately. */
|
|
@@ -203,8 +163,9 @@ export class HostedSync {
|
|
|
203
163
|
}
|
|
204
164
|
/**
|
|
205
165
|
* The user's plans on hosted Dari, for the check before a sign-in connects an
|
|
206
|
-
* account
|
|
207
|
-
*
|
|
166
|
+
* account and for dropping a plan here that moved there: `GET
|
|
167
|
+
* /v1/gateway/accounts` returns each one's provider, account identity, name,
|
|
168
|
+
* and when it was connected, never a token. Other computers may hold the same
|
|
208
169
|
* account, so only Dari's plans count.
|
|
209
170
|
*/
|
|
210
171
|
export async function readHostedAccounts(hosted, fetchImpl) {
|
|
@@ -225,9 +186,9 @@ export async function readHostedAccounts(hosted, fetchImpl) {
|
|
|
225
186
|
// Hosted Dari before this release also listed other computers' plans.
|
|
226
187
|
if (entry.where !== "dari")
|
|
227
188
|
continue;
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
189
|
+
// A provider this gateway does not know holds no account of a plan here.
|
|
190
|
+
if (!SUBSCRIPTION_PROVIDERS.includes(entry.provider))
|
|
191
|
+
continue;
|
|
231
192
|
let accountId = null;
|
|
232
193
|
if (typeof entry.account_id === "string")
|
|
233
194
|
accountId = entry.account_id;
|
|
@@ -237,43 +198,18 @@ export async function readHostedAccounts(hosted, fetchImpl) {
|
|
|
237
198
|
let name = null;
|
|
238
199
|
if (typeof entry.name === "string")
|
|
239
200
|
name = entry.name;
|
|
240
|
-
|
|
201
|
+
const connectedAt = typeof entry.connected_at === "string" ? new Date(entry.connected_at) : undefined;
|
|
202
|
+
accounts.push({
|
|
203
|
+
provider: entry.provider,
|
|
204
|
+
accountId,
|
|
205
|
+
accountEmail,
|
|
206
|
+
place: "dari",
|
|
207
|
+
name,
|
|
208
|
+
...(connectedAt === undefined || Number.isNaN(connectedAt.getTime()) ? {} : { connectedAt }),
|
|
209
|
+
});
|
|
241
210
|
}
|
|
242
211
|
return accounts;
|
|
243
212
|
}
|
|
244
213
|
function backoff(failures) {
|
|
245
214
|
return Math.min(RETRY_MAX_MS, RETRY_BASE_MS * 2 ** Math.max(0, failures - 1));
|
|
246
215
|
}
|
|
247
|
-
// One plan as `PUT /v1/gateway/subscriptions` takes it. Usage uses the keys
|
|
248
|
-
// and formats hosted subscriptions keep in their metadata.
|
|
249
|
-
function planReport(plan, now) {
|
|
250
|
-
const held = isHeld(plan, now);
|
|
251
|
-
const usage = plan.usage;
|
|
252
|
-
return {
|
|
253
|
-
local_id: plan.id,
|
|
254
|
-
provider: plan.provider,
|
|
255
|
-
label: plan.label,
|
|
256
|
-
account_email: plan.accountEmail,
|
|
257
|
-
account_id: plan.accountId,
|
|
258
|
-
plan: null,
|
|
259
|
-
connected_at: plan.createdAt.toISOString(),
|
|
260
|
-
last_used_at: plan.lastUsedAt?.toISOString() ?? null,
|
|
261
|
-
unavailable_until: held ? plan.unavailableUntil.toISOString() : null,
|
|
262
|
-
unavailable_reason: held ? plan.unavailableReason : null,
|
|
263
|
-
model_holds: Object.fromEntries(activeModelHolds(plan, now).map((hold) => [
|
|
264
|
-
hold.model,
|
|
265
|
-
{ until: hold.until.toISOString(), reason: hold.reason },
|
|
266
|
-
])),
|
|
267
|
-
usage: usage === null ? {} : {
|
|
268
|
-
usage_utilization: usage.utilization.toFixed(4),
|
|
269
|
-
usage_resets_at: usage.resetsAt.toISOString(),
|
|
270
|
-
usage_windows: JSON.stringify(usage.windows.map((window) => ({
|
|
271
|
-
...(window.modelFamily === undefined ? {} : { model_family: window.modelFamily }),
|
|
272
|
-
minutes: window.minutes,
|
|
273
|
-
utilization: Math.round(window.utilization * 10_000) / 10_000,
|
|
274
|
-
resets_at: window.resetsAt.toISOString(),
|
|
275
|
-
}))),
|
|
276
|
-
usage_observed_at: usage.observedAt.toISOString(),
|
|
277
|
-
},
|
|
278
|
-
};
|
|
279
|
-
}
|
package/dist/self_host/main.js
CHANGED
|
@@ -106,9 +106,6 @@ export async function startSelfHostedGateway(env = process.env) {
|
|
|
106
106
|
// The hosted router, read once a minute, for both serving and routing calls.
|
|
107
107
|
const hostedRouter = hosted === null ? null : hostedRouters(hosted, fetch);
|
|
108
108
|
const baseUrls = providerBaseUrls(config.providers);
|
|
109
|
-
if (sync !== null) {
|
|
110
|
-
subscriptions.onChange = (change) => change === "usage" ? sync.usageChanged() : sync.plansChanged();
|
|
111
|
-
}
|
|
112
109
|
const platformDeps = {
|
|
113
110
|
activity,
|
|
114
111
|
config,
|
|
@@ -6,6 +6,7 @@ import { subscriptionOAuthProviderFor } from "../providers/subscription_limits.j
|
|
|
6
6
|
import { SELF_HOSTED_BLOB_BUCKET } from "./activity_store.js";
|
|
7
7
|
import { servedRouter } from "./router_specs.js";
|
|
8
8
|
import { gatewayKeyIndex, resolveSelfHostedRouter, SELF_HOSTED_ORGANIZATION_ID, } from "./resolve.js";
|
|
9
|
+
import { planAccount } from "./subscriptions/index.js";
|
|
9
10
|
import { refreshedAccessToken } from "./subscriptions/access.js";
|
|
10
11
|
import { hasBankedResets, providerBaseUrls, recoverHeldPlans } from "./subscriptions/resets.js";
|
|
11
12
|
/**
|
|
@@ -46,6 +47,7 @@ export function createSelfHostedPlatform(deps) {
|
|
|
46
47
|
return undefined;
|
|
47
48
|
return {
|
|
48
49
|
credentialId: next.id,
|
|
50
|
+
...planAccount(next),
|
|
49
51
|
apiKey: await refreshedAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
|
|
50
52
|
};
|
|
51
53
|
},
|
|
@@ -15,7 +15,7 @@ import { linkSubscription } from "../link/self_hosted.js";
|
|
|
15
15
|
import { linkTokenGrant } from "../link/service.js";
|
|
16
16
|
import { servedRouter } from "./router_specs.js";
|
|
17
17
|
import { refreshedAccessToken } from "./subscriptions/access.js";
|
|
18
|
-
import { activeModelHolds, freshAccessToken, } from "./subscriptions/index.js";
|
|
18
|
+
import { activeModelHolds, freshAccessToken, planAccount, } from "./subscriptions/index.js";
|
|
19
19
|
// A self-hosted gateway is one tenant; these stand in for the hosted
|
|
20
20
|
// organization and the user a personal subscription belongs to.
|
|
21
21
|
export const SELF_HOSTED_ORGANIZATION_ID = "self-hosted";
|
|
@@ -221,6 +221,7 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
221
221
|
apiKey: await planToken(first.plan),
|
|
222
222
|
subscription: first.plan.provider,
|
|
223
223
|
credentialId: first.plan.id,
|
|
224
|
+
...planAccount(first.plan),
|
|
224
225
|
};
|
|
225
226
|
}
|
|
226
227
|
else {
|
|
@@ -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;
|