@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
|
@@ -9,16 +9,18 @@ import { tokens } from "./subscriptions/test_support.js";
|
|
|
9
9
|
* A self-hosted gateway, run through its entrypoint as its own process so no
|
|
10
10
|
* other test file's module mocks reach it, serving two Claude Code plans
|
|
11
11
|
* (access tokens `sk-ant-oat01-a` and `-b`) against a local stand-in for
|
|
12
|
-
* Anthropic. `upstream` answers each provider call given the plan's token
|
|
12
|
+
* Anthropic. `upstream` answers each provider call given the plan's token
|
|
13
|
+
* and the native model it asks for. The router lists `models`.
|
|
13
14
|
*/
|
|
14
|
-
export async function startSubscriptionGateway(upstream) {
|
|
15
|
+
export async function startSubscriptionGateway(upstream, models = ["anthropic/claude-sonnet-5-5"]) {
|
|
15
16
|
const served = [];
|
|
16
17
|
const provider = Bun.serve({
|
|
17
18
|
port: 0,
|
|
18
|
-
fetch(request) {
|
|
19
|
+
async fetch(request) {
|
|
19
20
|
const token = (request.headers.get("authorization") ?? "").replace(/^Bearer /, "");
|
|
20
21
|
served.push(token);
|
|
21
|
-
|
|
22
|
+
const body = await request.json();
|
|
23
|
+
return upstream(token, body.model ?? "");
|
|
22
24
|
},
|
|
23
25
|
});
|
|
24
26
|
const dir = mkdtempSync(join(tmpdir(), "dari-gateway-plans-"));
|
|
@@ -30,7 +32,7 @@ export async function startSubscriptionGateway(upstream) {
|
|
|
30
32
|
writeFileSync(configPath, `
|
|
31
33
|
routers:
|
|
32
34
|
default:
|
|
33
|
-
models: [
|
|
35
|
+
models: [${models.join(", ")}]
|
|
34
36
|
providers:
|
|
35
37
|
anthropic:
|
|
36
38
|
baseUrl: http://127.0.0.1:${provider.port}
|
|
@@ -55,8 +57,9 @@ providers:
|
|
|
55
57
|
planIds: plans.map((plan) => plan.id),
|
|
56
58
|
// The plans as the gateway stored them.
|
|
57
59
|
plan: (id) => new SubscriptionStore(new Database(dbPath)).get(id),
|
|
58
|
-
// One Claude Code request in the conversation `sessionId` starts
|
|
59
|
-
|
|
60
|
+
// One Claude Code request in the conversation `sessionId` starts, for
|
|
61
|
+
// `model` or, by default, routed.
|
|
62
|
+
claudeCode: async (sessionId, text, model = "dari/model/anthropic/claude-sonnet-5-5") => await fetch(`${baseUrl}/v1/messages`, {
|
|
60
63
|
method: "POST",
|
|
61
64
|
headers: {
|
|
62
65
|
"x-api-key": "k",
|
|
@@ -67,7 +70,7 @@ providers:
|
|
|
67
70
|
"x-claude-code-session-id": sessionId,
|
|
68
71
|
},
|
|
69
72
|
body: JSON.stringify({
|
|
70
|
-
model
|
|
73
|
+
model,
|
|
71
74
|
max_tokens: 64,
|
|
72
75
|
stream: true,
|
|
73
76
|
messages: [{ role: "user", content: text }],
|
|
@@ -8,3 +8,8 @@ export declare function freshAccessToken(store: SubscriptionStore, credential: S
|
|
|
8
8
|
fetch: OAuthFetch;
|
|
9
9
|
now?: Date;
|
|
10
10
|
}): Promise<string>;
|
|
11
|
+
/** A usable access token without recording a use. */
|
|
12
|
+
export declare function refreshedAccessToken(store: SubscriptionStore, credential: SubscriptionCredential, options: {
|
|
13
|
+
fetch: OAuthFetch;
|
|
14
|
+
now?: Date;
|
|
15
|
+
}): Promise<string>;
|
|
@@ -8,8 +8,12 @@ const inFlight = new Map();
|
|
|
8
8
|
* when it expires within five minutes. Records the credential as used.
|
|
9
9
|
*/
|
|
10
10
|
export async function freshAccessToken(store, credential, options) {
|
|
11
|
+
store.touch(credential.id, options.now ?? new Date());
|
|
12
|
+
return await refreshedAccessToken(store, credential, options);
|
|
13
|
+
}
|
|
14
|
+
/** A usable access token without recording a use. */
|
|
15
|
+
export async function refreshedAccessToken(store, credential, options) {
|
|
11
16
|
const now = options.now ?? new Date();
|
|
12
|
-
store.touch(credential.id, now);
|
|
13
17
|
if (!expiresSoon(credential, now))
|
|
14
18
|
return credential.accessToken;
|
|
15
19
|
const pending = inFlight.get(credential.id);
|
|
@@ -5,7 +5,9 @@
|
|
|
5
5
|
* every subscription. Errors are `{"detail": "..."}`, which the CLI prints.
|
|
6
6
|
*/
|
|
7
7
|
import { SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, startOAuth, } from "./oauth.js";
|
|
8
|
-
import {
|
|
8
|
+
import { canonicalModelName } from "../../models/canonical.js";
|
|
9
|
+
import { activeModelHolds, currentUsage, isHeld, } from "./store.js";
|
|
10
|
+
import { refreshStaleUsage } from "./usage.js";
|
|
9
11
|
const BASE = "/v1/organizations/current/credentials";
|
|
10
12
|
// Subscription names are env-var-style, which keeps other credential routes
|
|
11
13
|
// such as `provider-credentials/...` out of these matches.
|
|
@@ -25,8 +27,13 @@ export async function handleSubscriptionRequest(request, deps) {
|
|
|
25
27
|
const path = url.pathname.slice(BASE.length);
|
|
26
28
|
const now = deps.now?.() ?? new Date();
|
|
27
29
|
try {
|
|
28
|
-
if (path === "" && request.method === "GET")
|
|
30
|
+
if (path === "" && request.method === "GET") {
|
|
31
|
+
// OpenCode Go reports usage only when asked.
|
|
32
|
+
if (url.searchParams.get("refresh_usage") === "true") {
|
|
33
|
+
await refreshStaleUsage(deps.store, { fetch: deps.fetch, now });
|
|
34
|
+
}
|
|
29
35
|
return json(200, listBody(deps.store, now));
|
|
36
|
+
}
|
|
30
37
|
if (path === "/oauth/sessions" && request.method === "POST") {
|
|
31
38
|
return json(201, await startSession(deps, await readBody(request), now));
|
|
32
39
|
}
|
|
@@ -171,6 +178,13 @@ function credentialBody(credential, active, now) {
|
|
|
171
178
|
last_used_at: credential.lastUsedAt?.toISOString() ?? null,
|
|
172
179
|
unavailable_until: held ? credential.unavailableUntil.toISOString() : null,
|
|
173
180
|
unavailable_reason: held ? credential.unavailableReason : null,
|
|
181
|
+
// Models at their own usage limit; the plan still serves the others.
|
|
182
|
+
model_holds: activeModelHolds(credential, now).map((hold) => ({
|
|
183
|
+
model: hold.model,
|
|
184
|
+
display_name: canonicalModelName(hold.model),
|
|
185
|
+
unavailable_until: hold.until.toISOString(),
|
|
186
|
+
reason: hold.reason,
|
|
187
|
+
})),
|
|
174
188
|
subscription_active: active,
|
|
175
189
|
// The share of its tightest window the plan last reported used, while
|
|
176
190
|
// 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,9 +20,10 @@
|
|
|
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";
|
|
24
28
|
export { CODEX_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, parseAuthorizationResponse, refreshOAuth, startOAuth, type OAuthAuthorization, type OAuthFetch, type OAuthOptions, type OAuthTokens, type SubscriptionProvider, } from "./oauth.js";
|
|
25
|
-
export { SubscriptionStore, isHeld, type PendingOAuthSession, type SubscriptionCredential, } from "./store.js";
|
|
29
|
+
export { SubscriptionStore, activeModelHolds, isHeld, type PendingOAuthSession, type SubscriptionCredential, type SubscriptionModelHold, } from "./store.js";
|
|
@@ -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,9 +20,10 @@
|
|
|
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 } from "./http.js";
|
|
24
28
|
export { CODEX_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, parseAuthorizationResponse, refreshOAuth, startOAuth, } from "./oauth.js";
|
|
25
|
-
export { SubscriptionStore, isHeld, } from "./store.js";
|
|
29
|
+
export { SubscriptionStore, activeModelHolds, isHeld, } from "./store.js";
|
|
@@ -1,12 +1,16 @@
|
|
|
1
1
|
/**
|
|
2
2
|
* OAuth protocols for personal subscriptions: Claude Code (PKCE, the user
|
|
3
3
|
* pastes back the `code#state` Anthropic shows), ChatGPT/Codex (device code,
|
|
4
|
-
* the gateway polls for approval),
|
|
5
|
-
* subscription's Model API key minted from the sign-in token)
|
|
6
|
-
*
|
|
4
|
+
* the gateway polls for approval), Muse Code (Meta's device code, then the
|
|
5
|
+
* subscription's Model API key minted from the sign-in token), and OpenCode Go
|
|
6
|
+
* (the OpenCode Console device sign-in `opencode auth login` runs, scoped to
|
|
7
|
+
* the workspace that holds the plan).
|
|
8
|
+
* Every network call goes through the injected `fetch`.
|
|
7
9
|
*/
|
|
8
|
-
export type SubscriptionProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse";
|
|
10
|
+
export type SubscriptionProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse" | "opencode_go";
|
|
9
11
|
export declare const SUBSCRIPTION_PROVIDERS: readonly SubscriptionProvider[];
|
|
12
|
+
export declare const OPENCODE_CLIENT_ID = "opencode-cli";
|
|
13
|
+
export declare const OPENCODE_APPROVAL_PENDING = "OpenCode approval is still pending. Enter the code in the OpenCode console, finish approval, then try again.";
|
|
10
14
|
export type OAuthFetch = (url: string, init: RequestInit) => Promise<Response>;
|
|
11
15
|
export type OAuthOptions = {
|
|
12
16
|
fetch: OAuthFetch;
|
|
@@ -3,7 +3,12 @@ export const SUBSCRIPTION_PROVIDERS = [
|
|
|
3
3
|
"anthropic_claude_code",
|
|
4
4
|
"openai_codex",
|
|
5
5
|
"meta_muse",
|
|
6
|
+
"opencode_go",
|
|
6
7
|
];
|
|
8
|
+
const OPENCODE_CONSOLE_URL = "https://opencode.ai/console";
|
|
9
|
+
export const OPENCODE_CLIENT_ID = "opencode-cli";
|
|
10
|
+
const OPENCODE_TOKEN_URL = `${OPENCODE_CONSOLE_URL}/auth/device/token`;
|
|
11
|
+
export const OPENCODE_APPROVAL_PENDING = "OpenCode approval is still pending. Enter the code in the OpenCode console, finish approval, then try again.";
|
|
7
12
|
/** The provider refused or could not be reached (HTTP 502 at the edge). */
|
|
8
13
|
export class SubscriptionOAuthProviderError extends Error {
|
|
9
14
|
status;
|
|
@@ -56,6 +61,16 @@ const MUSE_SIGN_IN_REFRESH_PREFIX = "refresh:";
|
|
|
56
61
|
export const META_APPROVAL_PENDING = "Meta approval is still pending. Enter the code at Meta, finish approval, then try again.";
|
|
57
62
|
export async function startOAuth(provider, options) {
|
|
58
63
|
const expiresAt = new Date((options.now ?? new Date()).getTime() + FLOW_TIMEOUT_MS);
|
|
64
|
+
if (provider === "opencode_go") {
|
|
65
|
+
const device = await postJson(options.fetch, `${OPENCODE_CONSOLE_URL}/auth/device/code`, { client_id: OPENCODE_CLIENT_ID, supports_org_scope: true }, "OpenCode device code request");
|
|
66
|
+
const verification = requiredString(device, "verification_uri_complete");
|
|
67
|
+
return {
|
|
68
|
+
authorizationUrl: verification.startsWith("/") ? `https://opencode.ai${verification}` : verification,
|
|
69
|
+
expiresAt,
|
|
70
|
+
userCode: requiredString(device, "user_code"),
|
|
71
|
+
flow: { device_code: requiredString(device, "device_code") },
|
|
72
|
+
};
|
|
73
|
+
}
|
|
59
74
|
if (provider === "anthropic_claude_code") {
|
|
60
75
|
const verifier = randomUrlSafe(32);
|
|
61
76
|
const challenge = base64Url(createHash("sha256").update(verifier).digest());
|
|
@@ -105,6 +120,31 @@ export async function startOAuth(provider, options) {
|
|
|
105
120
|
*/
|
|
106
121
|
export async function completeOAuth(provider, flow, authorizationResponse, options) {
|
|
107
122
|
const now = options.now ?? new Date();
|
|
123
|
+
if (provider === "opencode_go") {
|
|
124
|
+
let token;
|
|
125
|
+
try {
|
|
126
|
+
token = await postJson(options.fetch, OPENCODE_TOKEN_URL, {
|
|
127
|
+
grant_type: "urn:ietf:params:oauth:grant-type:device_code",
|
|
128
|
+
device_code: requiredString(flow, "device_code"),
|
|
129
|
+
client_id: OPENCODE_CLIENT_ID,
|
|
130
|
+
}, "OpenCode device approval check");
|
|
131
|
+
}
|
|
132
|
+
catch (error) {
|
|
133
|
+
if (error instanceof SubscriptionOAuthProviderError) {
|
|
134
|
+
if (error.errorCode === "authorization_pending" || error.errorCode === "slow_down") {
|
|
135
|
+
throw new SubscriptionOAuthInputError(OPENCODE_APPROVAL_PENDING);
|
|
136
|
+
}
|
|
137
|
+
if (error.errorCode === "access_denied") {
|
|
138
|
+
throw new SubscriptionOAuthInputError("The sign-in was declined on OpenCode. Start again to retry.");
|
|
139
|
+
}
|
|
140
|
+
if (error.errorCode === "expired_token") {
|
|
141
|
+
throw new SubscriptionOAuthInputError("The OpenCode sign-in code expired. Start again.");
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
throw error;
|
|
145
|
+
}
|
|
146
|
+
return await opencodeGoTokens(token, null, options.fetch, now);
|
|
147
|
+
}
|
|
108
148
|
if (provider === "anthropic_claude_code") {
|
|
109
149
|
const verifier = requiredString(flow, "code_verifier");
|
|
110
150
|
const expectedState = requiredString(flow, "state");
|
|
@@ -175,6 +215,10 @@ export async function completeOAuth(provider, flow, authorizationResponse, optio
|
|
|
175
215
|
}
|
|
176
216
|
export async function refreshOAuth(credential, options) {
|
|
177
217
|
const now = options.now ?? new Date();
|
|
218
|
+
if (credential.provider === "opencode_go") {
|
|
219
|
+
const token = await postJson(options.fetch, OPENCODE_TOKEN_URL, { grant_type: "refresh_token", refresh_token: credential.refreshToken, client_id: OPENCODE_CLIENT_ID }, "OpenCode sign-in refresh");
|
|
220
|
+
return await opencodeGoTokens(token, credential.accountId, options.fetch, now);
|
|
221
|
+
}
|
|
178
222
|
if (credential.provider === "anthropic_claude_code") {
|
|
179
223
|
const token = await postJson(options.fetch, CLAUDE_TOKEN_URL, {
|
|
180
224
|
grant_type: "refresh_token",
|
|
@@ -374,3 +418,34 @@ function base64Url(value) {
|
|
|
374
418
|
function isRecord(value) {
|
|
375
419
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
376
420
|
}
|
|
421
|
+
// A Console token is scoped to the workspace the sign-in chose, which holds
|
|
422
|
+
// the Go plan; a refresh that omits it keeps the stored one.
|
|
423
|
+
async function opencodeGoTokens(token, workspace, fetch, now) {
|
|
424
|
+
const accessToken = requiredString(token, "access_token");
|
|
425
|
+
const orgId = typeof token.org_id === "string" && token.org_id ? token.org_id : workspace;
|
|
426
|
+
return {
|
|
427
|
+
provider: "opencode_go",
|
|
428
|
+
accessToken,
|
|
429
|
+
refreshToken: requiredString(token, "refresh_token"),
|
|
430
|
+
expiresAt: new Date(now.getTime() + positiveInt(token.expires_in) * 1000),
|
|
431
|
+
accountId: orgId,
|
|
432
|
+
accountEmail: await opencodeEmail(fetch, accessToken),
|
|
433
|
+
};
|
|
434
|
+
}
|
|
435
|
+
// The signed-in member's email, shown with the subscription; best effort.
|
|
436
|
+
async function opencodeEmail(fetch, accessToken) {
|
|
437
|
+
try {
|
|
438
|
+
const response = await fetch(`${OPENCODE_CONSOLE_URL}/api/user`, {
|
|
439
|
+
method: "GET",
|
|
440
|
+
headers: { Accept: "application/json", Authorization: `Bearer ${accessToken}`, "User-Agent": "Dari/1.0" },
|
|
441
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
442
|
+
});
|
|
443
|
+
if (!response.ok)
|
|
444
|
+
return null;
|
|
445
|
+
const user = await response.json();
|
|
446
|
+
return isRecord(user) && typeof user.email === "string" && user.email ? user.email : null;
|
|
447
|
+
}
|
|
448
|
+
catch {
|
|
449
|
+
return null;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
@@ -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 type { SubscriptionUsage } from "../../providers/subscription_limits.js";
|
|
@@ -37,6 +38,7 @@ export type SubscriptionCredential = {
|
|
|
37
38
|
expiresAt: Date;
|
|
38
39
|
unavailableUntil: Date | null;
|
|
39
40
|
unavailableReason: string | null;
|
|
41
|
+
modelHolds: SubscriptionModelHold[];
|
|
40
42
|
usage: (SubscriptionUsage & {
|
|
41
43
|
observedAt: Date;
|
|
42
44
|
}) | null;
|
|
@@ -45,6 +47,11 @@ export type SubscriptionCredential = {
|
|
|
45
47
|
updatedAt: Date;
|
|
46
48
|
lastUsedAt: Date | null;
|
|
47
49
|
};
|
|
50
|
+
export type SubscriptionModelHold = {
|
|
51
|
+
model: string;
|
|
52
|
+
until: Date;
|
|
53
|
+
reason: string;
|
|
54
|
+
};
|
|
48
55
|
export type PendingOAuthSession = {
|
|
49
56
|
token: string;
|
|
50
57
|
provider: SubscriptionProvider;
|
|
@@ -94,7 +101,13 @@ export declare class SubscriptionStore {
|
|
|
94
101
|
* a subscription for the same provider is available now.
|
|
95
102
|
*/
|
|
96
103
|
markUnavailable(id: string, until: Date, reason: string, now?: Date): boolean;
|
|
97
|
-
/**
|
|
104
|
+
/**
|
|
105
|
+
* Hold one model at its own usage limit on a subscription, which keeps
|
|
106
|
+
* serving its other models. A hold only grows, like the plan's. Returns
|
|
107
|
+
* whether the subscription is connected.
|
|
108
|
+
*/
|
|
109
|
+
holdModel(id: string, model: string, until: Date, reason: string, now?: Date): boolean;
|
|
110
|
+
/** Clear a subscription's usage-limit holds. Null when it is not connected. */
|
|
98
111
|
markAvailable(name: string, now?: Date): SubscriptionCredential | null;
|
|
99
112
|
createSession(session: Omit<PendingOAuthSession, "token">, now?: Date): PendingOAuthSession;
|
|
100
113
|
/** A pending session, including an expired one so callers can say it expired. */
|
|
@@ -103,6 +116,8 @@ export declare class SubscriptionStore {
|
|
|
103
116
|
private freeName;
|
|
104
117
|
}
|
|
105
118
|
export declare function isHeld(credential: SubscriptionCredential, now: Date): boolean;
|
|
119
|
+
/** The models held at their own limit on a subscription now, by model. */
|
|
120
|
+
export declare function activeModelHolds(credential: SubscriptionCredential, now: Date): SubscriptionModelHold[];
|
|
106
121
|
/** The usage a subscription last reported, while its window has not reset. */
|
|
107
122
|
/**
|
|
108
123
|
* The last reported usage of every window that has not reset. A short window
|
|
@@ -8,14 +8,16 @@ const BASE_NAMES = {
|
|
|
8
8
|
anthropic_claude_code: "ANTHROPIC_CLAUDE_CODE_OAUTH_TOKEN",
|
|
9
9
|
openai_codex: "OPENAI_CODEX_OAUTH_TOKEN",
|
|
10
10
|
meta_muse: "META_MUSE_OAUTH_TOKEN",
|
|
11
|
+
opencode_go: "OPENCODE_GO_OAUTH_TOKEN",
|
|
11
12
|
};
|
|
12
|
-
//
|
|
13
|
-
//
|
|
14
|
-
const
|
|
13
|
+
// Columns added after the table first shipped; existing databases gain them
|
|
14
|
+
// on open.
|
|
15
|
+
const ADDED_COLUMNS = {
|
|
15
16
|
usage_utilization: "REAL",
|
|
16
17
|
usage_resets_at: "INTEGER",
|
|
17
18
|
usage_observed_at: "INTEGER",
|
|
18
19
|
usage_windows: "TEXT",
|
|
20
|
+
model_holds: "TEXT",
|
|
19
21
|
};
|
|
20
22
|
export class SubscriptionStore {
|
|
21
23
|
db;
|
|
@@ -37,13 +39,14 @@ export class SubscriptionStore {
|
|
|
37
39
|
usage_resets_at INTEGER,
|
|
38
40
|
usage_observed_at INTEGER,
|
|
39
41
|
usage_windows TEXT,
|
|
42
|
+
model_holds TEXT,
|
|
40
43
|
position INTEGER NOT NULL,
|
|
41
44
|
created_at INTEGER NOT NULL,
|
|
42
45
|
updated_at INTEGER NOT NULL,
|
|
43
46
|
last_used_at INTEGER
|
|
44
47
|
)`);
|
|
45
48
|
const columns = new Set(db.query("PRAGMA table_info(subscription_credentials)").all().map((column) => column.name));
|
|
46
|
-
for (const [column, type] of Object.entries(
|
|
49
|
+
for (const [column, type] of Object.entries(ADDED_COLUMNS)) {
|
|
47
50
|
if (!columns.has(column))
|
|
48
51
|
db.run(`ALTER TABLE subscription_credentials ADD COLUMN ${column} ${type}`);
|
|
49
52
|
}
|
|
@@ -147,13 +150,14 @@ export class SubscriptionStore {
|
|
|
147
150
|
return null;
|
|
148
151
|
if (existing !== null) {
|
|
149
152
|
// Another (or an unidentified) account must not inherit the previous
|
|
150
|
-
// account's
|
|
153
|
+
// account's holds, reported usage, or conversations (whose cache is
|
|
151
154
|
// the previous account's).
|
|
152
155
|
const sameAccount = tokens.accountEmail !== null && tokens.accountEmail === existing.accountEmail;
|
|
153
156
|
const usage = sameAccount ? existing.usage : null;
|
|
154
157
|
this.db.run(`UPDATE subscription_credentials SET access_token = ?, refresh_token = ?, expires_at = ?,
|
|
155
158
|
account_id = ?, account_email = ?, unavailable_until = ?, unavailable_reason = ?,
|
|
156
|
-
usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, usage_windows = ?,
|
|
159
|
+
usage_utilization = ?, usage_resets_at = ?, usage_observed_at = ?, usage_windows = ?, model_holds = ?,
|
|
160
|
+
updated_at = ?
|
|
157
161
|
WHERE id = ?`, [
|
|
158
162
|
tokens.accessToken,
|
|
159
163
|
tokens.refreshToken,
|
|
@@ -166,6 +170,7 @@ export class SubscriptionStore {
|
|
|
166
170
|
usage?.resetsAt.getTime() ?? null,
|
|
167
171
|
usage?.observedAt.getTime() ?? null,
|
|
168
172
|
usage === null ? null : windowsJson(usage),
|
|
173
|
+
sameAccount ? modelHoldsJson(existing.modelHolds) : null,
|
|
169
174
|
now.getTime(),
|
|
170
175
|
existing.id,
|
|
171
176
|
]);
|
|
@@ -243,12 +248,34 @@ export class SubscriptionStore {
|
|
|
243
248
|
}
|
|
244
249
|
return this.activeCredential(credential.provider, now) !== null;
|
|
245
250
|
}
|
|
246
|
-
/**
|
|
251
|
+
/**
|
|
252
|
+
* Hold one model at its own usage limit on a subscription, which keeps
|
|
253
|
+
* serving its other models. A hold only grows, like the plan's. Returns
|
|
254
|
+
* whether the subscription is connected.
|
|
255
|
+
*/
|
|
256
|
+
holdModel(id, model, until, reason, now = new Date()) {
|
|
257
|
+
const credential = this.get(id);
|
|
258
|
+
if (credential === null)
|
|
259
|
+
return false;
|
|
260
|
+
const current = activeModelHolds(credential, now);
|
|
261
|
+
const existing = current.find((hold) => hold.model === model);
|
|
262
|
+
if (existing === undefined || until > existing.until) {
|
|
263
|
+
const holds = [...current.filter((hold) => hold.model !== model), { model, until, reason }];
|
|
264
|
+
this.db.run("UPDATE subscription_credentials SET model_holds = ?, updated_at = ? WHERE id = ?", [
|
|
265
|
+
modelHoldsJson(holds),
|
|
266
|
+
now.getTime(),
|
|
267
|
+
id,
|
|
268
|
+
]);
|
|
269
|
+
}
|
|
270
|
+
return true;
|
|
271
|
+
}
|
|
272
|
+
/** Clear a subscription's usage-limit holds. Null when it is not connected. */
|
|
247
273
|
markAvailable(name, now = new Date()) {
|
|
248
274
|
const credential = this.getByName(name);
|
|
249
275
|
if (credential === null)
|
|
250
276
|
return null;
|
|
251
|
-
this.db.run(
|
|
277
|
+
this.db.run(`UPDATE subscription_credentials SET unavailable_until = NULL, unavailable_reason = NULL, model_holds = NULL,
|
|
278
|
+
updated_at = ? WHERE id = ?`, [now.getTime(), credential.id]);
|
|
252
279
|
return this.get(credential.id);
|
|
253
280
|
}
|
|
254
281
|
createSession(session, now = new Date()) {
|
|
@@ -285,6 +312,12 @@ export class SubscriptionStore {
|
|
|
285
312
|
export function isHeld(credential, now) {
|
|
286
313
|
return credential.unavailableUntil !== null && credential.unavailableUntil > now;
|
|
287
314
|
}
|
|
315
|
+
/** The models held at their own limit on a subscription now, by model. */
|
|
316
|
+
export function activeModelHolds(credential, now) {
|
|
317
|
+
return credential.modelHolds
|
|
318
|
+
.filter((hold) => hold.until > now)
|
|
319
|
+
.sort((a, b) => a.model.localeCompare(b.model));
|
|
320
|
+
}
|
|
288
321
|
/** The usage a subscription last reported, while its window has not reset. */
|
|
289
322
|
/**
|
|
290
323
|
* The last reported usage of every window that has not reset. A short window
|
|
@@ -360,6 +393,7 @@ function credentialFromRow(row) {
|
|
|
360
393
|
observedAt: new Date(row.usage_observed_at),
|
|
361
394
|
windows: parseWindows(row.usage_windows),
|
|
362
395
|
},
|
|
396
|
+
modelHolds: parseModelHolds(row.model_holds),
|
|
363
397
|
position: row.position,
|
|
364
398
|
createdAt: new Date(row.created_at),
|
|
365
399
|
updatedAt: new Date(row.updated_at),
|
|
@@ -369,6 +403,17 @@ function credentialFromRow(row) {
|
|
|
369
403
|
function windowsJson(usage) {
|
|
370
404
|
return JSON.stringify(usage.windows.map((window) => ({ ...window, resetsAt: window.resetsAt.getTime() })));
|
|
371
405
|
}
|
|
406
|
+
function modelHoldsJson(holds) {
|
|
407
|
+
if (holds.length === 0)
|
|
408
|
+
return null;
|
|
409
|
+
return JSON.stringify(holds.map((hold) => ({ ...hold, until: hold.until.getTime() })));
|
|
410
|
+
}
|
|
411
|
+
function parseModelHolds(value) {
|
|
412
|
+
if (value === null)
|
|
413
|
+
return [];
|
|
414
|
+
return JSON.parse(value)
|
|
415
|
+
.map((hold) => ({ ...hold, until: new Date(hold.until) }));
|
|
416
|
+
}
|
|
372
417
|
// Rows recorded before windows were stored have none.
|
|
373
418
|
function parseWindows(value) {
|
|
374
419
|
if (value === null)
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
import type { OAuthFetch } from "./oauth.js";
|
|
2
|
+
import type { SubscriptionStore } from "./store.js";
|
|
3
|
+
/** Read every stale OpenCode Go plan again; a failed read keeps the last one. */
|
|
4
|
+
export declare function refreshStaleUsage(store: SubscriptionStore, options: {
|
|
5
|
+
fetch: OAuthFetch;
|
|
6
|
+
now?: Date;
|
|
7
|
+
}): Promise<void>;
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
import { openCodeGoUsageFromReport } from "../../providers/subscription_limits.js";
|
|
2
|
+
import { refreshedAccessToken } from "./access.js";
|
|
3
|
+
/**
|
|
4
|
+
* Claude Code, ChatGPT, and Muse Code report usage on the responses the
|
|
5
|
+
* gateway serves. OpenCode Go does not: it reports it from a usage endpoint
|
|
6
|
+
* that takes the plan's workspace, which the accounts view reads again when
|
|
7
|
+
* the last reading is stale.
|
|
8
|
+
*/
|
|
9
|
+
// A read, failed or not, is not repeated within this interval.
|
|
10
|
+
const READ_INTERVAL_MS = 60_000;
|
|
11
|
+
const READ_TIMEOUT_MS = 8_000;
|
|
12
|
+
const OPENCODE_GO_USAGE_URL = "https://opencode.ai/zen/go/v1/usage";
|
|
13
|
+
// Reads that recorded nothing (failed, or no running window), so such a plan is
|
|
14
|
+
// not re-read on every listing. A recorded reading stamps the credential
|
|
15
|
+
// itself, which a reconnect clears.
|
|
16
|
+
const unrecordedAt = new Map();
|
|
17
|
+
/** Read every stale OpenCode Go plan again; a failed read keeps the last one. */
|
|
18
|
+
export async function refreshStaleUsage(store, options) {
|
|
19
|
+
const now = options.now ?? new Date();
|
|
20
|
+
const due = (at) => now.getTime() - (at ?? 0) >= READ_INTERVAL_MS;
|
|
21
|
+
const stale = store.list("opencode_go").filter((credential) => due(credential.usage?.observedAt.getTime()) && due(unrecordedAt.get(credential.id)));
|
|
22
|
+
await Promise.all(stale.map(async (credential) => {
|
|
23
|
+
unrecordedAt.set(credential.id, now.getTime());
|
|
24
|
+
try {
|
|
25
|
+
await readUsage(store, credential, { ...options, now });
|
|
26
|
+
}
|
|
27
|
+
catch (error) {
|
|
28
|
+
console.error(`subscription usage read failed for ${credential.name}:`, error instanceof Error ? error.message : error);
|
|
29
|
+
}
|
|
30
|
+
}));
|
|
31
|
+
}
|
|
32
|
+
async function readUsage(store, credential, options) {
|
|
33
|
+
const token = await refreshedAccessToken(store, credential, options);
|
|
34
|
+
const response = await options.fetch(OPENCODE_GO_USAGE_URL, {
|
|
35
|
+
method: "GET",
|
|
36
|
+
headers: {
|
|
37
|
+
Accept: "application/json",
|
|
38
|
+
Authorization: `Bearer ${token}`,
|
|
39
|
+
"User-Agent": "dari-gateway",
|
|
40
|
+
...(credential.accountId === null ? {} : { "x-opencode-org-id": credential.accountId }),
|
|
41
|
+
},
|
|
42
|
+
signal: AbortSignal.timeout(READ_TIMEOUT_MS),
|
|
43
|
+
});
|
|
44
|
+
// Go answers 403 for a workspace without a Go plan.
|
|
45
|
+
if (!response.ok)
|
|
46
|
+
throw new Error(`OpenCode Go usage read failed with status ${response.status}.`);
|
|
47
|
+
const usage = openCodeGoUsageFromReport(await response.json(), options.now);
|
|
48
|
+
if (usage === null)
|
|
49
|
+
return;
|
|
50
|
+
unrecordedAt.delete(credential.id);
|
|
51
|
+
store.recordUsage(credential.id, usage, options.now);
|
|
52
|
+
}
|
|
@@ -11,11 +11,6 @@ export async function routeDecision(args) {
|
|
|
11
11
|
if (custom === null) {
|
|
12
12
|
throw new HttpError(502, "Router custom rule configuration is missing.", "custom_config_missing");
|
|
13
13
|
}
|
|
14
|
-
if (custom && resolution.candidates.length === 0) {
|
|
15
|
-
const error = new HttpError(502, "No custom routing rule or default model/thinking-level pair is routable for this request.", "custom_no_routable_candidates");
|
|
16
|
-
error.decisionDetails = { custom_rules: custom.audit };
|
|
17
|
-
throw error;
|
|
18
|
-
}
|
|
19
14
|
const relevance = args.selectorBackend.evalRelevance !== undefined
|
|
20
15
|
&& resolution.candidates.length > 1
|
|
21
16
|
? await relevantEvals({
|
package/dist/types.d.ts
CHANGED
|
@@ -18,7 +18,7 @@ export type AwsAssumeRoleProviderAuth = {
|
|
|
18
18
|
region: string;
|
|
19
19
|
};
|
|
20
20
|
export type ResolvedProviderAuth = BearerProviderAuth | AwsSigV4ProviderAuth;
|
|
21
|
-
export type SubscriptionKind = "openai_codex" | "anthropic_claude_code" | "meta_muse";
|
|
21
|
+
export type SubscriptionKind = "openai_codex" | "anthropic_claude_code" | "meta_muse" | "opencode_go";
|
|
22
22
|
export type ProviderCredential = {
|
|
23
23
|
apiKey: string;
|
|
24
24
|
baseUrl?: string;
|
|
@@ -63,6 +63,9 @@ export type ResolvedRouterModelConfig = {
|
|
|
63
63
|
fast_mode_cost?: RouterModelPrice | null;
|
|
64
64
|
zdr?: boolean;
|
|
65
65
|
};
|
|
66
|
+
export type RouterRole = "main" | "subagent";
|
|
67
|
+
export type RouterRoleModels = Partial<Record<RouterRole, string | null>>;
|
|
68
|
+
export type RouterRolePrompts = Partial<Record<RouterRole, string | null>>;
|
|
66
69
|
export type ResolvedRouter = {
|
|
67
70
|
router_id: string;
|
|
68
71
|
organization_id: string;
|
|
@@ -91,6 +94,8 @@ export type ResolvedRouter = {
|
|
|
91
94
|
prefix_hits?: RouterPrefixHit[];
|
|
92
95
|
routing_strategy?: RoutingStrategy;
|
|
93
96
|
custom_config?: CustomRouterConfig | null;
|
|
97
|
+
role_models?: RouterRoleModels;
|
|
98
|
+
role_prompts?: RouterRolePrompts;
|
|
94
99
|
model_thinking_levels?: Record<string, ReasoningEffort[]>;
|
|
95
100
|
fast_models?: string[];
|
|
96
101
|
model_prices?: Record<string, RouterModelPrice>;
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mupt-ai/dari-gateway",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.312",
|
|
4
4
|
"description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -51,7 +51,7 @@
|
|
|
51
51
|
},
|
|
52
52
|
"dependencies": {
|
|
53
53
|
"@aws-sdk/client-sts": "3.1063.0",
|
|
54
|
-
"@mupt-ai/dari-router": "1.0.
|
|
54
|
+
"@mupt-ai/dari-router": "1.0.312",
|
|
55
55
|
"@mupt-ai/pi-ai": "1.5.2-mupt.1"
|
|
56
56
|
},
|
|
57
57
|
"devDependencies": {
|
|
@@ -208,6 +208,13 @@ function sanitizeProviderContent(value: unknown): unknown {
|
|
|
208
208
|
if (part.type === "providerItem" && isRecord(part.item)) {
|
|
209
209
|
return part.item;
|
|
210
210
|
}
|
|
211
|
+
// A thinking signature is an opaque continuation token (encrypted
|
|
212
|
+
// reasoning, an Anthropic signature), not prompt text: its base64 would
|
|
213
|
+
// count far more tokens than the provider bills for it.
|
|
214
|
+
if (part.type === "thinking" && "thinkingSignature" in part) {
|
|
215
|
+
const { thinkingSignature: _signature, ...visible } = part;
|
|
216
|
+
return visible;
|
|
217
|
+
}
|
|
211
218
|
if (
|
|
212
219
|
part.type === "image"
|
|
213
220
|
&& typeof part.mimeType === "string"
|
|
@@ -193,7 +193,10 @@ export async function buildRoutingContext(args: {
|
|
|
193
193
|
thinkingEnabled: args.interaction.reasoning?.enabled === true,
|
|
194
194
|
toolChoice: args.interaction.toolChoice,
|
|
195
195
|
modelThinkingLevels: args.credentials.model_thinking_levels,
|
|
196
|
-
|
|
196
|
+
// Routing rules steer what the selector picks; an explicit model is
|
|
197
|
+
// served as requested, so they do not narrow its candidates.
|
|
198
|
+
strategy: args.credentials.routing_strategy === "custom"
|
|
199
|
+
&& explicitModelId(args.interaction.model) === null ? "custom" : "dari",
|
|
197
200
|
customConfig: args.credentials.custom_config,
|
|
198
201
|
modelPrices: args.credentials.model_prices ?? {},
|
|
199
202
|
pricing,
|