@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
package/README.md
CHANGED
|
@@ -83,6 +83,10 @@ routers:
|
|
|
83
83
|
subscriptions: true # prefer connected subscriptions over API keys
|
|
84
84
|
sessionPinning: false # route each session and subagent once, then keep its model
|
|
85
85
|
nativeCompaction: false # let Codex compact server-side; compacted requests route only to supporting models
|
|
86
|
+
roleModels: # optional: serve the main agent or subagents one model, without routing
|
|
87
|
+
subagent: openai/gpt-6.1-sol
|
|
88
|
+
rolePrompts: # optional: append to the main agent's or subagents' system prompt
|
|
89
|
+
main: Delegate codebase exploration to subagents.
|
|
86
90
|
local: # serves /local/v1/...
|
|
87
91
|
models: [local/qwen3-coder]
|
|
88
92
|
|
|
@@ -21,6 +21,16 @@ routers:
|
|
|
21
21
|
# Route each session's first turn, then keep that model for the whole
|
|
22
22
|
# session; each subagent is routed once on its own (default false).
|
|
23
23
|
sessionPinning: false
|
|
24
|
+
# Serve an agent role one of the router's models without routing: the
|
|
25
|
+
# main agent, and subagents (including workflow agents). A role left out
|
|
26
|
+
# is routed; background work keeps its own routing.
|
|
27
|
+
# roleModels:
|
|
28
|
+
# main: anthropic/claude-fable-5-2
|
|
29
|
+
# subagent: openai/gpt-6.1-terra
|
|
30
|
+
# Append text to the end of a role's system prompt, for example to nudge
|
|
31
|
+
# the main agent to delegate. Background work never gets it.
|
|
32
|
+
# rolePrompts:
|
|
33
|
+
# main: Delegate codebase exploration and independent edits to subagents.
|
|
24
34
|
# Let Codex compact context server-side with the provider's native
|
|
25
35
|
# compaction; requests carrying compaction state are routed only to
|
|
26
36
|
# models that support it (default false).
|
|
@@ -169,6 +169,13 @@ function sanitizeProviderContent(value) {
|
|
|
169
169
|
if (part.type === "providerItem" && isRecord(part.item)) {
|
|
170
170
|
return part.item;
|
|
171
171
|
}
|
|
172
|
+
// A thinking signature is an opaque continuation token (encrypted
|
|
173
|
+
// reasoning, an Anthropic signature), not prompt text: its base64 would
|
|
174
|
+
// count far more tokens than the provider bills for it.
|
|
175
|
+
if (part.type === "thinking" && "thinkingSignature" in part) {
|
|
176
|
+
const { thinkingSignature: _signature, ...visible } = part;
|
|
177
|
+
return visible;
|
|
178
|
+
}
|
|
172
179
|
if (part.type === "image"
|
|
173
180
|
&& typeof part.mimeType === "string"
|
|
174
181
|
&& typeof part.data === "string") {
|
|
@@ -90,7 +90,10 @@ export async function buildRoutingContext(args) {
|
|
|
90
90
|
thinkingEnabled: args.interaction.reasoning?.enabled === true,
|
|
91
91
|
toolChoice: args.interaction.toolChoice,
|
|
92
92
|
modelThinkingLevels: args.credentials.model_thinking_levels,
|
|
93
|
-
|
|
93
|
+
// Routing rules steer what the selector picks; an explicit model is
|
|
94
|
+
// served as requested, so they do not narrow its candidates.
|
|
95
|
+
strategy: args.credentials.routing_strategy === "custom"
|
|
96
|
+
&& explicitModelId(args.interaction.model) === null ? "custom" : "dari",
|
|
94
97
|
customConfig: args.credentials.custom_config,
|
|
95
98
|
modelPrices: args.credentials.model_prices ?? {},
|
|
96
99
|
pricing,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
/* Appends text to the end of the system prompt: after the client's
|
|
2
|
+
instructions and its leading system or developer messages, before the
|
|
3
|
+
conversation. The text is the same on every turn, so the provider's cached
|
|
4
|
+
prefix stays stable. */
|
|
5
|
+
export function withSystemPromptSuffix(interaction, suffix) {
|
|
6
|
+
if (!suffix)
|
|
7
|
+
return interaction;
|
|
8
|
+
const isPreamble = (item) => item.type === "message" && (item.role === "system" || item.role === "developer");
|
|
9
|
+
const at = interaction.items.findIndex((item) => !isPreamble(item));
|
|
10
|
+
const index = at === -1 ? interaction.items.length : at;
|
|
11
|
+
const message = {
|
|
12
|
+
type: "message",
|
|
13
|
+
role: "system",
|
|
14
|
+
content: [{ type: "text", text: suffix }],
|
|
15
|
+
contentShape: "string",
|
|
16
|
+
};
|
|
17
|
+
return {
|
|
18
|
+
...interaction,
|
|
19
|
+
items: [...interaction.items.slice(0, index), message, ...interaction.items.slice(index)],
|
|
20
|
+
};
|
|
21
|
+
}
|
|
@@ -5,3 +5,5 @@ export type CanonicalModel = {
|
|
|
5
5
|
};
|
|
6
6
|
/** The canonical models Dari serves, from the monorepo's router catalog. */
|
|
7
7
|
export declare const CANONICAL_MODELS: readonly CanonicalModel[];
|
|
8
|
+
/** A model's catalog name; a model the catalog does not list keeps its id. */
|
|
9
|
+
export declare function canonicalModelName(id: string): string;
|
package/dist/models/canonical.js
CHANGED
|
@@ -1,3 +1,7 @@
|
|
|
1
1
|
import canonicalModels from "./canonical_models.json" with { type: "json" };
|
|
2
2
|
/** The canonical models Dari serves, from the monorepo's router catalog. */
|
|
3
3
|
export const CANONICAL_MODELS = canonicalModels;
|
|
4
|
+
/** A model's catalog name; a model the catalog does not list keeps its id. */
|
|
5
|
+
export function canonicalModelName(id) {
|
|
6
|
+
return CANONICAL_MODELS.find((model) => model.id === id)?.name ?? id;
|
|
7
|
+
}
|
package/dist/models/catalog.js
CHANGED
|
@@ -8,6 +8,7 @@ const PROVIDER_LABELS = {
|
|
|
8
8
|
fireworks: "Fireworks",
|
|
9
9
|
meta: "Meta",
|
|
10
10
|
xai: "xAI",
|
|
11
|
+
"opencode-go": "OpenCode Go",
|
|
11
12
|
dari: "Dari",
|
|
12
13
|
"amazon-bedrock": "Amazon Bedrock",
|
|
13
14
|
azure: "Microsoft Azure",
|
|
@@ -28,6 +29,9 @@ const PROVIDER_BASE_URLS = {
|
|
|
28
29
|
anthropic: "https://api.anthropic.com",
|
|
29
30
|
fireworks: "https://api.fireworks.ai/inference/v1",
|
|
30
31
|
xai: "https://api.x.ai/v1",
|
|
32
|
+
// A flat-rate plan for open models; each model keeps its own API path
|
|
33
|
+
// under https://opencode.ai/inference/go/, and this is chat completions.
|
|
34
|
+
"opencode-go": "https://opencode.ai/inference/go/openai/v1",
|
|
31
35
|
// Meta's Model API serves OpenAI Responses and Chat Completions here, and
|
|
32
36
|
// Anthropic Messages at https://api.meta.ai.
|
|
33
37
|
meta: "https://api.meta.ai/v1",
|
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { type RouterModelPrice } from "@mupt-ai/dari-router/policy-engine";
|
|
2
2
|
import type { ClientHarness, ResolvedRouterModelConfig, SubscriptionKind } from "../types.js";
|
|
3
3
|
/**
|
|
4
|
-
* Whether a plan may serve a model for this client:
|
|
5
|
-
* own provider's models, and only to the client its
|
|
4
|
+
* Whether a plan may serve a model executed by `provider` for this client:
|
|
5
|
+
* each plan serves only its own provider's models, and only to the client its
|
|
6
|
+
* provider allows.
|
|
6
7
|
*/
|
|
7
|
-
export declare function subscriptionServes(kind: SubscriptionKind,
|
|
8
|
+
export declare function subscriptionServes(kind: SubscriptionKind, provider: string, clientHarness: ClientHarness | undefined): boolean;
|
|
8
9
|
export declare function codexModelConfig(modelId: string, price: RouterModelPrice | null): ResolvedRouterModelConfig;
|
|
@@ -1,10 +1,13 @@
|
|
|
1
|
-
import { nativeModelId
|
|
1
|
+
import { nativeModelId } from "@mupt-ai/dari-router/policy-engine";
|
|
2
2
|
const CODEX_BACKEND_URL = "https://chatgpt.com/backend-api";
|
|
3
|
-
// The
|
|
3
|
+
// The execution providers whose models each kind of plan serves; a ChatGPT
|
|
4
|
+
// plan's OpenAI models execute as `openai-codex` once resolve points them at
|
|
5
|
+
// the Codex backend.
|
|
4
6
|
const SUBSCRIPTION_MODEL_PROVIDERS = {
|
|
5
|
-
openai_codex: "openai",
|
|
6
|
-
anthropic_claude_code: "anthropic",
|
|
7
|
-
meta_muse: "meta",
|
|
7
|
+
openai_codex: ["openai", "openai-codex"],
|
|
8
|
+
anthropic_claude_code: ["anthropic"],
|
|
9
|
+
meta_muse: ["meta"],
|
|
10
|
+
opencode_go: ["opencode-go"],
|
|
8
11
|
};
|
|
9
12
|
// The client each plan is limited to, as its provider limits it: a Claude Code
|
|
10
13
|
// plan serves only Claude Code, and a Muse Code plan only Muse Code.
|
|
@@ -13,11 +16,12 @@ const SUBSCRIPTION_CLIENTS = {
|
|
|
13
16
|
meta_muse: "muse_code",
|
|
14
17
|
};
|
|
15
18
|
/**
|
|
16
|
-
* Whether a plan may serve a model for this client:
|
|
17
|
-
* own provider's models, and only to the client its
|
|
19
|
+
* Whether a plan may serve a model executed by `provider` for this client:
|
|
20
|
+
* each plan serves only its own provider's models, and only to the client its
|
|
21
|
+
* provider allows.
|
|
18
22
|
*/
|
|
19
|
-
export function subscriptionServes(kind,
|
|
20
|
-
if (SUBSCRIPTION_MODEL_PROVIDERS[kind]
|
|
23
|
+
export function subscriptionServes(kind, provider, clientHarness) {
|
|
24
|
+
if (!SUBSCRIPTION_MODEL_PROVIDERS[kind].includes(provider))
|
|
21
25
|
return false;
|
|
22
26
|
const client = SUBSCRIPTION_CLIENTS[kind];
|
|
23
27
|
return client === undefined || clientHarness === client;
|
|
@@ -46,6 +46,9 @@ export type GatewayPlatform = {
|
|
|
46
46
|
/**
|
|
47
47
|
* Hold an exhausted personal subscription until it resets. Resolves whether
|
|
48
48
|
* another connected subscription for the same provider can serve a retry.
|
|
49
|
+
* A limit naming a `model` holds only that model on the subscription, which
|
|
50
|
+
* keeps serving the router's other models; it resolves whether the hold
|
|
51
|
+
* landed, since those models then serve a retry.
|
|
49
52
|
*/
|
|
50
53
|
markSubscriptionUnavailable(hold: SubscriptionHold): Promise<boolean>;
|
|
51
54
|
/**
|
|
@@ -6,5 +6,18 @@ export declare function readCodexUsage(args: {
|
|
|
6
6
|
now?: number;
|
|
7
7
|
fetch?: typeof fetch;
|
|
8
8
|
}): Promise<SubscriptionUsage | null>;
|
|
9
|
+
/**
|
|
10
|
+
* When a ChatGPT usage-limit refusal came from a per-model cap rather than the
|
|
11
|
+
* plan's own limit, that cap's reset; null when the plan itself is spent or
|
|
12
|
+
* the report names no spent cap. The report lists those caps as
|
|
13
|
+
* `additional_rate_limits` beside the plan's `rate_limit`.
|
|
14
|
+
*/
|
|
15
|
+
export declare function readCodexModelLimitReset(args: {
|
|
16
|
+
accessToken: string;
|
|
17
|
+
baseUrl?: string;
|
|
18
|
+
now?: Date;
|
|
19
|
+
fetch?: typeof fetch;
|
|
20
|
+
}): Promise<Date | null>;
|
|
21
|
+
export declare function codexModelLimitResetFromReport(report: unknown, now: Date): Date | null;
|
|
9
22
|
/** Every Codex window with a future reset, or null when the report has none. */
|
|
10
23
|
export declare function codexUsageFromReport(report: unknown, now: Date): SubscriptionUsage | null;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { CODEX_USAGE_WINDOWS, subscriptionUsageFromWindows } from "./subscription_limits.js";
|
|
1
|
+
import { CODEX_USAGE_WINDOWS, DEFAULT_USAGE_LIMIT_WINDOW_MS, subscriptionUsageFromWindows, } from "./subscription_limits.js";
|
|
2
2
|
// Codex calls run over a WebSocket that bypasses fetch, so a ChatGPT plan's
|
|
3
3
|
// usage never reaches the gateway as response headers. The ChatGPT backend's
|
|
4
4
|
// usage report (the endpoint behind the Codex CLI's /status) has the same
|
|
@@ -14,6 +14,50 @@ export async function readCodexUsage(args) {
|
|
|
14
14
|
if (last !== undefined && now - last < CODEX_USAGE_INTERVAL_MS)
|
|
15
15
|
return null;
|
|
16
16
|
readAt.set(args.credentialId, now);
|
|
17
|
+
return codexUsageFromReport(await fetchCodexUsageReport(args), new Date(now));
|
|
18
|
+
}
|
|
19
|
+
/**
|
|
20
|
+
* When a ChatGPT usage-limit refusal came from a per-model cap rather than the
|
|
21
|
+
* plan's own limit, that cap's reset; null when the plan itself is spent or
|
|
22
|
+
* the report names no spent cap. The report lists those caps as
|
|
23
|
+
* `additional_rate_limits` beside the plan's `rate_limit`.
|
|
24
|
+
*/
|
|
25
|
+
export async function readCodexModelLimitReset(args) {
|
|
26
|
+
return codexModelLimitResetFromReport(await fetchCodexUsageReport(args), args.now ?? new Date());
|
|
27
|
+
}
|
|
28
|
+
export function codexModelLimitResetFromReport(report, now) {
|
|
29
|
+
if (!isRecord(report) || limitSpent(report.rate_limit))
|
|
30
|
+
return null;
|
|
31
|
+
const spent = (Array.isArray(report.additional_rate_limits) ? report.additional_rate_limits : [])
|
|
32
|
+
.map((limit) => isRecord(limit) ? limit.rate_limit : undefined)
|
|
33
|
+
.filter(limitSpent);
|
|
34
|
+
if (spent.length === 0)
|
|
35
|
+
return null;
|
|
36
|
+
const resets = spent.flatMap((limit) => limitWindows(limit))
|
|
37
|
+
.filter((window) => window.used >= 100 && window.resetAt !== null && window.resetAt > now)
|
|
38
|
+
.map((window) => window.resetAt.getTime());
|
|
39
|
+
return new Date(resets.length > 0 ? Math.max(...resets) : now.getTime() + DEFAULT_USAGE_LIMIT_WINDOW_MS);
|
|
40
|
+
}
|
|
41
|
+
function limitSpent(limit) {
|
|
42
|
+
if (!isRecord(limit))
|
|
43
|
+
return false;
|
|
44
|
+
return limit.limit_reached === true || limit.allowed === false
|
|
45
|
+
|| limitWindows(limit).some((window) => window.used >= 100);
|
|
46
|
+
}
|
|
47
|
+
function limitWindows(limit) {
|
|
48
|
+
if (!isRecord(limit))
|
|
49
|
+
return [];
|
|
50
|
+
return CODEX_USAGE_WINDOWS.flatMap(([name]) => {
|
|
51
|
+
const window = limit[`${name}_window`];
|
|
52
|
+
if (!isRecord(window) || typeof window.used_percent !== "number")
|
|
53
|
+
return [];
|
|
54
|
+
return [{
|
|
55
|
+
used: window.used_percent,
|
|
56
|
+
resetAt: typeof window.reset_at === "number" ? new Date(window.reset_at * 1000) : null,
|
|
57
|
+
}];
|
|
58
|
+
});
|
|
59
|
+
}
|
|
60
|
+
async function fetchCodexUsageReport(args) {
|
|
17
61
|
const accountId = codexAccountId(args.accessToken);
|
|
18
62
|
const response = await (args.fetch ?? globalThis.fetch)(`${(args.baseUrl ?? DEFAULT_CODEX_BASE_URL).replace(/\/$/, "")}/wham/usage`, {
|
|
19
63
|
headers: {
|
|
@@ -25,7 +69,7 @@ export async function readCodexUsage(args) {
|
|
|
25
69
|
});
|
|
26
70
|
if (!response.ok)
|
|
27
71
|
throw new Error(`Codex usage report failed with status ${response.status}.`);
|
|
28
|
-
return
|
|
72
|
+
return await response.json();
|
|
29
73
|
}
|
|
30
74
|
/** Every Codex window with a future reset, or null when the report has none. */
|
|
31
75
|
export function codexUsageFromReport(report, now) {
|
|
@@ -12,8 +12,8 @@ import { runProviderAttemptPlan, } from "./provider_attempt_runner.js";
|
|
|
12
12
|
import { estimatedCancelUsage, NO_DELIVERED_OUTPUT, observeDeliveredOutput, } from "./cancel_estimate.js";
|
|
13
13
|
import { providerResponseCaptureFromError } from "./response_capture.js";
|
|
14
14
|
import { createStreamFinalizer } from "./stream_finalization.js";
|
|
15
|
-
import { readCodexUsage } from "./codex_usage.js";
|
|
16
|
-
import { detectSubscriptionUsageLimit, codexUsageLimitError, subscriptionOAuthProviderFor, subscriptionUsageFromHeaders, failureWithSubscriptionUsageLimit, retryAfterSeconds, subscriptionUsageLimitFromFailure, subscriptionSwitchedMessage, subscriptionUsageLimitMessage, } from "./subscription_limits.js";
|
|
15
|
+
import { readCodexModelLimitReset, readCodexUsage } from "./codex_usage.js";
|
|
16
|
+
import { detectSubscriptionUsageLimit, codexUsageLimitError, subscriptionOAuthProviderFor, subscriptionUsageFromHeaders, museSubscriptionUsage, failureWithSubscriptionUsageLimit, retryAfterSeconds, subscriptionUsageLimitFromFailure, subscriptionSwitchedMessage, subscriptionUsageLimitMessage, } from "./subscription_limits.js";
|
|
17
17
|
export async function executeNonStreaming(args) {
|
|
18
18
|
const result = await completeNonStreaming(args);
|
|
19
19
|
if (result.reportBarrierError !== undefined) {
|
|
@@ -418,14 +418,17 @@ function recordSettledFailure(reporter, choice, attempt, result) {
|
|
|
418
418
|
recordProviderAttempt(reporter, choice, attempt, result.kind === "customer_canceled" ? "canceled" : "error", result.kind, result.message);
|
|
419
419
|
}
|
|
420
420
|
async function providerFailedAttempt(message, latencyMs, execution, responseCapture) {
|
|
421
|
-
const
|
|
421
|
+
const detected = detectSubscriptionUsageLimit({
|
|
422
422
|
provider: execution.provider,
|
|
423
423
|
keySource: execution.providerKeySource,
|
|
424
|
+
model: execution.model,
|
|
424
425
|
captured: responseCapture?.last,
|
|
425
426
|
failure: message,
|
|
426
427
|
});
|
|
427
|
-
if (
|
|
428
|
+
if (detected === null) {
|
|
428
429
|
const status = responseCapture?.last?.status;
|
|
430
|
+
if (execution.providerKeySource === "subscription")
|
|
431
|
+
logUnclassifiedRefusal(execution, responseCapture);
|
|
429
432
|
// The customer's own key was refused: theirs to fix, not a gateway fault.
|
|
430
433
|
const rejected = execution.providerKeySource === "user" && (status === 401 || status === 403);
|
|
431
434
|
return {
|
|
@@ -437,10 +440,15 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
|
|
|
437
440
|
retryable: !isPromptPolicyRejection(message),
|
|
438
441
|
};
|
|
439
442
|
}
|
|
443
|
+
const limit = detected.oauthProvider === "openai_codex" && detected.model === undefined
|
|
444
|
+
&& execution.subscriptionUserId !== undefined
|
|
445
|
+
? await withCodexModelLimit(detected, execution)
|
|
446
|
+
: detected;
|
|
440
447
|
// Retrying an exhausted plan cannot succeed. The platform learns about it
|
|
441
448
|
// before this request returns so the next resolve already serves the
|
|
442
449
|
// user's next subscription, or the model's API credential when the router
|
|
443
|
-
// allows subscription API fallback for it.
|
|
450
|
+
// allows subscription API fallback for it. A limit on one model holds only
|
|
451
|
+
// that model, and the next resolve routes to the others.
|
|
444
452
|
const switched = execution.subscriptionUserId !== undefined
|
|
445
453
|
&& await holdSubscription({
|
|
446
454
|
userId: execution.subscriptionUserId,
|
|
@@ -448,8 +456,9 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
|
|
|
448
456
|
limit,
|
|
449
457
|
});
|
|
450
458
|
// Nothing reached the client yet, so the same request is retried on the
|
|
451
|
-
// next plan at once when the platform names it.
|
|
452
|
-
|
|
459
|
+
// next plan at once when the platform names it. The same plan still serves
|
|
460
|
+
// after a model limit, so there is no next plan to retry on.
|
|
461
|
+
const nextSubscription = switched && limit.model === undefined
|
|
453
462
|
? await nextSubscriptionFor(execution)
|
|
454
463
|
: undefined;
|
|
455
464
|
return {
|
|
@@ -495,6 +504,46 @@ function usageHasTokens(usage) {
|
|
|
495
504
|
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
496
505
|
});
|
|
497
506
|
}
|
|
507
|
+
// Codex's WebSocket transport carries no headers, and a refusal over HTTP may
|
|
508
|
+
// carry none of the per-limit families, so the usage report tells whether the
|
|
509
|
+
// plan or only this model's own cap is spent. Unknown keeps the plan hold.
|
|
510
|
+
async function withCodexModelLimit(limit, execution) {
|
|
511
|
+
try {
|
|
512
|
+
const resetsAt = await readCodexModelLimitReset({
|
|
513
|
+
accessToken: execution.apiKey,
|
|
514
|
+
baseUrl: execution.endpoint?.baseUrl ?? execution.config?.base_url ?? undefined,
|
|
515
|
+
});
|
|
516
|
+
if (resetsAt === null)
|
|
517
|
+
return limit;
|
|
518
|
+
return { ...limit, model: execution.model, resetsAt, reason: `ChatGPT usage limit for ${execution.model} reached.` };
|
|
519
|
+
}
|
|
520
|
+
catch (error) {
|
|
521
|
+
console.error("codex usage report for a usage limit failed", error);
|
|
522
|
+
return limit;
|
|
523
|
+
}
|
|
524
|
+
}
|
|
525
|
+
// A subscription refusal no rule recognizes may be a usage limit in a shape
|
|
526
|
+
// not seen yet (a new per-model cap). Log what identifies one, never content.
|
|
527
|
+
function logUnclassifiedRefusal(execution, responseCapture) {
|
|
528
|
+
const captured = responseCapture?.last;
|
|
529
|
+
if (captured === undefined || (captured.status !== 403 && captured.status !== 429))
|
|
530
|
+
return;
|
|
531
|
+
// Claude Code's per-minute limit, a known transient refusal.
|
|
532
|
+
if (captured.headers.get("anthropic-ratelimit-unified-status")?.startsWith("allowed"))
|
|
533
|
+
return;
|
|
534
|
+
const headers = {};
|
|
535
|
+
captured.headers.forEach((value, name) => {
|
|
536
|
+
if (/ratelimit|rate-limit|used-percent|reset|retry-after|limit-name/i.test(name))
|
|
537
|
+
headers[name] = value;
|
|
538
|
+
});
|
|
539
|
+
console.warn("unclassified subscription refusal", JSON.stringify({
|
|
540
|
+
provider: execution.provider,
|
|
541
|
+
model: execution.model,
|
|
542
|
+
status: captured.status,
|
|
543
|
+
headers,
|
|
544
|
+
body: captured.bodyText.slice(0, 500),
|
|
545
|
+
}));
|
|
546
|
+
}
|
|
498
547
|
function isPromptPolicyRejection(message) {
|
|
499
548
|
const text = providerFailureMessage(message).toLowerCase();
|
|
500
549
|
return text.includes("invalid prompt") && text.includes("usage policy");
|
|
@@ -545,16 +594,20 @@ function noteSubscriptionUsage(execution, responseCapture) {
|
|
|
545
594
|
const fromHeaders = headers === undefined
|
|
546
595
|
? null
|
|
547
596
|
: subscriptionUsageFromHeaders(execution.provider, execution.providerKeySource, headers);
|
|
597
|
+
const oauthProvider = subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource);
|
|
548
598
|
// Codex's WebSocket transport carries no headers; its usage report does.
|
|
599
|
+
// Muse Code's usage is the last event of its stream.
|
|
549
600
|
const usage = fromHeaders !== null
|
|
550
601
|
? Promise.resolve(fromHeaders)
|
|
551
|
-
:
|
|
602
|
+
: oauthProvider === "openai_codex"
|
|
552
603
|
? readCodexUsage({
|
|
553
604
|
credentialId,
|
|
554
605
|
accessToken: execution.apiKey,
|
|
555
606
|
baseUrl: execution.endpoint?.baseUrl ?? execution.config?.base_url ?? undefined,
|
|
556
607
|
})
|
|
557
|
-
:
|
|
608
|
+
: oauthProvider === "meta_muse" && responseCapture !== undefined
|
|
609
|
+
? responseCapture.streamedSubscriptionUsage.then((snapshot) => museSubscriptionUsage(snapshot, new Date()))
|
|
610
|
+
: Promise.resolve(null);
|
|
558
611
|
usage
|
|
559
612
|
.then((reported) => reported === null ? undefined : record({ userId, credentialId, usage: reported }))
|
|
560
613
|
.catch((error) => {
|
|
@@ -32,6 +32,9 @@ function keyCheckRequest(provider, key, endpoint) {
|
|
|
32
32
|
return { url: "https://openrouter.ai/api/v1/key", headers: bearer };
|
|
33
33
|
if (provider === "vercel-ai-gateway")
|
|
34
34
|
return { url: "https://ai-gateway.vercel.sh/v1/credits", headers: bearer };
|
|
35
|
+
// OpenCode Go's models list is public, so it cannot tell a bad key.
|
|
36
|
+
if (provider === "opencode-go")
|
|
37
|
+
return null;
|
|
35
38
|
}
|
|
36
39
|
const target = endpoint
|
|
37
40
|
?? getBuiltinModels(provider)?.[0];
|
package/dist/providers/pi.js
CHANGED
|
@@ -39,6 +39,11 @@ function piStreamSimple(model, context, options) {
|
|
|
39
39
|
const api = PI_APIS[String(model.api)];
|
|
40
40
|
if (!api)
|
|
41
41
|
throw new Error(`No Pi API implementation for ${String(model.api)}.`);
|
|
42
|
+
// The Anthropic SDK adds ANTHROPIC_CUSTOM_HEADERS from the process
|
|
43
|
+
// environment to every request. A gateway started from a Claude Code
|
|
44
|
+
// session inherits Dari's own `Authorization` there, which would replace
|
|
45
|
+
// the credential the gateway resolved; upstream headers are the gateway's.
|
|
46
|
+
delete process.env.ANTHROPIC_CUSTOM_HEADERS;
|
|
42
47
|
return api.streamSimple(model, normalizeContext(context), options);
|
|
43
48
|
}
|
|
44
49
|
export const pi = {
|
|
@@ -44,6 +44,14 @@ export function buildOptions(request, auth, selectedModel, model, pi, sessionId,
|
|
|
44
44
|
if (model.provider === "meta" && request.museCodeClientId !== undefined) {
|
|
45
45
|
headers["x-client-id"] = request.museCodeClientId;
|
|
46
46
|
}
|
|
47
|
+
// OpenCode Go serves coding agents that name themselves and send a stable
|
|
48
|
+
// session id; a generic SDK user agent reads as abuse.
|
|
49
|
+
// https://opencode.ai/docs/go/
|
|
50
|
+
if (model.provider === "opencode-go") {
|
|
51
|
+
headers["user-agent"] = "dari-gateway";
|
|
52
|
+
if (sessionId)
|
|
53
|
+
headers["x-opencode-session"] = sessionId;
|
|
54
|
+
}
|
|
47
55
|
// Pi's Anthropic transport honors compat.supportsTemperature; the OpenAI
|
|
48
56
|
// transports forward temperature regardless, so drop it here for models
|
|
49
57
|
// that reject it instead of failing the whole request.
|
|
@@ -18,6 +18,7 @@ type ProviderCallConfig = {
|
|
|
18
18
|
reasoningEffort: ReasoningEffort;
|
|
19
19
|
promptEstimate: PromptTokenEstimate | undefined;
|
|
20
20
|
endpoint?: ProviderEndpoint;
|
|
21
|
+
systemPromptSuffix?: string;
|
|
21
22
|
};
|
|
22
23
|
export type ProviderExecution = ProviderCallConfig & {
|
|
23
24
|
provider: Provider;
|
|
@@ -54,6 +55,7 @@ export declare function prepareProviderExecution(args: {
|
|
|
54
55
|
promptCacheKey?: string;
|
|
55
56
|
costEstimates?: readonly CandidateCostEstimate[];
|
|
56
57
|
tags?: RequestTags;
|
|
58
|
+
systemPromptSuffix?: string;
|
|
57
59
|
}): ProviderExecution;
|
|
58
60
|
export declare function startProviderCompletion(args: {
|
|
59
61
|
interaction: InteractionRequest;
|
|
@@ -8,8 +8,10 @@ import { scrubSecretValues } from "../telemetry/scrub.js";
|
|
|
8
8
|
import { usageContextFor, } from "../telemetry/usage.js";
|
|
9
9
|
import { awsRoleCredentials } from "./aws_assume_role.js";
|
|
10
10
|
import { attachProviderResponseCapture, createProviderResponseCapture, } from "./response_capture.js";
|
|
11
|
+
import { subscriptionOAuthProviderFor } from "./subscription_limits.js";
|
|
11
12
|
import { completeInteractionModel, streamInteractionModel, } from "./pi.js";
|
|
12
13
|
import { promptTokenEstimateFor } from "./cancel_estimate.js";
|
|
14
|
+
import { withSystemPromptSuffix } from "../interaction/system_prompt.js";
|
|
13
15
|
export function prepareProviderExecution(args) {
|
|
14
16
|
const model = args.decision.selectedModel;
|
|
15
17
|
const promptEstimate = promptTokenEstimateFor(args.costEstimates, model, args.decision.reasoningEffort);
|
|
@@ -44,6 +46,7 @@ export function prepareProviderExecution(args) {
|
|
|
44
46
|
: args.conversationId,
|
|
45
47
|
reasoningEffort: args.decision.reasoningEffort,
|
|
46
48
|
promptEstimate,
|
|
49
|
+
...(args.systemPromptSuffix ? { systemPromptSuffix: args.systemPromptSuffix } : {}),
|
|
47
50
|
...(supplied?.baseUrl || supplied?.headers
|
|
48
51
|
? { endpoint: { baseUrl: supplied.baseUrl, headers: supplied.headers } }
|
|
49
52
|
: {}),
|
|
@@ -97,9 +100,12 @@ export function startProviderCompletion(args) {
|
|
|
97
100
|
function responseCaptureFor(execution) {
|
|
98
101
|
// A subscription's failures carry its usage limit; a customer key's say
|
|
99
102
|
// whether the provider refused the key itself.
|
|
103
|
+
// Muse Code reports its plan's usage as the stream's last event.
|
|
100
104
|
return execution.providerKeySource === "managed"
|
|
101
105
|
? undefined
|
|
102
|
-
: createProviderResponseCapture(
|
|
106
|
+
: createProviderResponseCapture({
|
|
107
|
+
watchSubscriptionUsage: subscriptionOAuthProviderFor(execution.provider, execution.providerKeySource) === "meta_muse",
|
|
108
|
+
});
|
|
103
109
|
}
|
|
104
110
|
export async function startProviderStream(args) {
|
|
105
111
|
const providerStartedMs = Date.now();
|
|
@@ -114,7 +120,7 @@ export async function startProviderStream(args) {
|
|
|
114
120
|
try {
|
|
115
121
|
const providerStream = await streamInteractionModel({
|
|
116
122
|
model: args.execution.model,
|
|
117
|
-
request: args.interaction,
|
|
123
|
+
request: withSystemPromptSuffix(args.interaction, args.execution.systemPromptSuffix),
|
|
118
124
|
apiKey: args.execution.apiKey,
|
|
119
125
|
auth: await awsRoleCredentials.resolve(args.execution.auth),
|
|
120
126
|
pricing: args.execution.pricing,
|
|
@@ -193,7 +199,7 @@ async function completeProvider(args) {
|
|
|
193
199
|
const providerStartedAt = new Date();
|
|
194
200
|
const completion = await completeInteractionModel({
|
|
195
201
|
model: args.execution.model,
|
|
196
|
-
request: args.interaction,
|
|
202
|
+
request: withSystemPromptSuffix(args.interaction, args.execution.systemPromptSuffix),
|
|
197
203
|
apiKey: args.execution.apiKey,
|
|
198
204
|
auth: await awsRoleCredentials.resolve(args.execution.auth),
|
|
199
205
|
pricing: args.execution.pricing,
|
|
@@ -8,6 +8,7 @@ export type ProviderResponseCapture = {
|
|
|
8
8
|
fetch: ProviderFetch;
|
|
9
9
|
last: CapturedProviderResponse | undefined;
|
|
10
10
|
succeeded: Headers | undefined;
|
|
11
|
+
streamedSubscriptionUsage: Promise<unknown>;
|
|
11
12
|
};
|
|
12
13
|
/**
|
|
13
14
|
* A fetch wrapper that remembers the last failed provider response, and the
|
|
@@ -16,7 +17,9 @@ export type ProviderResponseCapture = {
|
|
|
16
17
|
* runtime, so this is the only place the status, rate-limit headers, and
|
|
17
18
|
* structured error body of a rejected call can still be read.
|
|
18
19
|
*/
|
|
19
|
-
export declare function createProviderResponseCapture(
|
|
20
|
+
export declare function createProviderResponseCapture(options?: {
|
|
21
|
+
watchSubscriptionUsage?: boolean;
|
|
22
|
+
}): ProviderResponseCapture;
|
|
20
23
|
/**
|
|
21
24
|
* A provider call that throws before returning a stream loses its capture with
|
|
22
25
|
* the started state, so the error carries it to the attempt runner instead.
|
|
@@ -1,3 +1,5 @@
|
|
|
1
|
+
const SUBSCRIPTION_USAGE_EVENT = "response.subscription_usage";
|
|
2
|
+
const MAX_SCANNED_LINE = 64 * 1024;
|
|
1
3
|
const CAPTURED_BODY_MAX_BYTES = 64 * 1024;
|
|
2
4
|
/**
|
|
3
5
|
* A fetch wrapper that remembers the last failed provider response, and the
|
|
@@ -6,15 +8,23 @@ const CAPTURED_BODY_MAX_BYTES = 64 * 1024;
|
|
|
6
8
|
* runtime, so this is the only place the status, rate-limit headers, and
|
|
7
9
|
* structured error body of a rejected call can still be read.
|
|
8
10
|
*/
|
|
9
|
-
export function createProviderResponseCapture() {
|
|
11
|
+
export function createProviderResponseCapture(options = {}) {
|
|
10
12
|
const capture = {
|
|
11
13
|
last: undefined,
|
|
12
14
|
succeeded: undefined,
|
|
15
|
+
streamedSubscriptionUsage: Promise.resolve(null),
|
|
13
16
|
fetch: async (input, init) => {
|
|
14
17
|
const response = await globalThis.fetch(input, init);
|
|
15
18
|
if (response.ok) {
|
|
16
19
|
capture.succeeded = response.headers;
|
|
17
|
-
|
|
20
|
+
if (options.watchSubscriptionUsage !== true
|
|
21
|
+
|| response.body === null
|
|
22
|
+
|| !response.headers.get("content-type")?.includes("text/event-stream")) {
|
|
23
|
+
return response;
|
|
24
|
+
}
|
|
25
|
+
const watched = watchSubscriptionUsage(response.body);
|
|
26
|
+
capture.streamedSubscriptionUsage = watched.usage;
|
|
27
|
+
return new Response(watched.body, response);
|
|
18
28
|
}
|
|
19
29
|
const bodyText = await readBodyPrefix(response.clone());
|
|
20
30
|
capture.last = { status: response.status, headers: response.headers, bodyText };
|
|
@@ -23,6 +33,75 @@ export function createProviderResponseCapture() {
|
|
|
23
33
|
};
|
|
24
34
|
return capture;
|
|
25
35
|
}
|
|
36
|
+
/**
|
|
37
|
+
* Passes a server-sent event stream through unchanged while watching for its
|
|
38
|
+
* subscription usage event. The usage resolves when the stream ends or is
|
|
39
|
+
* cancelled.
|
|
40
|
+
*/
|
|
41
|
+
function watchSubscriptionUsage(source) {
|
|
42
|
+
let found = null;
|
|
43
|
+
let settle = () => undefined;
|
|
44
|
+
const usage = new Promise((resolve) => { settle = resolve; });
|
|
45
|
+
const decoder = new TextDecoder();
|
|
46
|
+
const reader = source.getReader();
|
|
47
|
+
// The usage event is small; a longer line (an image, a large output item)
|
|
48
|
+
// is skipped rather than buffered.
|
|
49
|
+
let line = "";
|
|
50
|
+
let skipping = false;
|
|
51
|
+
const take = (complete) => {
|
|
52
|
+
if (!complete.startsWith("data:") || !complete.includes(SUBSCRIPTION_USAGE_EVENT))
|
|
53
|
+
return;
|
|
54
|
+
try {
|
|
55
|
+
const event = JSON.parse(complete.slice(5));
|
|
56
|
+
if (event.type === SUBSCRIPTION_USAGE_EVENT)
|
|
57
|
+
found = event.subscription ?? null;
|
|
58
|
+
}
|
|
59
|
+
catch {
|
|
60
|
+
// Not this event; the stream itself is the client's to parse.
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
const scan = (text) => {
|
|
64
|
+
const pieces = text.split("\n");
|
|
65
|
+
for (let index = 0; index < pieces.length; index += 1) {
|
|
66
|
+
if (!skipping)
|
|
67
|
+
line += pieces[index];
|
|
68
|
+
if (line.length > MAX_SCANNED_LINE) {
|
|
69
|
+
line = "";
|
|
70
|
+
skipping = true;
|
|
71
|
+
}
|
|
72
|
+
if (index < pieces.length - 1) {
|
|
73
|
+
if (!skipping)
|
|
74
|
+
take(line.trimEnd());
|
|
75
|
+
line = "";
|
|
76
|
+
skipping = false;
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
};
|
|
80
|
+
const body = new ReadableStream({
|
|
81
|
+
async pull(controller) {
|
|
82
|
+
try {
|
|
83
|
+
const { done, value } = await reader.read();
|
|
84
|
+
if (done) {
|
|
85
|
+
scan(decoder.decode() + "\n");
|
|
86
|
+
settle(found);
|
|
87
|
+
controller.close();
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
scan(decoder.decode(value, { stream: true }));
|
|
91
|
+
controller.enqueue(value);
|
|
92
|
+
}
|
|
93
|
+
catch (error) {
|
|
94
|
+
settle(found);
|
|
95
|
+
controller.error(error);
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
async cancel(reason) {
|
|
99
|
+
settle(found);
|
|
100
|
+
await reader.cancel(reason);
|
|
101
|
+
},
|
|
102
|
+
});
|
|
103
|
+
return { body, usage };
|
|
104
|
+
}
|
|
26
105
|
async function readBodyPrefix(response) {
|
|
27
106
|
try {
|
|
28
107
|
const text = await response.text();
|