@mupt-ai/dari-gateway 1.0.310 → 1.0.312
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +4 -0
- package/dari-gateway.example.yaml +10 -0
- package/dist/context/provider_prompt_accounting.js +7 -0
- package/dist/context/routing_context.js +4 -1
- package/dist/interaction/system_prompt.d.ts +2 -0
- package/dist/interaction/system_prompt.js +21 -0
- package/dist/models/canonical.d.ts +2 -0
- package/dist/models/canonical.js +4 -0
- package/dist/models/catalog.js +1 -0
- package/dist/models/provider_defaults.js +4 -0
- package/dist/models/subscriptions.d.ts +4 -3
- package/dist/models/subscriptions.js +13 -9
- package/dist/platform/platform.d.ts +3 -0
- package/dist/providers/codex_usage.d.ts +13 -0
- package/dist/providers/codex_usage.js +46 -2
- package/dist/providers/execution.js +62 -9
- package/dist/providers/key_check.js +3 -0
- package/dist/providers/pi.js +5 -0
- package/dist/providers/pi_options.js +8 -0
- package/dist/providers/provider_call.d.ts +2 -0
- package/dist/providers/provider_call.js +9 -3
- package/dist/providers/response_capture.d.ts +4 -1
- package/dist/providers/response_capture.js +81 -2
- package/dist/providers/subscription_limits.d.ts +20 -2
- package/dist/providers/subscription_limits.js +115 -13
- package/dist/runtime/explicit_model.js +9 -4
- package/dist/runtime/prepare_routed_completion.d.ts +3 -1
- package/dist/runtime/prepare_routed_completion.js +7 -2
- package/dist/runtime/role_model.d.ts +8 -0
- package/dist/runtime/role_model.js +27 -0
- package/dist/runtime/routed_runtime.js +3 -1
- package/dist/self_host/config.d.ts +9 -1
- package/dist/self_host/config.js +44 -1
- package/dist/self_host/platform.js +7 -2
- package/dist/self_host/resolve.js +18 -3
- package/dist/self_host/subscription_test_gateway.d.ts +4 -3
- package/dist/self_host/subscription_test_gateway.js +11 -8
- package/dist/self_host/subscriptions/access.d.ts +5 -0
- package/dist/self_host/subscriptions/access.js +5 -1
- package/dist/self_host/subscriptions/http.js +16 -2
- package/dist/self_host/subscriptions/index.d.ts +6 -2
- package/dist/self_host/subscriptions/index.js +6 -2
- package/dist/self_host/subscriptions/oauth.d.ts +8 -4
- package/dist/self_host/subscriptions/oauth.js +75 -0
- package/dist/self_host/subscriptions/store.d.ts +17 -2
- package/dist/self_host/subscriptions/store.js +53 -8
- package/dist/self_host/subscriptions/usage.d.ts +7 -0
- package/dist/self_host/subscriptions/usage.js +52 -0
- package/dist/strategies/route_decision.js +0 -5
- package/dist/types.d.ts +6 -1
- package/package.json +2 -2
- package/src/context/provider_prompt_accounting.ts +7 -0
- package/src/context/routing_context.ts +4 -1
- package/src/interaction/system_prompt.ts +26 -0
- package/src/models/canonical.ts +5 -0
- package/src/models/catalog.ts +1 -0
- package/src/models/provider_defaults.ts +4 -0
- package/src/models/subscriptions.ts +14 -14
- package/src/platform/platform.ts +3 -0
- package/src/providers/codex_usage.ts +59 -2
- package/src/providers/execution.ts +65 -8
- package/src/providers/key_check.ts +2 -0
- package/src/providers/pi.ts +5 -0
- package/src/providers/pi_options.ts +7 -0
- package/src/providers/provider_call.ts +12 -3
- package/src/providers/response_capture.ts +88 -2
- package/src/providers/subscription_limits.ts +131 -14
- package/src/runtime/explicit_model.ts +9 -4
- package/src/runtime/prepare_routed_completion.ts +13 -3
- package/src/runtime/role_model.ts +35 -0
- package/src/runtime/routed_runtime.ts +3 -1
- package/src/self_host/config.ts +55 -2
- package/src/self_host/platform.ts +6 -3
- package/src/self_host/resolve.ts +15 -2
- package/src/self_host/subscription_test_gateway.ts +14 -8
- package/src/self_host/subscriptions/access.ts +10 -1
- package/src/self_host/subscriptions/http.ts +23 -2
- package/src/self_host/subscriptions/index.ts +7 -1
- package/src/self_host/subscriptions/oauth.ts +104 -5
- package/src/self_host/subscriptions/store.ts +65 -9
- package/src/self_host/subscriptions/usage.ts +64 -0
- package/src/strategies/route_decision.ts +0 -9
- package/src/types.ts +13 -1
|
@@ -13,7 +13,15 @@ import {
|
|
|
13
13
|
type OAuthFetch,
|
|
14
14
|
type SubscriptionProvider,
|
|
15
15
|
} from "./oauth.js";
|
|
16
|
-
import {
|
|
16
|
+
import { canonicalModelName } from "../../models/canonical.js";
|
|
17
|
+
import {
|
|
18
|
+
activeModelHolds,
|
|
19
|
+
currentUsage,
|
|
20
|
+
isHeld,
|
|
21
|
+
type SubscriptionCredential,
|
|
22
|
+
type SubscriptionStore,
|
|
23
|
+
} from "./store.js";
|
|
24
|
+
import { refreshStaleUsage } from "./usage.js";
|
|
17
25
|
|
|
18
26
|
export type SubscriptionHttpDeps = {
|
|
19
27
|
store: SubscriptionStore;
|
|
@@ -42,7 +50,13 @@ export async function handleSubscriptionRequest(
|
|
|
42
50
|
const path = url.pathname.slice(BASE.length);
|
|
43
51
|
const now = deps.now?.() ?? new Date();
|
|
44
52
|
try {
|
|
45
|
-
if (path === "" && request.method === "GET")
|
|
53
|
+
if (path === "" && request.method === "GET") {
|
|
54
|
+
// OpenCode Go reports usage only when asked.
|
|
55
|
+
if (url.searchParams.get("refresh_usage") === "true") {
|
|
56
|
+
await refreshStaleUsage(deps.store, { fetch: deps.fetch, now });
|
|
57
|
+
}
|
|
58
|
+
return json(200, listBody(deps.store, now));
|
|
59
|
+
}
|
|
46
60
|
if (path === "/oauth/sessions" && request.method === "POST") {
|
|
47
61
|
return json(201, await startSession(deps, await readBody(request), now));
|
|
48
62
|
}
|
|
@@ -188,6 +202,13 @@ function credentialBody(credential: SubscriptionCredential, active: boolean, now
|
|
|
188
202
|
last_used_at: credential.lastUsedAt?.toISOString() ?? null,
|
|
189
203
|
unavailable_until: held ? credential.unavailableUntil!.toISOString() : null,
|
|
190
204
|
unavailable_reason: held ? credential.unavailableReason : null,
|
|
205
|
+
// Models at their own usage limit; the plan still serves the others.
|
|
206
|
+
model_holds: activeModelHolds(credential, now).map((hold) => ({
|
|
207
|
+
model: hold.model,
|
|
208
|
+
display_name: canonicalModelName(hold.model),
|
|
209
|
+
unavailable_until: hold.until.toISOString(),
|
|
210
|
+
reason: hold.reason,
|
|
211
|
+
})),
|
|
191
212
|
subscription_active: active,
|
|
192
213
|
// The share of its tightest window the plan last reported used, while
|
|
193
214
|
// that window has not reset; null when it reports none.
|
|
@@ -9,6 +9,9 @@
|
|
|
9
9
|
* database file; protect that file like a secret.
|
|
10
10
|
* - `access.ts`: `freshAccessToken` refreshes a token expiring within five
|
|
11
11
|
* minutes before handing it out, one refresh per credential at a time.
|
|
12
|
+
* - `usage.ts`: `refreshStaleUsage` reads OpenCode Go plan usage from its
|
|
13
|
+
* usage endpoint, which its responses never report, when the accounts view
|
|
14
|
+
* asks.
|
|
12
15
|
* - `http.ts`: `handleSubscriptionRequest` serves the credential endpoints the
|
|
13
16
|
* Dari CLI uses to connect, list, rename, release, and disconnect
|
|
14
17
|
* subscriptions. The caller authenticates the request first.
|
|
@@ -17,7 +20,8 @@
|
|
|
17
20
|
* `store.ts` for how usage, resets, and conversations decide it. Successful
|
|
18
21
|
* responses report usage through `store.recordUsage`. When a provider reports a usage limit,
|
|
19
22
|
* `store.markUnavailable` holds that subscription until its reset and says
|
|
20
|
-
* whether another one can serve the retry
|
|
23
|
+
* whether another one can serve the retry; a limit on one model only
|
|
24
|
+
* (`store.holdModel`) holds that model, and routing serves the others.
|
|
21
25
|
*/
|
|
22
26
|
export { freshAccessToken } from "./access.js";
|
|
23
27
|
export { handleSubscriptionRequest, type SubscriptionHttpDeps } from "./http.js";
|
|
@@ -38,7 +42,9 @@ export {
|
|
|
38
42
|
} from "./oauth.js";
|
|
39
43
|
export {
|
|
40
44
|
SubscriptionStore,
|
|
45
|
+
activeModelHolds,
|
|
41
46
|
isHeld,
|
|
42
47
|
type PendingOAuthSession,
|
|
43
48
|
type SubscriptionCredential,
|
|
49
|
+
type SubscriptionModelHold,
|
|
44
50
|
} from "./store.js";
|
|
@@ -3,19 +3,29 @@ import { createHash, randomBytes } from "node:crypto";
|
|
|
3
3
|
/**
|
|
4
4
|
* OAuth protocols for personal subscriptions: Claude Code (PKCE, the user
|
|
5
5
|
* pastes back the `code#state` Anthropic shows), ChatGPT/Codex (device code,
|
|
6
|
-
* the gateway polls for approval),
|
|
7
|
-
* subscription's Model API key minted from the sign-in token)
|
|
8
|
-
*
|
|
6
|
+
* the gateway polls for approval), Muse Code (Meta's device code, then the
|
|
7
|
+
* subscription's Model API key minted from the sign-in token), and OpenCode Go
|
|
8
|
+
* (the OpenCode Console device sign-in `opencode auth login` runs, scoped to
|
|
9
|
+
* the workspace that holds the plan).
|
|
10
|
+
* Every network call goes through the injected `fetch`.
|
|
9
11
|
*/
|
|
10
12
|
|
|
11
|
-
export type SubscriptionProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse";
|
|
13
|
+
export type SubscriptionProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse" | "opencode_go";
|
|
12
14
|
|
|
13
15
|
export const SUBSCRIPTION_PROVIDERS: readonly SubscriptionProvider[] = [
|
|
14
16
|
"anthropic_claude_code",
|
|
15
17
|
"openai_codex",
|
|
16
18
|
"meta_muse",
|
|
19
|
+
"opencode_go",
|
|
17
20
|
];
|
|
18
21
|
|
|
22
|
+
const OPENCODE_CONSOLE_URL = "https://opencode.ai/console";
|
|
23
|
+
export const OPENCODE_CLIENT_ID = "opencode-cli";
|
|
24
|
+
const OPENCODE_TOKEN_URL = `${OPENCODE_CONSOLE_URL}/auth/device/token`;
|
|
25
|
+
|
|
26
|
+
export const OPENCODE_APPROVAL_PENDING =
|
|
27
|
+
"OpenCode approval is still pending. Enter the code in the OpenCode console, finish approval, then try again.";
|
|
28
|
+
|
|
19
29
|
export type OAuthFetch = (url: string, init: RequestInit) => Promise<Response>;
|
|
20
30
|
|
|
21
31
|
export type OAuthOptions = { fetch: OAuthFetch; now?: Date };
|
|
@@ -103,6 +113,21 @@ export async function startOAuth(
|
|
|
103
113
|
options: OAuthOptions,
|
|
104
114
|
): Promise<OAuthAuthorization> {
|
|
105
115
|
const expiresAt = new Date((options.now ?? new Date()).getTime() + FLOW_TIMEOUT_MS);
|
|
116
|
+
if (provider === "opencode_go") {
|
|
117
|
+
const device = await postJson(
|
|
118
|
+
options.fetch,
|
|
119
|
+
`${OPENCODE_CONSOLE_URL}/auth/device/code`,
|
|
120
|
+
{ client_id: OPENCODE_CLIENT_ID, supports_org_scope: true },
|
|
121
|
+
"OpenCode device code request",
|
|
122
|
+
);
|
|
123
|
+
const verification = requiredString(device, "verification_uri_complete");
|
|
124
|
+
return {
|
|
125
|
+
authorizationUrl: verification.startsWith("/") ? `https://opencode.ai${verification}` : verification,
|
|
126
|
+
expiresAt,
|
|
127
|
+
userCode: requiredString(device, "user_code"),
|
|
128
|
+
flow: { device_code: requiredString(device, "device_code") },
|
|
129
|
+
};
|
|
130
|
+
}
|
|
106
131
|
if (provider === "anthropic_claude_code") {
|
|
107
132
|
const verifier = randomUrlSafe(32);
|
|
108
133
|
const challenge = base64Url(createHash("sha256").update(verifier).digest());
|
|
@@ -168,6 +193,35 @@ export async function completeOAuth(
|
|
|
168
193
|
options: OAuthOptions,
|
|
169
194
|
): Promise<OAuthTokens> {
|
|
170
195
|
const now = options.now ?? new Date();
|
|
196
|
+
if (provider === "opencode_go") {
|
|
197
|
+
let token: Record<string, unknown>;
|
|
198
|
+
try {
|
|
199
|
+
token = await postJson(
|
|
200
|
+
options.fetch,
|
|
201
|
+
OPENCODE_TOKEN_URL,
|
|
202
|
+
{
|
|
203
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
204
|
+
device_code: requiredString(flow, "device_code"),
|
|
205
|
+
client_id: OPENCODE_CLIENT_ID,
|
|
206
|
+
},
|
|
207
|
+
"OpenCode device approval check",
|
|
208
|
+
);
|
|
209
|
+
} catch (error) {
|
|
210
|
+
if (error instanceof SubscriptionOAuthProviderError) {
|
|
211
|
+
if (error.errorCode === "authorization_pending" || error.errorCode === "slow_down") {
|
|
212
|
+
throw new SubscriptionOAuthInputError(OPENCODE_APPROVAL_PENDING);
|
|
213
|
+
}
|
|
214
|
+
if (error.errorCode === "access_denied") {
|
|
215
|
+
throw new SubscriptionOAuthInputError("The sign-in was declined on OpenCode. Start again to retry.");
|
|
216
|
+
}
|
|
217
|
+
if (error.errorCode === "expired_token") {
|
|
218
|
+
throw new SubscriptionOAuthInputError("The OpenCode sign-in code expired. Start again.");
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
throw error;
|
|
222
|
+
}
|
|
223
|
+
return await opencodeGoTokens(token, null, options.fetch, now);
|
|
224
|
+
}
|
|
171
225
|
if (provider === "anthropic_claude_code") {
|
|
172
226
|
const verifier = requiredString(flow, "code_verifier");
|
|
173
227
|
const expectedState = requiredString(flow, "state");
|
|
@@ -261,6 +315,15 @@ export async function refreshOAuth(
|
|
|
261
315
|
options: OAuthOptions,
|
|
262
316
|
): Promise<OAuthTokens> {
|
|
263
317
|
const now = options.now ?? new Date();
|
|
318
|
+
if (credential.provider === "opencode_go") {
|
|
319
|
+
const token = await postJson(
|
|
320
|
+
options.fetch,
|
|
321
|
+
OPENCODE_TOKEN_URL,
|
|
322
|
+
{ grant_type: "refresh_token", refresh_token: credential.refreshToken, client_id: OPENCODE_CLIENT_ID },
|
|
323
|
+
"OpenCode sign-in refresh",
|
|
324
|
+
);
|
|
325
|
+
return await opencodeGoTokens(token, credential.accountId, options.fetch, now);
|
|
326
|
+
}
|
|
264
327
|
if (credential.provider === "anthropic_claude_code") {
|
|
265
328
|
const token = await postJson(
|
|
266
329
|
options.fetch,
|
|
@@ -459,7 +522,7 @@ function jwtPayload(token: string): Record<string, unknown> | null {
|
|
|
459
522
|
function postJson(
|
|
460
523
|
fetch: OAuthFetch,
|
|
461
524
|
url: string,
|
|
462
|
-
payload: Record<string, string>,
|
|
525
|
+
payload: Record<string, string | boolean>,
|
|
463
526
|
operation: string,
|
|
464
527
|
): Promise<Record<string, unknown>> {
|
|
465
528
|
return requestJson(fetch, url, JSON.stringify(payload), "application/json", operation);
|
|
@@ -524,3 +587,39 @@ function base64Url(value: Buffer): string {
|
|
|
524
587
|
function isRecord(value: unknown): value is Record<string, unknown> {
|
|
525
588
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
526
589
|
}
|
|
590
|
+
|
|
591
|
+
// A Console token is scoped to the workspace the sign-in chose, which holds
|
|
592
|
+
// the Go plan; a refresh that omits it keeps the stored one.
|
|
593
|
+
async function opencodeGoTokens(
|
|
594
|
+
token: Record<string, unknown>,
|
|
595
|
+
workspace: string | null,
|
|
596
|
+
fetch: OAuthFetch,
|
|
597
|
+
now: Date,
|
|
598
|
+
): Promise<OAuthTokens> {
|
|
599
|
+
const accessToken = requiredString(token, "access_token");
|
|
600
|
+
const orgId = typeof token.org_id === "string" && token.org_id ? token.org_id : workspace;
|
|
601
|
+
return {
|
|
602
|
+
provider: "opencode_go",
|
|
603
|
+
accessToken,
|
|
604
|
+
refreshToken: requiredString(token, "refresh_token"),
|
|
605
|
+
expiresAt: new Date(now.getTime() + positiveInt(token.expires_in) * 1000),
|
|
606
|
+
accountId: orgId,
|
|
607
|
+
accountEmail: await opencodeEmail(fetch, accessToken),
|
|
608
|
+
};
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
// The signed-in member's email, shown with the subscription; best effort.
|
|
612
|
+
async function opencodeEmail(fetch: OAuthFetch, accessToken: string): Promise<string | null> {
|
|
613
|
+
try {
|
|
614
|
+
const response = await fetch(`${OPENCODE_CONSOLE_URL}/api/user`, {
|
|
615
|
+
method: "GET",
|
|
616
|
+
headers: { Accept: "application/json", Authorization: `Bearer ${accessToken}`, "User-Agent": "Dari/1.0" },
|
|
617
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
618
|
+
});
|
|
619
|
+
if (!response.ok) return null;
|
|
620
|
+
const user: unknown = await response.json();
|
|
621
|
+
return isRecord(user) && typeof user.email === "string" && user.email ? user.email : null;
|
|
622
|
+
} catch {
|
|
623
|
+
return null;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
@@ -19,7 +19,8 @@
|
|
|
19
19
|
* used last.
|
|
20
20
|
* - When every subscription is past the threshold, the least used serves.
|
|
21
21
|
* A hold ends on its own once `unavailable_until` passes; reported usage
|
|
22
|
-
* stops counting once its window resets.
|
|
22
|
+
* stops counting once its window resets. A model hold (one model at its own
|
|
23
|
+
* limit) leaves the subscription serving its other models.
|
|
23
24
|
*/
|
|
24
25
|
import type { Database } from "bun:sqlite";
|
|
25
26
|
import { randomBytes, randomUUID } from "node:crypto";
|
|
@@ -48,6 +49,8 @@ export type SubscriptionCredential = {
|
|
|
48
49
|
expiresAt: Date;
|
|
49
50
|
unavailableUntil: Date | null;
|
|
50
51
|
unavailableReason: string | null;
|
|
52
|
+
// Models at their own usage limit on this plan, including expired holds.
|
|
53
|
+
modelHolds: SubscriptionModelHold[];
|
|
51
54
|
// The last usage a response reported, and when.
|
|
52
55
|
usage: (SubscriptionUsage & { observedAt: Date }) | null;
|
|
53
56
|
position: number;
|
|
@@ -56,6 +59,12 @@ export type SubscriptionCredential = {
|
|
|
56
59
|
lastUsedAt: Date | null;
|
|
57
60
|
};
|
|
58
61
|
|
|
62
|
+
export type SubscriptionModelHold = {
|
|
63
|
+
model: string;
|
|
64
|
+
until: Date;
|
|
65
|
+
reason: string;
|
|
66
|
+
};
|
|
67
|
+
|
|
59
68
|
export type PendingOAuthSession = {
|
|
60
69
|
token: string;
|
|
61
70
|
provider: SubscriptionProvider;
|
|
@@ -69,6 +78,7 @@ const BASE_NAMES: Record<SubscriptionProvider, string> = {
|
|
|
69
78
|
anthropic_claude_code: "ANTHROPIC_CLAUDE_CODE_OAUTH_TOKEN",
|
|
70
79
|
openai_codex: "OPENAI_CODEX_OAUTH_TOKEN",
|
|
71
80
|
meta_muse: "META_MUSE_OAUTH_TOKEN",
|
|
81
|
+
opencode_go: "OPENCODE_GO_OAUTH_TOKEN",
|
|
72
82
|
};
|
|
73
83
|
|
|
74
84
|
type CredentialRow = {
|
|
@@ -87,19 +97,21 @@ type CredentialRow = {
|
|
|
87
97
|
usage_resets_at: number | null;
|
|
88
98
|
usage_observed_at: number | null;
|
|
89
99
|
usage_windows: string | null;
|
|
100
|
+
model_holds: string | null;
|
|
90
101
|
position: number;
|
|
91
102
|
created_at: number;
|
|
92
103
|
updated_at: number;
|
|
93
104
|
last_used_at: number | null;
|
|
94
105
|
};
|
|
95
106
|
|
|
96
|
-
//
|
|
97
|
-
//
|
|
98
|
-
const
|
|
107
|
+
// Columns added after the table first shipped; existing databases gain them
|
|
108
|
+
// on open.
|
|
109
|
+
const ADDED_COLUMNS = {
|
|
99
110
|
usage_utilization: "REAL",
|
|
100
111
|
usage_resets_at: "INTEGER",
|
|
101
112
|
usage_observed_at: "INTEGER",
|
|
102
113
|
usage_windows: "TEXT",
|
|
114
|
+
model_holds: "TEXT",
|
|
103
115
|
} as const;
|
|
104
116
|
|
|
105
117
|
type SessionRow = {
|
|
@@ -128,6 +140,7 @@ export class SubscriptionStore {
|
|
|
128
140
|
usage_resets_at INTEGER,
|
|
129
141
|
usage_observed_at INTEGER,
|
|
130
142
|
usage_windows TEXT,
|
|
143
|
+
model_holds TEXT,
|
|
131
144
|
position INTEGER NOT NULL,
|
|
132
145
|
created_at INTEGER NOT NULL,
|
|
133
146
|
updated_at INTEGER NOT NULL,
|
|
@@ -136,7 +149,7 @@ export class SubscriptionStore {
|
|
|
136
149
|
const columns = new Set(
|
|
137
150
|
db.query<{ name: string }, []>("PRAGMA table_info(subscription_credentials)").all().map((column) => column.name),
|
|
138
151
|
);
|
|
139
|
-
for (const [column, type] of Object.entries(
|
|
152
|
+
for (const [column, type] of Object.entries(ADDED_COLUMNS)) {
|
|
140
153
|
if (!columns.has(column)) db.run(`ALTER TABLE subscription_credentials ADD COLUMN ${column} ${type}`);
|
|
141
154
|
}
|
|
142
155
|
db.run(`CREATE TABLE IF NOT EXISTS subscription_conversation_pins (
|
|
@@ -266,14 +279,15 @@ export class SubscriptionStore {
|
|
|
266
279
|
|
|
267
280
|
if (existing !== null) {
|
|
268
281
|
// Another (or an unidentified) account must not inherit the previous
|
|
269
|
-
// account's
|
|
282
|
+
// account's holds, reported usage, or conversations (whose cache is
|
|
270
283
|
// the previous account's).
|
|
271
284
|
const sameAccount = tokens.accountEmail !== null && tokens.accountEmail === existing.accountEmail;
|
|
272
285
|
const usage = sameAccount ? existing.usage : null;
|
|
273
286
|
this.db.run(
|
|
274
287
|
`UPDATE subscription_credentials SET access_token = ?, refresh_token = ?, expires_at = ?,
|
|
275
288
|
account_id = ?, account_email = ?, unavailable_until = ?, unavailable_reason = ?,
|
|
276
|
-
usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, usage_windows = ?,
|
|
289
|
+
usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, usage_windows = ?, model_holds = ?,
|
|
290
|
+
updated_at = ?
|
|
277
291
|
WHERE id = ?`,
|
|
278
292
|
[
|
|
279
293
|
tokens.accessToken,
|
|
@@ -287,6 +301,7 @@ export class SubscriptionStore {
|
|
|
287
301
|
usage?.resetsAt.getTime() ?? null,
|
|
288
302
|
usage?.observedAt.getTime() ?? null,
|
|
289
303
|
usage === null ? null : windowsJson(usage),
|
|
304
|
+
sameAccount ? modelHoldsJson(existing.modelHolds) : null,
|
|
290
305
|
now.getTime(),
|
|
291
306
|
existing.id,
|
|
292
307
|
],
|
|
@@ -378,12 +393,34 @@ export class SubscriptionStore {
|
|
|
378
393
|
return this.activeCredential(credential.provider, now) !== null;
|
|
379
394
|
}
|
|
380
395
|
|
|
381
|
-
/**
|
|
396
|
+
/**
|
|
397
|
+
* Hold one model at its own usage limit on a subscription, which keeps
|
|
398
|
+
* serving its other models. A hold only grows, like the plan's. Returns
|
|
399
|
+
* whether the subscription is connected.
|
|
400
|
+
*/
|
|
401
|
+
holdModel(id: string, model: string, until: Date, reason: string, now = new Date()): boolean {
|
|
402
|
+
const credential = this.get(id);
|
|
403
|
+
if (credential === null) return false;
|
|
404
|
+
const current = activeModelHolds(credential, now);
|
|
405
|
+
const existing = current.find((hold) => hold.model === model);
|
|
406
|
+
if (existing === undefined || until > existing.until) {
|
|
407
|
+
const holds = [...current.filter((hold) => hold.model !== model), { model, until, reason }];
|
|
408
|
+
this.db.run("UPDATE subscription_credentials SET model_holds = ?, updated_at = ? WHERE id = ?", [
|
|
409
|
+
modelHoldsJson(holds),
|
|
410
|
+
now.getTime(),
|
|
411
|
+
id,
|
|
412
|
+
]);
|
|
413
|
+
}
|
|
414
|
+
return true;
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
/** Clear a subscription's usage-limit holds. Null when it is not connected. */
|
|
382
418
|
markAvailable(name: string, now = new Date()): SubscriptionCredential | null {
|
|
383
419
|
const credential = this.getByName(name);
|
|
384
420
|
if (credential === null) return null;
|
|
385
421
|
this.db.run(
|
|
386
|
-
|
|
422
|
+
`UPDATE subscription_credentials SET unavailable_until = NULL, unavailable_reason = NULL, model_holds = NULL,
|
|
423
|
+
updated_at = ? WHERE id = ?`,
|
|
387
424
|
[now.getTime(), credential.id],
|
|
388
425
|
);
|
|
389
426
|
return this.get(credential.id);
|
|
@@ -432,6 +469,13 @@ export function isHeld(credential: SubscriptionCredential, now: Date): boolean {
|
|
|
432
469
|
return credential.unavailableUntil !== null && credential.unavailableUntil > now;
|
|
433
470
|
}
|
|
434
471
|
|
|
472
|
+
/** The models held at their own limit on a subscription now, by model. */
|
|
473
|
+
export function activeModelHolds(credential: SubscriptionCredential, now: Date): SubscriptionModelHold[] {
|
|
474
|
+
return credential.modelHolds
|
|
475
|
+
.filter((hold) => hold.until > now)
|
|
476
|
+
.sort((a, b) => a.model.localeCompare(b.model));
|
|
477
|
+
}
|
|
478
|
+
|
|
435
479
|
/** The usage a subscription last reported, while its window has not reset. */
|
|
436
480
|
/**
|
|
437
481
|
* The last reported usage of every window that has not reset. A short window
|
|
@@ -512,6 +556,7 @@ function credentialFromRow(row: CredentialRow): SubscriptionCredential {
|
|
|
512
556
|
observedAt: new Date(row.usage_observed_at),
|
|
513
557
|
windows: parseWindows(row.usage_windows),
|
|
514
558
|
},
|
|
559
|
+
modelHolds: parseModelHolds(row.model_holds),
|
|
515
560
|
position: row.position,
|
|
516
561
|
createdAt: new Date(row.created_at),
|
|
517
562
|
updatedAt: new Date(row.updated_at),
|
|
@@ -523,6 +568,17 @@ function windowsJson(usage: SubscriptionUsage): string {
|
|
|
523
568
|
return JSON.stringify(usage.windows.map((window) => ({ ...window, resetsAt: window.resetsAt.getTime() })));
|
|
524
569
|
}
|
|
525
570
|
|
|
571
|
+
function modelHoldsJson(holds: SubscriptionModelHold[]): string | null {
|
|
572
|
+
if (holds.length === 0) return null;
|
|
573
|
+
return JSON.stringify(holds.map((hold) => ({ ...hold, until: hold.until.getTime() })));
|
|
574
|
+
}
|
|
575
|
+
|
|
576
|
+
function parseModelHolds(value: string | null): SubscriptionModelHold[] {
|
|
577
|
+
if (value === null) return [];
|
|
578
|
+
return (JSON.parse(value) as Array<{ model: string; until: number; reason: string }>)
|
|
579
|
+
.map((hold) => ({ ...hold, until: new Date(hold.until) }));
|
|
580
|
+
}
|
|
581
|
+
|
|
526
582
|
// Rows recorded before windows were stored have none.
|
|
527
583
|
function parseWindows(value: string | null): SubscriptionUsage["windows"] {
|
|
528
584
|
if (value === null) return [];
|
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { openCodeGoUsageFromReport } from "../../providers/subscription_limits.js";
|
|
2
|
+
import { refreshedAccessToken } from "./access.js";
|
|
3
|
+
import type { OAuthFetch } from "./oauth.js";
|
|
4
|
+
import type { SubscriptionCredential, SubscriptionStore } from "./store.js";
|
|
5
|
+
|
|
6
|
+
/**
|
|
7
|
+
* Claude Code, ChatGPT, and Muse Code report usage on the responses the
|
|
8
|
+
* gateway serves. OpenCode Go does not: it reports it from a usage endpoint
|
|
9
|
+
* that takes the plan's workspace, which the accounts view reads again when
|
|
10
|
+
* the last reading is stale.
|
|
11
|
+
*/
|
|
12
|
+
// A read, failed or not, is not repeated within this interval.
|
|
13
|
+
const READ_INTERVAL_MS = 60_000;
|
|
14
|
+
const READ_TIMEOUT_MS = 8_000;
|
|
15
|
+
const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
|
|
16
|
+
|
|
17
|
+
// Reads that recorded nothing (failed, or no running window), so such a plan is
|
|
18
|
+
// not re-read on every listing. A recorded reading stamps the credential
|
|
19
|
+
// itself, which a reconnect clears.
|
|
20
|
+
const unrecordedAt = new Map<string, number>();
|
|
21
|
+
|
|
22
|
+
/** Read every stale OpenCode Go plan again; a failed read keeps the last one. */
|
|
23
|
+
export async function refreshStaleUsage(
|
|
24
|
+
store: SubscriptionStore,
|
|
25
|
+
options: { fetch: OAuthFetch; now?: Date },
|
|
26
|
+
): Promise<void> {
|
|
27
|
+
const now = options.now ?? new Date();
|
|
28
|
+
const due = (at: number | undefined) => now.getTime() - (at ?? 0) >= READ_INTERVAL_MS;
|
|
29
|
+
const stale = store.list("opencode_go").filter((credential) =>
|
|
30
|
+
due(credential.usage?.observedAt.getTime()) && due(unrecordedAt.get(credential.id))
|
|
31
|
+
);
|
|
32
|
+
await Promise.all(stale.map(async (credential) => {
|
|
33
|
+
unrecordedAt.set(credential.id, now.getTime());
|
|
34
|
+
try {
|
|
35
|
+
await readUsage(store, credential, { ...options, now });
|
|
36
|
+
} catch (error) {
|
|
37
|
+
console.error(`subscription usage read failed for ${credential.name}:`, error instanceof Error ? error.message : error);
|
|
38
|
+
}
|
|
39
|
+
}));
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
async function readUsage(
|
|
43
|
+
store: SubscriptionStore,
|
|
44
|
+
credential: SubscriptionCredential,
|
|
45
|
+
options: { fetch: OAuthFetch; now: Date },
|
|
46
|
+
): Promise<void> {
|
|
47
|
+
const token = await refreshedAccessToken(store, credential, options);
|
|
48
|
+
const response = await options.fetch(OPENCODE_GO_USAGE_URL, {
|
|
49
|
+
method: "GET",
|
|
50
|
+
headers: {
|
|
51
|
+
Accept: "application/json",
|
|
52
|
+
Authorization: `Bearer ${token}`,
|
|
53
|
+
"User-Agent": "dari-gateway",
|
|
54
|
+
...(credential.accountId === null ? {} : { "x-opencode-org-id": credential.accountId }),
|
|
55
|
+
},
|
|
56
|
+
signal: AbortSignal.timeout(READ_TIMEOUT_MS),
|
|
57
|
+
});
|
|
58
|
+
// Go answers 403 for a workspace without a Go plan.
|
|
59
|
+
if (!response.ok) throw new Error(`OpenCode Go usage read failed with status ${response.status}.`);
|
|
60
|
+
const usage = openCodeGoUsageFromReport(await response.json(), options.now);
|
|
61
|
+
if (usage === null) return;
|
|
62
|
+
unrecordedAt.delete(credential.id);
|
|
63
|
+
store.recordUsage(credential.id, usage, options.now);
|
|
64
|
+
}
|
|
@@ -44,15 +44,6 @@ export async function routeDecision(
|
|
|
44
44
|
"custom_config_missing",
|
|
45
45
|
);
|
|
46
46
|
}
|
|
47
|
-
if (custom && resolution.candidates.length === 0) {
|
|
48
|
-
const error = new HttpError(
|
|
49
|
-
502,
|
|
50
|
-
"No custom routing rule or default model/thinking-level pair is routable for this request.",
|
|
51
|
-
"custom_no_routable_candidates",
|
|
52
|
-
) as HttpError & { decisionDetails?: Record<string, unknown> };
|
|
53
|
-
error.decisionDetails = { custom_rules: custom.audit };
|
|
54
|
-
throw error;
|
|
55
|
-
}
|
|
56
47
|
|
|
57
48
|
const relevance = args.selectorBackend.evalRelevance !== undefined
|
|
58
49
|
&& resolution.candidates.length > 1
|
package/src/types.ts
CHANGED
|
@@ -51,7 +51,8 @@ export type ResolvedProviderAuth = BearerProviderAuth | AwsSigV4ProviderAuth;
|
|
|
51
51
|
// `claude setup-token` prints. It serves Claude Code clients only.
|
|
52
52
|
// - "meta_muse": a Meta (Muse) sign-in; the token is the Model API key the
|
|
53
53
|
// sign-in mints (Pi's Meta OAuth `access`).
|
|
54
|
-
|
|
54
|
+
// - "opencode_go": an OpenCode Go plan; the token is the plan's API key.
|
|
55
|
+
export type SubscriptionKind = "openai_codex" | "anthropic_claude_code" | "meta_muse" | "opencode_go";
|
|
55
56
|
|
|
56
57
|
// A bearer credential an embedding platform supplies for one request through
|
|
57
58
|
// GatewayPlatform.resolveProviderCredential, optionally with its own endpoint.
|
|
@@ -119,6 +120,11 @@ export type ResolvedRouterModelConfig = {
|
|
|
119
120
|
zdr?: boolean;
|
|
120
121
|
};
|
|
121
122
|
|
|
123
|
+
// Subagents include workflow agents. Background requests have no role.
|
|
124
|
+
export type RouterRole = "main" | "subagent";
|
|
125
|
+
export type RouterRoleModels = Partial<Record<RouterRole, string | null>>;
|
|
126
|
+
export type RouterRolePrompts = Partial<Record<RouterRole, string | null>>;
|
|
127
|
+
|
|
122
128
|
export type ResolvedRouter = {
|
|
123
129
|
router_id: string;
|
|
124
130
|
organization_id: string;
|
|
@@ -173,6 +179,12 @@ export type ResolvedRouter = {
|
|
|
173
179
|
prefix_hits?: RouterPrefixHit[];
|
|
174
180
|
routing_strategy?: RoutingStrategy;
|
|
175
181
|
custom_config?: CustomRouterConfig | null;
|
|
182
|
+
// Fixed models for agent roles; a role with a model is served it without
|
|
183
|
+
// routing, whatever model the client asked for.
|
|
184
|
+
role_models?: RouterRoleModels;
|
|
185
|
+
// Text appended to the end of the system prompt of each request from a
|
|
186
|
+
// role, routed or fixed.
|
|
187
|
+
role_prompts?: RouterRolePrompts;
|
|
176
188
|
model_thinking_levels?: Record<string, ReasoningEffort[]>;
|
|
177
189
|
fast_models?: string[];
|
|
178
190
|
model_prices?: Record<string, RouterModelPrice>;
|