@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
|
@@ -55,6 +55,7 @@ const SUBSCRIPTION_LABEL = {
|
|
|
55
55
|
anthropic_claude_code: "Claude Code",
|
|
56
56
|
openai_codex: "ChatGPT",
|
|
57
57
|
meta_muse: "Muse Code",
|
|
58
|
+
opencode_go: "OpenCode Go",
|
|
58
59
|
};
|
|
59
60
|
// Providers whose plan page the accounts page links to for buying another.
|
|
60
61
|
const BUYABLE_SUBSCRIPTIONS = new Set(["anthropic_claude_code", "openai_codex"]);
|
|
@@ -67,6 +68,8 @@ export function subscriptionOAuthProviderFor(provider, keySource) {
|
|
|
67
68
|
return "openai_codex";
|
|
68
69
|
if (provider === "meta")
|
|
69
70
|
return "meta_muse";
|
|
71
|
+
if (provider === "opencode-go")
|
|
72
|
+
return "opencode_go";
|
|
70
73
|
return null;
|
|
71
74
|
}
|
|
72
75
|
/**
|
|
@@ -74,7 +77,8 @@ export function subscriptionOAuthProviderFor(provider, keySource) {
|
|
|
74
77
|
* answers 429 with the unified rate-limit headers; the ChatGPT backend answers
|
|
75
78
|
* 429 with a structured `error.code` and `resets_at`. Meta documents no
|
|
76
79
|
* usage-limit signature for Muse Code plans, so any 429 on one holds it until
|
|
77
|
-
* the reset Meta gives, if any.
|
|
80
|
+
* the reset Meta gives, if any. OpenCode Go names its refusal
|
|
81
|
+
* `GoUsageLimitError`. The Codex WebSocket
|
|
78
82
|
* transport bypasses fetch, so its usage-limit error only survives as message
|
|
79
83
|
* text and is matched there without a reset time.
|
|
80
84
|
*/
|
|
@@ -84,13 +88,20 @@ export function detectSubscriptionUsageLimit(args) {
|
|
|
84
88
|
return null;
|
|
85
89
|
const now = args.now ?? new Date();
|
|
86
90
|
if (oauthProvider === "anthropic_claude_code") {
|
|
87
|
-
return anthropicUsageLimit(args.captured, now);
|
|
91
|
+
return anthropicUsageLimit(args.captured, args.model, now);
|
|
88
92
|
}
|
|
89
93
|
if (oauthProvider === "meta_muse")
|
|
90
94
|
return museUsageLimit(args.captured, now);
|
|
91
|
-
|
|
95
|
+
if (oauthProvider === "opencode_go")
|
|
96
|
+
return openCodeGoUsageLimit(args.captured, now);
|
|
97
|
+
return codexUsageLimit(args.captured, providerFailureMessage(args.failure), args.model, now);
|
|
92
98
|
}
|
|
93
|
-
|
|
99
|
+
// Claude Code plans also cap some model families on their own
|
|
100
|
+
// (`seven_day_opus`, `seven_day_sonnet`). The representative claim names the
|
|
101
|
+
// window that refused, and `-fallback: available` says another model can still
|
|
102
|
+
// serve; either way the rest of the plan is not exhausted.
|
|
103
|
+
const ANTHROPIC_MODEL_CLAIM = /^(?:five_hour|seven_day)_(?:opus|sonnet|haiku|fable|mythos)(?:_|$)/;
|
|
104
|
+
function anthropicUsageLimit(captured, model, now) {
|
|
94
105
|
if (captured === undefined || captured.status !== 429)
|
|
95
106
|
return null;
|
|
96
107
|
const status = captured.headers.get("anthropic-ratelimit-unified-status");
|
|
@@ -101,25 +112,29 @@ function anthropicUsageLimit(captured, now) {
|
|
|
101
112
|
return null;
|
|
102
113
|
}
|
|
103
114
|
const claim = captured.headers.get("anthropic-ratelimit-unified-representative-claim");
|
|
115
|
+
const modelLimit = (claim !== null && ANTHROPIC_MODEL_CLAIM.test(claim))
|
|
116
|
+
|| captured.headers.get("anthropic-ratelimit-unified-fallback") === "available";
|
|
104
117
|
return {
|
|
105
118
|
oauthProvider: "anthropic_claude_code",
|
|
106
119
|
resetsAt: resetFromUnixSeconds(captured.headers.get("anthropic-ratelimit-unified-reset"), now),
|
|
107
|
-
reason: claim
|
|
120
|
+
reason: claim
|
|
121
|
+
? `Claude Code ${claim.replaceAll("_", " ")} usage limit reached.`
|
|
122
|
+
: modelLimit ? `Claude Code usage limit for ${model} reached.` : "Claude Code usage limit reached.",
|
|
123
|
+
...(modelLimit ? { model } : {}),
|
|
108
124
|
};
|
|
109
125
|
}
|
|
110
126
|
const CODEX_LIMIT_CODES = new Set(["usage_limit_reached", "usage_not_included"]);
|
|
111
127
|
const CODEX_LIMIT_MESSAGE = /usage_limit_reached|usage_not_included|hit your ChatGPT usage limit|the usage limit has been reached/i;
|
|
112
|
-
function codexUsageLimit(captured, failureMessage, now) {
|
|
128
|
+
function codexUsageLimit(captured, failureMessage, model, now) {
|
|
113
129
|
if (captured !== undefined && captured.status === 429) {
|
|
114
130
|
const error = codexErrorBody(captured.bodyText);
|
|
115
131
|
const code = typeof error?.code === "string" ? error.code : "";
|
|
116
132
|
if (error !== null && (CODEX_LIMIT_CODES.has(code) || failureMessage.match(CODEX_LIMIT_MESSAGE))) {
|
|
117
133
|
const plan = typeof error.plan_type === "string" ? ` (${error.plan_type.toLowerCase()} plan)` : "";
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
reason: `ChatGPT usage limit reached${plan}
|
|
122
|
-
};
|
|
134
|
+
const resetsAt = laterReset(error.resets_at, captured.headers, now);
|
|
135
|
+
return codexModelLimitExhausted(captured.headers)
|
|
136
|
+
? { oauthProvider: "openai_codex", resetsAt, reason: `ChatGPT usage limit for ${model} reached${plan}.`, model }
|
|
137
|
+
: { oauthProvider: "openai_codex", resetsAt, reason: `ChatGPT usage limit reached${plan}.` };
|
|
123
138
|
}
|
|
124
139
|
return null;
|
|
125
140
|
}
|
|
@@ -131,6 +146,23 @@ function codexUsageLimit(captured, failureMessage, now) {
|
|
|
131
146
|
reason: "ChatGPT usage limit reached.",
|
|
132
147
|
};
|
|
133
148
|
}
|
|
149
|
+
// The ChatGPT backend reports each limit as its own header family,
|
|
150
|
+
// `x-<limit>-primary-used-percent`, the plan's own being `x-codex-*`. A refusal
|
|
151
|
+
// while only another family is spent is that model's own cap.
|
|
152
|
+
function codexModelLimitExhausted(headers) {
|
|
153
|
+
let plan = false;
|
|
154
|
+
let other = false;
|
|
155
|
+
headers.forEach((value, name) => {
|
|
156
|
+
const family = /^x-(.+)-(?:primary|secondary)-used-percent$/.exec(name.toLowerCase())?.[1];
|
|
157
|
+
if (family === undefined || !(Number(value) >= 100))
|
|
158
|
+
return;
|
|
159
|
+
if (family === "codex")
|
|
160
|
+
plan = true;
|
|
161
|
+
else
|
|
162
|
+
other = true;
|
|
163
|
+
});
|
|
164
|
+
return other && !plan;
|
|
165
|
+
}
|
|
134
166
|
function museUsageLimit(captured, now) {
|
|
135
167
|
if (captured === undefined || captured.status !== 429)
|
|
136
168
|
return null;
|
|
@@ -140,6 +172,23 @@ function museUsageLimit(captured, now) {
|
|
|
140
172
|
reason: "Muse Code usage limit reached.",
|
|
141
173
|
};
|
|
142
174
|
}
|
|
175
|
+
// OpenCode Go refuses an exhausted plan with 429 and a `GoUsageLimitError`
|
|
176
|
+
// naming the window ("5 hour", "weekly", "monthly"), as OpenCode's own client
|
|
177
|
+
// recognizes it; an upstream's transient 429 on Go does not hold the plan.
|
|
178
|
+
// The reset is `resetsAt` (ISO) when sent, else Retry-After.
|
|
179
|
+
function openCodeGoUsageLimit(captured, now) {
|
|
180
|
+
if (captured === undefined || captured.status !== 429)
|
|
181
|
+
return null;
|
|
182
|
+
if (!captured.bodyText.includes("GoUsageLimitError"))
|
|
183
|
+
return null;
|
|
184
|
+
const window = /"limitName"\s*:\s*"([^"]+)"/.exec(captured.bodyText)?.[1];
|
|
185
|
+
const resetsAt = Date.parse(/"resetsAt"\s*:\s*"([^"]+)"/.exec(captured.bodyText)?.[1] ?? "");
|
|
186
|
+
return {
|
|
187
|
+
oauthProvider: "opencode_go",
|
|
188
|
+
resetsAt: laterReset(Number.isNaN(resetsAt) ? undefined : resetsAt / 1000, captured.headers, now),
|
|
189
|
+
reason: `OpenCode Go ${window ? `${window} ` : ""}usage limit reached.`,
|
|
190
|
+
};
|
|
191
|
+
}
|
|
143
192
|
function codexErrorBody(bodyText) {
|
|
144
193
|
try {
|
|
145
194
|
const parsed = JSON.parse(bodyText);
|
|
@@ -191,6 +240,7 @@ export function failureWithSubscriptionUsageLimit(failure, limit) {
|
|
|
191
240
|
oauth_provider: limit.oauthProvider,
|
|
192
241
|
resets_at: limit.resetsAt.toISOString(),
|
|
193
242
|
reason: limit.reason,
|
|
243
|
+
...(limit.model !== undefined ? { model: limit.model } : {}),
|
|
194
244
|
...(limit.switched === true ? { switched: true } : {}),
|
|
195
245
|
},
|
|
196
246
|
};
|
|
@@ -209,6 +259,7 @@ export function subscriptionUsageLimitFromFailure(failure) {
|
|
|
209
259
|
oauthProvider: oauthProvider,
|
|
210
260
|
resetsAt,
|
|
211
261
|
reason: typeof marker.reason === "string" ? marker.reason : "Subscription usage limit reached.",
|
|
262
|
+
...(typeof marker.model === "string" ? { model: marker.model } : {}),
|
|
212
263
|
...(marker.switched === true ? { switched: true } : {}),
|
|
213
264
|
};
|
|
214
265
|
}
|
|
@@ -219,7 +270,8 @@ export function subscriptionUsageLimitFromFailure(failure) {
|
|
|
219
270
|
*/
|
|
220
271
|
export function subscriptionUsageLimitMessage(limit, accountsUrl) {
|
|
221
272
|
const label = SUBSCRIPTION_LABEL[limit.oauthProvider];
|
|
222
|
-
const
|
|
273
|
+
const scope = limit.model === undefined ? "" : ` for ${limit.model}`;
|
|
274
|
+
const reached = `Your ${label} subscription usage limit${scope} is reached. It resets at ${limit.resetsAt.toISOString()}. `;
|
|
223
275
|
if (accountsUrl === undefined) {
|
|
224
276
|
return reached
|
|
225
277
|
+ `To keep going now, add another ${label} subscription or mark this one available early with \`dari accounts\`.`;
|
|
@@ -237,7 +289,8 @@ export function subscriptionUsageLimitMessage(limit, accountsUrl) {
|
|
|
237
289
|
* at <reset>."
|
|
238
290
|
*/
|
|
239
291
|
export function codexUsageLimitError(limit, accountsUrl) {
|
|
240
|
-
|
|
292
|
+
// Codex would show a per-model limit as the whole plan's.
|
|
293
|
+
if (limit.oauthProvider !== "openai_codex" || limit.model !== undefined)
|
|
241
294
|
return null;
|
|
242
295
|
const promo = accountsUrl === undefined
|
|
243
296
|
? "Add another ChatGPT subscription with `dari accounts`"
|
|
@@ -249,6 +302,10 @@ export function codexUsageLimitError(limit, accountsUrl) {
|
|
|
249
302
|
}
|
|
250
303
|
export function subscriptionSwitchedMessage(limit) {
|
|
251
304
|
const label = SUBSCRIPTION_LABEL[limit.oauthProvider];
|
|
305
|
+
if (limit.model !== undefined) {
|
|
306
|
+
return `Your ${label} subscription usage limit for ${limit.model} is reached; it resets at `
|
|
307
|
+
+ `${limit.resetsAt.toISOString()}. Dari routes to other models until then; retry the request.`;
|
|
308
|
+
}
|
|
252
309
|
return `Your ${label} subscription usage limit is reached. `
|
|
253
310
|
+ `Dari switched to your next connected ${label} subscription; retry the request.`;
|
|
254
311
|
}
|
|
@@ -2,15 +2,18 @@ import { HttpError } from "../http/errors.js";
|
|
|
2
2
|
import { explicitModelId } from "../protocol/input/router_model.js";
|
|
3
3
|
/* A request for `dari/model/<id>` is served by exactly that enabled model,
|
|
4
4
|
with no selector or lease: the user chose it, like picking a
|
|
5
|
-
model in their agent's /model menu
|
|
6
|
-
|
|
5
|
+
model in their agent's /model menu, or the router fixed it for the
|
|
6
|
+
request's agent role. Routing rules and switch-cost pruning narrow only
|
|
7
|
+
what the selector may pick, so they never remove it. The client's thinking
|
|
8
|
+
level is kept when the model supports it; otherwise the model's default
|
|
9
|
+
level is used. */
|
|
7
10
|
export function explicitModelDecision(prepared) {
|
|
8
11
|
const modelId = explicitModelId(prepared.interaction.model);
|
|
9
12
|
if (modelId === null)
|
|
10
13
|
return null;
|
|
11
14
|
if (!prepared.credentials.enabled_models.includes(modelId))
|
|
12
15
|
throw modelNotEnabled(modelId);
|
|
13
|
-
const candidates = prepared.routing.candidateResolution.
|
|
16
|
+
const candidates = prepared.routing.candidateResolution.allCandidates.filter((candidate) => candidate.model === modelId);
|
|
14
17
|
if (candidates.length === 0) {
|
|
15
18
|
throw new HttpError(400, `Model '${modelId}' cannot serve this request.`, "model_unavailable", "model");
|
|
16
19
|
}
|
|
@@ -18,7 +21,9 @@ export function explicitModelDecision(prepared) {
|
|
|
18
21
|
const decision = {
|
|
19
22
|
selectedModel: candidate.model,
|
|
20
23
|
reasoningEffort: candidate.reasoningEffort,
|
|
21
|
-
reason:
|
|
24
|
+
reason: prepared.role === undefined
|
|
25
|
+
? `Requested model ${modelId} served without selection.`
|
|
26
|
+
: `The router's ${prepared.role} model ${modelId} served without selection.`,
|
|
22
27
|
};
|
|
23
28
|
return { decision };
|
|
24
29
|
}
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { type RoutingContext } from "../context/routing_context.js";
|
|
2
2
|
import { type InteractionRequest } from "../interaction/types.js";
|
|
3
3
|
import { type RequestTags, type SessionPin } from "../platform/platform.js";
|
|
4
|
-
import type { ClientHarness, ResolvedRouter } from "../types.js";
|
|
4
|
+
import type { ClientHarness, ResolvedRouter, RouterRole } from "../types.js";
|
|
5
5
|
import type { RoutedRuntimeReporter } from "./runtime_reporter.js";
|
|
6
6
|
import type { RoutedProtocol } from "./routed_protocol.js";
|
|
7
7
|
import { type HarnessConversationIdentity } from "./harness_identity/index.js";
|
|
@@ -20,6 +20,8 @@ export type PreparedRoutedCompletion = {
|
|
|
20
20
|
key: string;
|
|
21
21
|
pin: SessionPin | null;
|
|
22
22
|
};
|
|
23
|
+
role?: RouterRole;
|
|
24
|
+
rolePrompt?: string;
|
|
23
25
|
reporter: RoutedRuntimeReporter;
|
|
24
26
|
};
|
|
25
27
|
export declare function prepareRoutedCompletion(args: {
|
|
@@ -11,6 +11,7 @@ import { resolveRouter } from "../strategies/routing.js";
|
|
|
11
11
|
import { RequestReporter } from "../telemetry/report.js";
|
|
12
12
|
import { RoutingBillingFinalization } from "../telemetry/billing_finalization.js";
|
|
13
13
|
import { requestTags } from "./request_tags.js";
|
|
14
|
+
import { rolePrompt, withRoleModel } from "./role_model.js";
|
|
14
15
|
import { strictProviderAccess } from "./strict_provider_access.js";
|
|
15
16
|
import { scopedHarnessAgentId, scopedHarnessConversationId, scopedHarnessSessionId, } from "./harness_identity/index.js";
|
|
16
17
|
export async function prepareRoutedCompletion(args) {
|
|
@@ -86,7 +87,9 @@ export async function prepareRoutedCompletion(args) {
|
|
|
86
87
|
}
|
|
87
88
|
credentials = conversationCredentials;
|
|
88
89
|
}
|
|
89
|
-
const
|
|
90
|
+
const roleModel = withRoleModel(credentials, args.interaction);
|
|
91
|
+
const prompt = rolePrompt(credentials, args.interaction);
|
|
92
|
+
const access = strictProviderAccess(credentials, roleModel.interaction);
|
|
90
93
|
credentials = access.credentials;
|
|
91
94
|
args = {
|
|
92
95
|
...args,
|
|
@@ -167,6 +170,8 @@ export async function prepareRoutedCompletion(args) {
|
|
|
167
170
|
harnessConversationIdentity: args.harnessConversationIdentity,
|
|
168
171
|
routing,
|
|
169
172
|
...(sessionPin === undefined ? {} : { sessionPin }),
|
|
173
|
+
...(roleModel.role === undefined ? {} : { role: roleModel.role }),
|
|
174
|
+
...(prompt === undefined ? {} : { rolePrompt: prompt }),
|
|
170
175
|
reporter,
|
|
171
176
|
};
|
|
172
177
|
}
|
|
@@ -193,7 +198,7 @@ async function withProviderCredentials(credentials, apiKey, clientHarness) {
|
|
|
193
198
|
if (!credential?.apiKey.trim())
|
|
194
199
|
continue;
|
|
195
200
|
const plan = credential.subscription;
|
|
196
|
-
if (plan !== undefined && !subscriptionServes(plan, model, clientHarness))
|
|
201
|
+
if (plan !== undefined && !subscriptionServes(plan, executionProviderForModel(credentials, model), clientHarness))
|
|
197
202
|
continue;
|
|
198
203
|
provider_credentials[model] = credential;
|
|
199
204
|
if (plan === "openai_codex") {
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
import { type InteractionRequest } from "../interaction/types.js";
|
|
2
|
+
import type { ResolvedRouter, RouterRole } from "../types.js";
|
|
3
|
+
export declare function requestRole(interaction: InteractionRequest): RouterRole | null;
|
|
4
|
+
export declare function withRoleModel(credentials: ResolvedRouter, interaction: InteractionRequest): {
|
|
5
|
+
interaction: InteractionRequest;
|
|
6
|
+
role?: RouterRole;
|
|
7
|
+
};
|
|
8
|
+
export declare function rolePrompt(credentials: ResolvedRouter, interaction: InteractionRequest): string | undefined;
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { isBackgroundRequest } from "../interaction/types.js";
|
|
2
|
+
import { EXPLICIT_MODEL_PREFIX } from "../protocol/input/router_model.js";
|
|
3
|
+
/* The agent role a request comes from: subagents include workflow agents, and
|
|
4
|
+
anything else that is not background work (compaction, auxiliary requests,
|
|
5
|
+
side replies) is the main agent. Background work has no role. */
|
|
6
|
+
export function requestRole(interaction) {
|
|
7
|
+
if (isBackgroundRequest(interaction))
|
|
8
|
+
return null;
|
|
9
|
+
const requestClass = interaction.agentContext?.requestClass;
|
|
10
|
+
return requestClass === "subagent" || requestClass === "workflow" ? "subagent" : "main";
|
|
11
|
+
}
|
|
12
|
+
/* A router can fix the model for an agent role. A request from a fixed role
|
|
13
|
+
is served that model as if it had asked for `dari/model/<id>`, whatever
|
|
14
|
+
model it did ask for. */
|
|
15
|
+
export function withRoleModel(credentials, interaction) {
|
|
16
|
+
const role = requestRole(interaction);
|
|
17
|
+
const model = role === null ? null : credentials.role_models?.[role];
|
|
18
|
+
if (!role || !model)
|
|
19
|
+
return { interaction };
|
|
20
|
+
return { interaction: { ...interaction, model: `${EXPLICIT_MODEL_PREFIX}${model}` }, role };
|
|
21
|
+
}
|
|
22
|
+
/* The router's prompt for a request's role, or undefined. */
|
|
23
|
+
export function rolePrompt(credentials, interaction) {
|
|
24
|
+
const role = requestRole(interaction);
|
|
25
|
+
const prompt = role === null ? undefined : credentials.role_prompts?.[role]?.trim();
|
|
26
|
+
return prompt || undefined;
|
|
27
|
+
}
|
|
@@ -145,10 +145,11 @@ async function prepareRuntimeExecution(args) {
|
|
|
145
145
|
if (explicit) {
|
|
146
146
|
prepared.reporter.attachServingDecision(explicit.decision);
|
|
147
147
|
prepared.reporter.attachDecisionDetails({
|
|
148
|
-
decision_source: "explicit_model",
|
|
148
|
+
decision_source: prepared.role === undefined ? "explicit_model" : "role_model",
|
|
149
149
|
explicit_model: {
|
|
150
150
|
model: explicit.decision.selectedModel,
|
|
151
151
|
reasoning_effort: explicit.decision.reasoningEffort,
|
|
152
|
+
...(prepared.role === undefined ? {} : { role: prepared.role }),
|
|
152
153
|
},
|
|
153
154
|
});
|
|
154
155
|
return selectedExecutionPlan(prepared, explicit);
|
|
@@ -441,6 +442,7 @@ function providerExecution(prepared, decision) {
|
|
|
441
442
|
costEstimates: prepared.routing.reportingCostEstimates,
|
|
442
443
|
promptCacheKey: prepared.interaction.promptCacheKey,
|
|
443
444
|
tags: prepared.tags,
|
|
445
|
+
systemPromptSuffix: prepared.rolePrompt,
|
|
444
446
|
});
|
|
445
447
|
}
|
|
446
448
|
function tokenCount(value) {
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { type ReasoningEffort } from "@mupt-ai/dari-router/policy-engine";
|
|
2
|
-
import type { ClientHarness } from "../types.js";
|
|
2
|
+
import type { ClientHarness, RouterRoleModels, RouterRolePrompts } from "../types.js";
|
|
3
3
|
/**
|
|
4
4
|
* The self-hosted gateway's configuration file (YAML or JSON):
|
|
5
5
|
*
|
|
@@ -15,6 +15,11 @@ import type { ClientHarness } from "../types.js";
|
|
|
15
15
|
* - openai/gpt-6.1-sol
|
|
16
16
|
* subscriptions: true # serve with connected Claude Code / ChatGPT plans
|
|
17
17
|
* sessionPinning: false # route each session and subagent once, then keep its model
|
|
18
|
+
* roleModels: # optional: serve an agent role one model, without routing
|
|
19
|
+
* main: anthropic/claude-fable-5-2
|
|
20
|
+
* subagent: openai/gpt-6.1-sol
|
|
21
|
+
* rolePrompts: # optional: append to an agent role's system prompt
|
|
22
|
+
* main: Delegate codebase exploration to subagents.
|
|
18
23
|
* nativeCompaction: false # let Codex compact server-side with the provider's native compaction
|
|
19
24
|
* providers: # optional: OpenAI-compatible or self-run endpoints
|
|
20
25
|
* local:
|
|
@@ -45,6 +50,8 @@ export type RouterConfig = {
|
|
|
45
50
|
sessionPinning: boolean;
|
|
46
51
|
nativeCompaction: boolean;
|
|
47
52
|
zdr: boolean;
|
|
53
|
+
roleModels: RouterRoleModels;
|
|
54
|
+
rolePrompts: RouterRolePrompts;
|
|
48
55
|
};
|
|
49
56
|
export type RouterModelConfig = {
|
|
50
57
|
id: string;
|
|
@@ -62,5 +69,6 @@ export declare function parseGatewayConfig(raw: unknown): GatewayConfig;
|
|
|
62
69
|
export declare function routerModelsFor(router: RouterConfig, clientHarness?: ClientHarness): RouterModelConfig[];
|
|
63
70
|
/** Every model a router can serve, to any client. */
|
|
64
71
|
export declare function allRouterModels(router: RouterConfig): RouterModelConfig[];
|
|
72
|
+
export declare const ROLE_PROMPT_MAX_LENGTH = 4000;
|
|
65
73
|
/** Read one model list of a router, naming `field` in what it rejects. */
|
|
66
74
|
export declare function parseRouterModels(routerId: string, field: string, raw: unknown): RouterModelConfig[];
|
package/dist/self_host/config.js
CHANGED
|
@@ -108,9 +108,12 @@ function parseRouter(id, raw) {
|
|
|
108
108
|
agentModels[agent] = parseRouterModels(id, `agentModels.${agent}`, models);
|
|
109
109
|
}
|
|
110
110
|
}
|
|
111
|
+
const models = parseRouterModels(id, "models", raw.models);
|
|
111
112
|
return {
|
|
112
|
-
models
|
|
113
|
+
models,
|
|
113
114
|
agentModels,
|
|
115
|
+
roleModels: parseRoleModels(id, raw.roleModels, [models, ...Object.values(agentModels)].flat()),
|
|
116
|
+
rolePrompts: parseRolePrompts(id, raw.rolePrompts),
|
|
114
117
|
retries: optionalRetries(raw.retries, `routers.${id}.retries`) ?? 1,
|
|
115
118
|
subscriptions: optionalBoolean(raw.subscriptions, `routers.${id}.subscriptions`) ?? true,
|
|
116
119
|
sessionPinning: optionalBoolean(raw.sessionPinning, `routers.${id}.sessionPinning`) ?? false,
|
|
@@ -118,6 +121,46 @@ function parseRouter(id, raw) {
|
|
|
118
121
|
zdr: optionalBoolean(raw.zdr, `routers.${id}.zdr`) ?? false,
|
|
119
122
|
};
|
|
120
123
|
}
|
|
124
|
+
const ROUTER_ROLES = ["main", "subagent"];
|
|
125
|
+
function parseRoleModels(routerId, raw, models) {
|
|
126
|
+
if (raw === undefined)
|
|
127
|
+
return {};
|
|
128
|
+
if (!isRecord(raw))
|
|
129
|
+
throw new Error(`routers.${routerId}.roleModels must map main and subagent to models.`);
|
|
130
|
+
const roleModels = {};
|
|
131
|
+
for (const [role, model] of Object.entries(raw)) {
|
|
132
|
+
if (!ROUTER_ROLES.includes(role)) {
|
|
133
|
+
throw new Error(`routers.${routerId}.roleModels has an unknown role "${role}"; use main or subagent.`);
|
|
134
|
+
}
|
|
135
|
+
if (model === null)
|
|
136
|
+
continue;
|
|
137
|
+
if (typeof model !== "string" || !models.some((listed) => listed.id === model)) {
|
|
138
|
+
throw new Error(`routers.${routerId}.roleModels.${role} must be one of the router's models.`);
|
|
139
|
+
}
|
|
140
|
+
roleModels[role] = model;
|
|
141
|
+
}
|
|
142
|
+
return roleModels;
|
|
143
|
+
}
|
|
144
|
+
export const ROLE_PROMPT_MAX_LENGTH = 4000;
|
|
145
|
+
function parseRolePrompts(routerId, raw) {
|
|
146
|
+
if (raw === undefined)
|
|
147
|
+
return {};
|
|
148
|
+
if (!isRecord(raw))
|
|
149
|
+
throw new Error(`routers.${routerId}.rolePrompts must map main and subagent to text.`);
|
|
150
|
+
const rolePrompts = {};
|
|
151
|
+
for (const [role, prompt] of Object.entries(raw)) {
|
|
152
|
+
if (!ROUTER_ROLES.includes(role)) {
|
|
153
|
+
throw new Error(`routers.${routerId}.rolePrompts has an unknown role "${role}"; use main or subagent.`);
|
|
154
|
+
}
|
|
155
|
+
if (prompt === null)
|
|
156
|
+
continue;
|
|
157
|
+
if (typeof prompt !== "string" || !prompt.trim() || prompt.length > ROLE_PROMPT_MAX_LENGTH) {
|
|
158
|
+
throw new Error(`routers.${routerId}.rolePrompts.${role} must be text of at most ${ROLE_PROMPT_MAX_LENGTH} characters.`);
|
|
159
|
+
}
|
|
160
|
+
rolePrompts[role] = prompt.trim();
|
|
161
|
+
}
|
|
162
|
+
return rolePrompts;
|
|
163
|
+
}
|
|
121
164
|
/** Read one model list of a router, naming `field` in what it rejects. */
|
|
122
165
|
export function parseRouterModels(routerId, field, raw) {
|
|
123
166
|
if (!Array.isArray(raw) || raw.length === 0) {
|
|
@@ -37,8 +37,13 @@ export function createSelfHostedPlatform(deps) {
|
|
|
37
37
|
apiKey: await freshAccessToken(deps.subscriptions, next, { fetch: deps.fetch }),
|
|
38
38
|
};
|
|
39
39
|
},
|
|
40
|
-
|
|
41
|
-
|
|
40
|
+
async markSubscriptionUnavailable({ credentialId, limit }) {
|
|
41
|
+
if (credentialId === undefined)
|
|
42
|
+
return false;
|
|
43
|
+
return limit.model === undefined
|
|
44
|
+
? deps.subscriptions.markUnavailable(credentialId, limit.resetsAt, limit.reason)
|
|
45
|
+
: deps.subscriptions.holdModel(credentialId, limit.model, limit.resetsAt, limit.reason);
|
|
46
|
+
},
|
|
42
47
|
async recordUsage() {
|
|
43
48
|
// Resolution never reports a "managed" key source here.
|
|
44
49
|
throw new Error("The self-hosted gateway has no managed provider keys to account.");
|
|
@@ -4,7 +4,7 @@ import { HttpError } from "../http/errors.js";
|
|
|
4
4
|
import { codexModelConfig } from "../models/subscriptions.js";
|
|
5
5
|
import { registeredModelPrice } from "../providers/pi.js";
|
|
6
6
|
import { allRouterModels, routerModelsFor, } from "./config.js";
|
|
7
|
-
import { freshAccessToken, } from "./subscriptions/index.js";
|
|
7
|
+
import { activeModelHolds, freshAccessToken, } from "./subscriptions/index.js";
|
|
8
8
|
// A self-hosted gateway is one tenant; these stand in for the hosted
|
|
9
9
|
// organization and the user a personal subscription belongs to.
|
|
10
10
|
export const SELF_HOSTED_ORGANIZATION_ID = "self-hosted";
|
|
@@ -55,7 +55,17 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
55
55
|
const apiKey = await configuredProviderApiKey(deps, provider);
|
|
56
56
|
credentials.set(provider, apiKey ? { key: apiKey, source: "user" } : null);
|
|
57
57
|
}
|
|
58
|
-
|
|
58
|
+
// A model at its own limit on the serving plan leaves routing until it resets.
|
|
59
|
+
const models = listed.filter((model) => {
|
|
60
|
+
const credential = credentials.get(providerForModel(model.id));
|
|
61
|
+
if (credential == null)
|
|
62
|
+
return false;
|
|
63
|
+
const plan = credential.subscription;
|
|
64
|
+
if (plan === undefined || !activeModelHolds(plan, now).some((hold) => hold.model === model.id))
|
|
65
|
+
return true;
|
|
66
|
+
exhausted.add(plan.provider);
|
|
67
|
+
return false;
|
|
68
|
+
});
|
|
59
69
|
if (models.length === 0) {
|
|
60
70
|
const missing = [...credentials].filter(([, credential]) => credential == null).map(([provider]) => provider);
|
|
61
71
|
throw unavailableRouterError(request.routerId, exhausted, missing);
|
|
@@ -77,6 +87,8 @@ export async function resolveSelfHostedRouter(deps, request) {
|
|
|
77
87
|
primary_retries: router.retries,
|
|
78
88
|
routing_strategy: "dari",
|
|
79
89
|
custom_config: null,
|
|
90
|
+
role_models: router.roleModels,
|
|
91
|
+
role_prompts: router.rolePrompts,
|
|
80
92
|
evals: [],
|
|
81
93
|
model_thinking_levels: thinkingLevels(listed),
|
|
82
94
|
model_prices: {},
|
|
@@ -149,6 +161,8 @@ function subscriptionProviderFor(provider, clientHarness) {
|
|
|
149
161
|
return clientHarness === "muse_code" ? "meta_muse" : null;
|
|
150
162
|
if (provider === "openai")
|
|
151
163
|
return "openai_codex";
|
|
164
|
+
if (provider === "opencode-go")
|
|
165
|
+
return "opencode_go";
|
|
152
166
|
return null;
|
|
153
167
|
}
|
|
154
168
|
// A ChatGPT plan serves OpenAI models as the `openai-codex` provider, and the
|
|
@@ -165,6 +179,7 @@ const SUBSCRIPTION_PLAN_NAMES = {
|
|
|
165
179
|
anthropic_claude_code: "Claude Code",
|
|
166
180
|
openai_codex: "ChatGPT",
|
|
167
181
|
meta_muse: "Muse Code",
|
|
182
|
+
opencode_go: "OpenCode Go",
|
|
168
183
|
};
|
|
169
184
|
/**
|
|
170
185
|
* Providers a router lists that no credential can serve: no API key and no
|
|
@@ -193,7 +208,7 @@ function unavailableRouterError(routerId, exhausted, missing) {
|
|
|
193
208
|
const plans = [...exhausted]
|
|
194
209
|
.map((provider) => SUBSCRIPTION_PLAN_NAMES[provider])
|
|
195
210
|
.join(" and ");
|
|
196
|
-
return new HttpError(424, `Every connected ${plans} subscription is at its usage limit, and no API key can serve
|
|
211
|
+
return new HttpError(424, `Every connected ${plans} subscription is at its usage limit for the models router ${routerId} lists, and no API key can serve them instead.${missingNote}`, "personal_subscription_unavailable");
|
|
197
212
|
}
|
|
198
213
|
return new HttpError(424, `No credentials can serve router ${routerId}.${missingNote} Set each provider's API key or connect a subscription that can serve it.`, "provider_credentials_missing");
|
|
199
214
|
}
|
|
@@ -2,13 +2,14 @@
|
|
|
2
2
|
* A self-hosted gateway, run through its entrypoint as its own process so no
|
|
3
3
|
* other test file's module mocks reach it, serving two Claude Code plans
|
|
4
4
|
* (access tokens `sk-ant-oat01-a` and `-b`) against a local stand-in for
|
|
5
|
-
* Anthropic. `upstream` answers each provider call given the plan's token
|
|
5
|
+
* Anthropic. `upstream` answers each provider call given the plan's token
|
|
6
|
+
* and the native model it asks for. The router lists `models`.
|
|
6
7
|
*/
|
|
7
|
-
export declare function startSubscriptionGateway(upstream: (token: string) => Response): Promise<{
|
|
8
|
+
export declare function startSubscriptionGateway(upstream: (token: string, model: string) => Response, models?: string[]): Promise<{
|
|
8
9
|
served: string[];
|
|
9
10
|
planIds: string[];
|
|
10
11
|
plan: (id: string) => import("./subscriptions/store.js").SubscriptionCredential | null;
|
|
11
|
-
claudeCode: (sessionId: string, text: string) => Promise<Response>;
|
|
12
|
+
claudeCode: (sessionId: string, text: string, model?: string) => Promise<Response>;
|
|
12
13
|
stop: () => Promise<void>;
|
|
13
14
|
}>;
|
|
14
15
|
/** A streamed Anthropic reply with the given response headers. */
|
|
@@ -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 }],
|
|
@@ -5,7 +5,8 @@
|
|
|
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";
|
|
9
10
|
const BASE = "/v1/organizations/current/credentials";
|
|
10
11
|
// Subscription names are env-var-style, which keeps other credential routes
|
|
11
12
|
// such as `provider-credentials/...` out of these matches.
|
|
@@ -171,6 +172,13 @@ function credentialBody(credential, active, now) {
|
|
|
171
172
|
last_used_at: credential.lastUsedAt?.toISOString() ?? null,
|
|
172
173
|
unavailable_until: held ? credential.unavailableUntil.toISOString() : null,
|
|
173
174
|
unavailable_reason: held ? credential.unavailableReason : null,
|
|
175
|
+
// Models at their own usage limit; the plan still serves the others.
|
|
176
|
+
model_holds: activeModelHolds(credential, now).map((hold) => ({
|
|
177
|
+
model: hold.model,
|
|
178
|
+
display_name: canonicalModelName(hold.model),
|
|
179
|
+
unavailable_until: hold.until.toISOString(),
|
|
180
|
+
reason: hold.reason,
|
|
181
|
+
})),
|
|
174
182
|
subscription_active: active,
|
|
175
183
|
// The share of its tightest window the plan last reported used, while
|
|
176
184
|
// that window has not reset; null when it reports none.
|
|
@@ -17,9 +17,10 @@
|
|
|
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";
|
|
24
25
|
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";
|
|
26
|
+
export { SubscriptionStore, activeModelHolds, isHeld, type PendingOAuthSession, type SubscriptionCredential, type SubscriptionModelHold, } from "./store.js";
|
|
@@ -17,9 +17,10 @@
|
|
|
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 } from "./http.js";
|
|
24
25
|
export { CODEX_APPROVAL_PENDING, SUBSCRIPTION_PROVIDERS, SubscriptionOAuthInputError, SubscriptionOAuthProviderError, completeOAuth, parseAuthorizationResponse, refreshOAuth, startOAuth, } from "./oauth.js";
|
|
25
|
-
export { SubscriptionStore, isHeld, } from "./store.js";
|
|
26
|
+
export { SubscriptionStore, activeModelHolds, isHeld, } from "./store.js";
|