@mupt-ai/dari-gateway 1.0.310 → 1.0.311
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/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 +55 -6
- 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 +4 -2
- package/dist/providers/subscription_limits.d.ts +5 -2
- package/dist/providers/subscription_limits.js +70 -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/http.js +9 -1
- package/dist/self_host/subscriptions/index.d.ts +3 -2
- package/dist/self_host/subscriptions/index.js +3 -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/strategies/route_decision.js +0 -5
- package/dist/types.d.ts +6 -1
- package/package.json +2 -2
- 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 +58 -6
- 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 +7 -2
- package/src/providers/subscription_limits.ts +78 -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/http.ts +15 -1
- package/src/self_host/subscriptions/index.ts +4 -1
- package/src/self_host/subscriptions/oauth.ts +104 -5
- package/src/self_host/subscriptions/store.ts +65 -9
- package/src/strategies/route_decision.ts +0 -9
- package/src/types.ts +13 -1
|
@@ -44,9 +44,12 @@ export function createSelfHostedPlatform(deps: Omit<SelfHostedResolverDeps, "pre
|
|
|
44
44
|
apiKey: await freshAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
|
|
45
45
|
};
|
|
46
46
|
},
|
|
47
|
-
markSubscriptionUnavailable
|
|
48
|
-
|
|
49
|
-
|
|
47
|
+
async markSubscriptionUnavailable({ credentialId, limit }) {
|
|
48
|
+
if (credentialId === undefined) return false;
|
|
49
|
+
return limit.model === undefined
|
|
50
|
+
? deps.subscriptions.markUnavailable(credentialId, limit.resetsAt, limit.reason)
|
|
51
|
+
: deps.subscriptions.holdModel(credentialId, limit.model, limit.resetsAt, limit.reason);
|
|
52
|
+
},
|
|
50
53
|
async recordUsage() {
|
|
51
54
|
// Resolution never reports a "managed" key source here.
|
|
52
55
|
throw new Error("The self-hosted gateway has no managed provider keys to account.");
|
package/src/self_host/resolve.ts
CHANGED
|
@@ -20,6 +20,7 @@ import {
|
|
|
20
20
|
} from "./config.js";
|
|
21
21
|
import type { RouterModelStore } from "./router_models.js";
|
|
22
22
|
import {
|
|
23
|
+
activeModelHolds,
|
|
23
24
|
freshAccessToken,
|
|
24
25
|
type OAuthFetch,
|
|
25
26
|
type SubscriptionCredential,
|
|
@@ -109,7 +110,15 @@ export async function resolveSelfHostedRouter(
|
|
|
109
110
|
credentials.set(provider, apiKey ? { key: apiKey, source: "user" } : null);
|
|
110
111
|
}
|
|
111
112
|
|
|
112
|
-
|
|
113
|
+
// A model at its own limit on the serving plan leaves routing until it resets.
|
|
114
|
+
const models = listed.filter((model) => {
|
|
115
|
+
const credential = credentials.get(providerForModel(model.id));
|
|
116
|
+
if (credential == null) return false;
|
|
117
|
+
const plan = credential.subscription;
|
|
118
|
+
if (plan === undefined || !activeModelHolds(plan, now).some((hold) => hold.model === model.id)) return true;
|
|
119
|
+
exhausted.add(plan.provider);
|
|
120
|
+
return false;
|
|
121
|
+
});
|
|
113
122
|
if (models.length === 0) {
|
|
114
123
|
const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
|
|
115
124
|
throw unavailableRouterError(request.routerId, exhausted, missing);
|
|
@@ -132,6 +141,8 @@ export async function resolveSelfHostedRouter(
|
|
|
132
141
|
primary_retries: router.retries,
|
|
133
142
|
routing_strategy: "dari",
|
|
134
143
|
custom_config: null,
|
|
144
|
+
role_models: router.roleModels,
|
|
145
|
+
role_prompts: router.rolePrompts,
|
|
135
146
|
evals: [],
|
|
136
147
|
model_thinking_levels: thinkingLevels(listed),
|
|
137
148
|
model_prices: {},
|
|
@@ -206,6 +217,7 @@ function subscriptionProviderFor(
|
|
|
206
217
|
}
|
|
207
218
|
if (provider === "meta") return clientHarness === "muse_code" ? "meta_muse" : null;
|
|
208
219
|
if (provider === "openai") return "openai_codex";
|
|
220
|
+
if (provider === "opencode-go") return "opencode_go";
|
|
209
221
|
return null;
|
|
210
222
|
}
|
|
211
223
|
|
|
@@ -227,6 +239,7 @@ const SUBSCRIPTION_PLAN_NAMES: Record<SubscriptionProvider, string> = {
|
|
|
227
239
|
anthropic_claude_code: "Claude Code",
|
|
228
240
|
openai_codex: "ChatGPT",
|
|
229
241
|
meta_muse: "Muse Code",
|
|
242
|
+
opencode_go: "OpenCode Go",
|
|
230
243
|
};
|
|
231
244
|
|
|
232
245
|
/**
|
|
@@ -264,7 +277,7 @@ function unavailableRouterError(
|
|
|
264
277
|
.join(" and ");
|
|
265
278
|
return new HttpError(
|
|
266
279
|
424,
|
|
267
|
-
`Every connected ${plans} subscription is at its usage limit, and no API key can serve
|
|
280
|
+
`Every connected ${plans} subscription is at its usage limit for the models router ${routerId} lists, and no API key can serve them instead.${missingNote}`,
|
|
268
281
|
"personal_subscription_unavailable",
|
|
269
282
|
);
|
|
270
283
|
}
|
|
@@ -11,16 +11,21 @@ import { tokens } from "./subscriptions/test_support.js";
|
|
|
11
11
|
* A self-hosted gateway, run through its entrypoint as its own process so no
|
|
12
12
|
* other test file's module mocks reach it, serving two Claude Code plans
|
|
13
13
|
* (access tokens `sk-ant-oat01-a` and `-b`) against a local stand-in for
|
|
14
|
-
* Anthropic. `upstream` answers each provider call given the plan's token
|
|
14
|
+
* Anthropic. `upstream` answers each provider call given the plan's token
|
|
15
|
+
* and the native model it asks for. The router lists `models`.
|
|
15
16
|
*/
|
|
16
|
-
export async function startSubscriptionGateway(
|
|
17
|
+
export async function startSubscriptionGateway(
|
|
18
|
+
upstream: (token: string, model: string) => Response,
|
|
19
|
+
models: string[] = ["anthropic/claude-sonnet-5-5"],
|
|
20
|
+
) {
|
|
17
21
|
const served: string[] = [];
|
|
18
22
|
const provider = Bun.serve({
|
|
19
23
|
port: 0,
|
|
20
|
-
fetch(request) {
|
|
24
|
+
async fetch(request) {
|
|
21
25
|
const token = (request.headers.get("authorization") ?? "").replace(/^Bearer /, "");
|
|
22
26
|
served.push(token);
|
|
23
|
-
|
|
27
|
+
const body = await request.json() as { model?: string };
|
|
28
|
+
return upstream(token, body.model ?? "");
|
|
24
29
|
},
|
|
25
30
|
});
|
|
26
31
|
const dir = mkdtempSync(join(tmpdir(), "dari-gateway-plans-"));
|
|
@@ -34,7 +39,7 @@ export async function startSubscriptionGateway(upstream: (token: string) => Resp
|
|
|
34
39
|
writeFileSync(configPath, `
|
|
35
40
|
routers:
|
|
36
41
|
default:
|
|
37
|
-
models: [
|
|
42
|
+
models: [${models.join(", ")}]
|
|
38
43
|
providers:
|
|
39
44
|
anthropic:
|
|
40
45
|
baseUrl: http://127.0.0.1:${provider.port}
|
|
@@ -60,8 +65,9 @@ providers:
|
|
|
60
65
|
planIds: plans.map((plan) => plan.id),
|
|
61
66
|
// The plans as the gateway stored them.
|
|
62
67
|
plan: (id: string) => new SubscriptionStore(new Database(dbPath)).get(id),
|
|
63
|
-
// One Claude Code request in the conversation `sessionId` starts
|
|
64
|
-
|
|
68
|
+
// One Claude Code request in the conversation `sessionId` starts, for
|
|
69
|
+
// `model` or, by default, routed.
|
|
70
|
+
claudeCode: async (sessionId: string, text: string, model = "dari/model/anthropic/claude-sonnet-5-5") =>
|
|
65
71
|
await fetch(`${baseUrl}/v1/messages`, {
|
|
66
72
|
method: "POST",
|
|
67
73
|
headers: {
|
|
@@ -73,7 +79,7 @@ providers:
|
|
|
73
79
|
"x-claude-code-session-id": sessionId,
|
|
74
80
|
},
|
|
75
81
|
body: JSON.stringify({
|
|
76
|
-
model
|
|
82
|
+
model,
|
|
77
83
|
max_tokens: 64,
|
|
78
84
|
stream: true,
|
|
79
85
|
messages: [{ role: "user", content: text }],
|
|
@@ -13,7 +13,14 @@ 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";
|
|
17
24
|
|
|
18
25
|
export type SubscriptionHttpDeps = {
|
|
19
26
|
store: SubscriptionStore;
|
|
@@ -188,6 +195,13 @@ function credentialBody(credential: SubscriptionCredential, active: boolean, now
|
|
|
188
195
|
last_used_at: credential.lastUsedAt?.toISOString() ?? null,
|
|
189
196
|
unavailable_until: held ? credential.unavailableUntil!.toISOString() : null,
|
|
190
197
|
unavailable_reason: held ? credential.unavailableReason : null,
|
|
198
|
+
// Models at their own usage limit; the plan still serves the others.
|
|
199
|
+
model_holds: activeModelHolds(credential, now).map((hold) => ({
|
|
200
|
+
model: hold.model,
|
|
201
|
+
display_name: canonicalModelName(hold.model),
|
|
202
|
+
unavailable_until: hold.until.toISOString(),
|
|
203
|
+
reason: hold.reason,
|
|
204
|
+
})),
|
|
191
205
|
subscription_active: active,
|
|
192
206
|
// The share of its tightest window the plan last reported used, while
|
|
193
207
|
// that window has not reset; null when it reports none.
|
|
@@ -17,7 +17,8 @@
|
|
|
17
17
|
* `store.ts` for how usage, resets, and conversations decide it. Successful
|
|
18
18
|
* responses report usage through `store.recordUsage`. When a provider reports a usage limit,
|
|
19
19
|
* `store.markUnavailable` holds that subscription until its reset and says
|
|
20
|
-
* whether another one can serve the retry
|
|
20
|
+
* whether another one can serve the retry; a limit on one model only
|
|
21
|
+
* (`store.holdModel`) holds that model, and routing serves the others.
|
|
21
22
|
*/
|
|
22
23
|
export { freshAccessToken } from "./access.js";
|
|
23
24
|
export { handleSubscriptionRequest, type SubscriptionHttpDeps } from "./http.js";
|
|
@@ -38,7 +39,9 @@ export {
|
|
|
38
39
|
} from "./oauth.js";
|
|
39
40
|
export {
|
|
40
41
|
SubscriptionStore,
|
|
42
|
+
activeModelHolds,
|
|
41
43
|
isHeld,
|
|
42
44
|
type PendingOAuthSession,
|
|
43
45
|
type SubscriptionCredential,
|
|
46
|
+
type SubscriptionModelHold,
|
|
44
47
|
} 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 [];
|
|
@@ -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>;
|