@mupt-ai/dari-gateway 1.0.309 → 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 +69 -8
- 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 -5
- 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/provider_stream_outcome.d.ts +7 -0
- package/dist/runtime/provider_stream_outcome.js +9 -0
- 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/telemetry/report.js +6 -3
- 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 +77 -7
- 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 -5
- 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/provider_stream_outcome.ts +19 -0
- 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/telemetry/report.ts +6 -3
- 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).
|
|
@@ -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) {
|
|
@@ -2,7 +2,7 @@ import { HttpError } from "../http/errors.js";
|
|
|
2
2
|
import { piMessageToInteractionOutput } from "./pi_output.js";
|
|
3
3
|
import { captureOperationalError } from "../observability/errors.js";
|
|
4
4
|
import { CustomerDisconnectedError, customerCanceledProviderMessage, } from "../runtime/customer_disconnect.js";
|
|
5
|
-
import { isProviderFailureMessage, providerFailureFromCaught, providerFailureFromTerminal, providerFailureMessage, } from "../runtime/provider_stream_outcome.js";
|
|
5
|
+
import { credentialRejectionFromFailure, failureWithCredentialRejection, isProviderFailureMessage, providerFailureFromCaught, providerFailureFromTerminal, providerFailureMessage, } from "../runtime/provider_stream_outcome.js";
|
|
6
6
|
import { reportedExecution, } from "../runtime/runtime_reporter.js";
|
|
7
7
|
import { trackBackgroundTelemetry } from "../telemetry/background.js";
|
|
8
8
|
import { gatewayPlatform } from "../platform/platform.js";
|
|
@@ -12,7 +12,7 @@ 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";
|
|
15
|
+
import { readCodexModelLimitReset, readCodexUsage } from "./codex_usage.js";
|
|
16
16
|
import { detectSubscriptionUsageLimit, codexUsageLimitError, subscriptionOAuthProviderFor, subscriptionUsageFromHeaders, failureWithSubscriptionUsageLimit, retryAfterSeconds, subscriptionUsageLimitFromFailure, subscriptionSwitchedMessage, subscriptionUsageLimitMessage, } from "./subscription_limits.js";
|
|
17
17
|
export async function executeNonStreaming(args) {
|
|
18
18
|
const result = await completeNonStreaming(args);
|
|
@@ -248,6 +248,13 @@ async function throwProviderFailure(args) {
|
|
|
248
248
|
const codex = codexUsageLimitError(limit, accountsUrl);
|
|
249
249
|
throw new HttpError(429, subscriptionUsageLimitMessage(limit, accountsUrl), "subscription_usage_limit", undefined, { "retry-after": String(retryAfterSeconds(limit)), ...codex?.headers }, codex?.body);
|
|
250
250
|
}
|
|
251
|
+
const rejected = credentialRejectionFromFailure(result.failure);
|
|
252
|
+
if (rejected !== null) {
|
|
253
|
+
const accountsUrl = gatewayPlatform().accountsUrl;
|
|
254
|
+
throw new HttpError(502, `Your ${rejected.provider} API key was rejected (${rejected.status}): `
|
|
255
|
+
+ `${providerFailureMessage(result.failure)} `
|
|
256
|
+
+ (accountsUrl ? `Update it at ${accountsUrl}.` : "Update it with `dari accounts`."), "provider_credential_rejected");
|
|
257
|
+
}
|
|
251
258
|
throw new HttpError(502, providerFailureMessage(result.failure), "provider_execution_failed");
|
|
252
259
|
}
|
|
253
260
|
export async function prepareStreamingExecution(args) {
|
|
@@ -411,24 +418,37 @@ function recordSettledFailure(reporter, choice, attempt, result) {
|
|
|
411
418
|
recordProviderAttempt(reporter, choice, attempt, result.kind === "customer_canceled" ? "canceled" : "error", result.kind, result.message);
|
|
412
419
|
}
|
|
413
420
|
async function providerFailedAttempt(message, latencyMs, execution, responseCapture) {
|
|
414
|
-
const
|
|
421
|
+
const detected = detectSubscriptionUsageLimit({
|
|
415
422
|
provider: execution.provider,
|
|
416
423
|
keySource: execution.providerKeySource,
|
|
424
|
+
model: execution.model,
|
|
417
425
|
captured: responseCapture?.last,
|
|
418
426
|
failure: message,
|
|
419
427
|
});
|
|
420
|
-
if (
|
|
428
|
+
if (detected === null) {
|
|
429
|
+
const status = responseCapture?.last?.status;
|
|
430
|
+
if (execution.providerKeySource === "subscription")
|
|
431
|
+
logUnclassifiedRefusal(execution, responseCapture);
|
|
432
|
+
// The customer's own key was refused: theirs to fix, not a gateway fault.
|
|
433
|
+
const rejected = execution.providerKeySource === "user" && (status === 401 || status === 403);
|
|
421
434
|
return {
|
|
422
435
|
kind: "provider_failed",
|
|
423
|
-
message
|
|
436
|
+
message: rejected
|
|
437
|
+
? failureWithCredentialRejection(message, { provider: execution.provider, status })
|
|
438
|
+
: message,
|
|
424
439
|
latencyMs,
|
|
425
440
|
retryable: !isPromptPolicyRejection(message),
|
|
426
441
|
};
|
|
427
442
|
}
|
|
443
|
+
const limit = detected.oauthProvider === "openai_codex" && detected.model === undefined
|
|
444
|
+
&& execution.subscriptionUserId !== undefined
|
|
445
|
+
? await withCodexModelLimit(detected, execution)
|
|
446
|
+
: detected;
|
|
428
447
|
// Retrying an exhausted plan cannot succeed. The platform learns about it
|
|
429
448
|
// before this request returns so the next resolve already serves the
|
|
430
449
|
// user's next subscription, or the model's API credential when the router
|
|
431
|
-
// 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.
|
|
432
452
|
const switched = execution.subscriptionUserId !== undefined
|
|
433
453
|
&& await holdSubscription({
|
|
434
454
|
userId: execution.subscriptionUserId,
|
|
@@ -436,8 +456,9 @@ async function providerFailedAttempt(message, latencyMs, execution, responseCapt
|
|
|
436
456
|
limit,
|
|
437
457
|
});
|
|
438
458
|
// Nothing reached the client yet, so the same request is retried on the
|
|
439
|
-
// next plan at once when the platform names it.
|
|
440
|
-
|
|
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
|
|
441
462
|
? await nextSubscriptionFor(execution)
|
|
442
463
|
: undefined;
|
|
443
464
|
return {
|
|
@@ -483,6 +504,46 @@ function usageHasTokens(usage) {
|
|
|
483
504
|
return typeof value === "number" && Number.isFinite(value) && value > 0;
|
|
484
505
|
});
|
|
485
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
|
+
}
|
|
486
547
|
function isPromptPolicyRejection(message) {
|
|
487
548
|
const text = providerFailureMessage(message).toLowerCase();
|
|
488
549
|
return text.includes("invalid prompt") && text.includes("usage policy");
|
|
@@ -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;
|
|
@@ -10,6 +10,7 @@ import { awsRoleCredentials } from "./aws_assume_role.js";
|
|
|
10
10
|
import { attachProviderResponseCapture, createProviderResponseCapture, } from "./response_capture.js";
|
|
11
11
|
import { completeInteractionModel, streamInteractionModel, } from "./pi.js";
|
|
12
12
|
import { promptTokenEstimateFor } from "./cancel_estimate.js";
|
|
13
|
+
import { withSystemPromptSuffix } from "../interaction/system_prompt.js";
|
|
13
14
|
export function prepareProviderExecution(args) {
|
|
14
15
|
const model = args.decision.selectedModel;
|
|
15
16
|
const promptEstimate = promptTokenEstimateFor(args.costEstimates, model, args.decision.reasoningEffort);
|
|
@@ -44,6 +45,7 @@ export function prepareProviderExecution(args) {
|
|
|
44
45
|
: args.conversationId,
|
|
45
46
|
reasoningEffort: args.decision.reasoningEffort,
|
|
46
47
|
promptEstimate,
|
|
48
|
+
...(args.systemPromptSuffix ? { systemPromptSuffix: args.systemPromptSuffix } : {}),
|
|
47
49
|
...(supplied?.baseUrl || supplied?.headers
|
|
48
50
|
? { endpoint: { baseUrl: supplied.baseUrl, headers: supplied.headers } }
|
|
49
51
|
: {}),
|
|
@@ -95,9 +97,11 @@ export function startProviderCompletion(args) {
|
|
|
95
97
|
return { promise, customerAbort, responseCapture };
|
|
96
98
|
}
|
|
97
99
|
function responseCaptureFor(execution) {
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
100
|
+
// A subscription's failures carry its usage limit; a customer key's say
|
|
101
|
+
// whether the provider refused the key itself.
|
|
102
|
+
return execution.providerKeySource === "managed"
|
|
103
|
+
? undefined
|
|
104
|
+
: createProviderResponseCapture();
|
|
101
105
|
}
|
|
102
106
|
export async function startProviderStream(args) {
|
|
103
107
|
const providerStartedMs = Date.now();
|
|
@@ -112,7 +116,7 @@ export async function startProviderStream(args) {
|
|
|
112
116
|
try {
|
|
113
117
|
const providerStream = await streamInteractionModel({
|
|
114
118
|
model: args.execution.model,
|
|
115
|
-
request: args.interaction,
|
|
119
|
+
request: withSystemPromptSuffix(args.interaction, args.execution.systemPromptSuffix),
|
|
116
120
|
apiKey: args.execution.apiKey,
|
|
117
121
|
auth: await awsRoleCredentials.resolve(args.execution.auth),
|
|
118
122
|
pricing: args.execution.pricing,
|
|
@@ -191,7 +195,7 @@ async function completeProvider(args) {
|
|
|
191
195
|
const providerStartedAt = new Date();
|
|
192
196
|
const completion = await completeInteractionModel({
|
|
193
197
|
model: args.execution.model,
|
|
194
|
-
request: args.interaction,
|
|
198
|
+
request: withSystemPromptSuffix(args.interaction, args.execution.systemPromptSuffix),
|
|
195
199
|
apiKey: args.execution.apiKey,
|
|
196
200
|
auth: await awsRoleCredentials.resolve(args.execution.auth),
|
|
197
201
|
pricing: args.execution.pricing,
|
|
@@ -1,10 +1,11 @@
|
|
|
1
1
|
import type { ProviderKeySource } from "../types.js";
|
|
2
2
|
import type { CapturedProviderResponse } from "./response_capture.js";
|
|
3
|
-
export type SubscriptionOAuthProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse";
|
|
3
|
+
export type SubscriptionOAuthProvider = "anthropic_claude_code" | "openai_codex" | "meta_muse" | "opencode_go";
|
|
4
4
|
export type SubscriptionUsageLimit = {
|
|
5
5
|
oauthProvider: SubscriptionOAuthProvider;
|
|
6
6
|
resetsAt: Date;
|
|
7
7
|
reason: string;
|
|
8
|
+
model?: string;
|
|
8
9
|
switched?: boolean;
|
|
9
10
|
};
|
|
10
11
|
/** One quota window of a plan: its length, share used (0 to 1), and reset. */
|
|
@@ -43,13 +44,15 @@ export declare function subscriptionOAuthProviderFor(provider: string, keySource
|
|
|
43
44
|
* answers 429 with the unified rate-limit headers; the ChatGPT backend answers
|
|
44
45
|
* 429 with a structured `error.code` and `resets_at`. Meta documents no
|
|
45
46
|
* usage-limit signature for Muse Code plans, so any 429 on one holds it until
|
|
46
|
-
* the reset Meta gives, if any.
|
|
47
|
+
* the reset Meta gives, if any. OpenCode Go names its refusal
|
|
48
|
+
* `GoUsageLimitError`. The Codex WebSocket
|
|
47
49
|
* transport bypasses fetch, so its usage-limit error only survives as message
|
|
48
50
|
* text and is matched there without a reset time.
|
|
49
51
|
*/
|
|
50
52
|
export declare function detectSubscriptionUsageLimit(args: {
|
|
51
53
|
provider: string;
|
|
52
54
|
keySource: ProviderKeySource;
|
|
55
|
+
model: string;
|
|
53
56
|
captured: CapturedProviderResponse | undefined;
|
|
54
57
|
failure: Record<string, unknown>;
|
|
55
58
|
now?: Date;
|