@mupt-ai/dari-gateway 1.0.361 → 1.0.363
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/dist/ingress/anthropic_messages.js +18 -25
- package/dist/ingress/chat_completions.js +10 -17
- package/dist/ingress/claude_code/request_context.d.ts +2 -0
- package/dist/ingress/claude_code/request_context.js +11 -0
- package/dist/ingress/client_harness.d.ts +2 -1
- package/dist/ingress/client_harness.js +31 -4
- package/dist/ingress/codex.js +9 -21
- package/dist/ingress/harness_request.d.ts +27 -0
- package/dist/ingress/harness_request.js +57 -0
- package/dist/providers/model_capabilities.js +19 -1
- package/dist/providers/provider_call.js +3 -1
- package/dist/self_host/subscriptions/http.js +12 -2
- package/dist/self_host/subscriptions/store.js +7 -11
- package/package.json +2 -2
- package/src/ingress/anthropic_messages.ts +18 -36
- package/src/ingress/chat_completions.ts +10 -25
- package/src/ingress/claude_code/request_context.ts +17 -0
- package/src/ingress/client_harness.ts +31 -4
- package/src/ingress/codex.ts +9 -27
- package/src/ingress/harness_request.ts +91 -0
- package/src/providers/model_capabilities.ts +20 -1
- package/src/providers/provider_call.ts +3 -1
- package/src/self_host/subscriptions/http.ts +11 -2
- package/src/self_host/subscriptions/store.ts +8 -11
|
@@ -8,13 +8,10 @@ import { captureRequestError } from "../observability/errors.js";
|
|
|
8
8
|
import { anthropicMessagesToInteraction } from "../protocol/input/anthropic_messages.js";
|
|
9
9
|
import { CANONICAL_ROUTER_MODEL, explicitModelId, isLinkToken, linkTokenModel } from "../protocol/input/router_model.js";
|
|
10
10
|
import { handleRoutedCompletion } from "../runtime/routed_completion.js";
|
|
11
|
-
import {
|
|
12
|
-
import { claimedClientHarness } from "./client_harness.js";
|
|
13
|
-
import { claudeCodeConversationIdentity, piRequestContext, } from "../runtime/harness_identity/index.js";
|
|
11
|
+
import { harnessRequest } from "./harness_request.js";
|
|
14
12
|
import { parseJsonRequest } from "./json.js";
|
|
15
13
|
import { anthropicWebSearchTool } from "../interaction/capabilities.js";
|
|
16
14
|
import { isBackgroundRequest } from "../interaction/types.js";
|
|
17
|
-
const LEGACY_CLAUDE_CODE_BETA = "claude-code-20250219";
|
|
18
15
|
const SAFEGUARDS_BETA_PREFIX = "dangerous-tool-use-";
|
|
19
16
|
const CONTEXT_MANAGEMENT_BETA_PREFIX = "context-management-";
|
|
20
17
|
export async function handleAnthropicMessages(request, routerId, selectorBackend) {
|
|
@@ -22,13 +19,17 @@ export async function handleAnthropicMessages(request, routerId, selectorBackend
|
|
|
22
19
|
const apiKey = anthropicToken(request.headers);
|
|
23
20
|
const rawPayload = await parseJsonRequest(request);
|
|
24
21
|
const interaction = anthropicMessagesToInteraction({ ...rawPayload, model: linkTokenModel(apiKey, rawPayload.model) });
|
|
25
|
-
const isClaudeCode = isClaudeCodeRequest(request.headers);
|
|
26
|
-
const anthropicSafeguards = safeguardsFrom(rawPayload, request.headers);
|
|
27
|
-
const anthropicContextManagement = contextManagementFrom(rawPayload, request.headers);
|
|
28
22
|
// Pi's turns arrive as chat completions; the Dari extension's web search
|
|
29
23
|
// tool sends its search here, marked as Pi's.
|
|
30
|
-
const
|
|
31
|
-
|
|
24
|
+
const harness = harnessRequest(request.headers, {
|
|
25
|
+
sourceProtocol: "anthropic_messages",
|
|
26
|
+
payload: rawPayload,
|
|
27
|
+
promptCacheKey: interaction.promptCacheKey,
|
|
28
|
+
});
|
|
29
|
+
const isClaudeCode = harness.clientHarness === "claude_code";
|
|
30
|
+
const agentContext = harness.agentContext;
|
|
31
|
+
const anthropicSafeguards = safeguardsFrom(rawPayload, request.headers);
|
|
32
|
+
const anthropicContextManagement = contextManagementFrom(rawPayload, request.headers);
|
|
32
33
|
// Claude Code runs a web search as a background request that names one of
|
|
33
34
|
// the session's models, and Pi's search tool as one that asks for routing.
|
|
34
35
|
// Like other background work, Dari serves it on the cheapest model that
|
|
@@ -55,7 +56,12 @@ export async function handleAnthropicMessages(request, routerId, selectorBackend
|
|
|
55
56
|
? { requestPurpose: "tool_continuation" } : {}),
|
|
56
57
|
claudeCodeUserAgent: request.headers.get("user-agent").trim(),
|
|
57
58
|
}
|
|
58
|
-
: {
|
|
59
|
+
: {
|
|
60
|
+
...forwarded,
|
|
61
|
+
...(agentContext === undefined ? {} : { agentContext }),
|
|
62
|
+
...(harness.requestPurpose === undefined ? {} : { requestPurpose: harness.requestPurpose }),
|
|
63
|
+
...(harness.museCodeClientId === undefined ? {} : { museCodeClientId: harness.museCodeClientId }),
|
|
64
|
+
};
|
|
59
65
|
return await handleRoutedCompletion({
|
|
60
66
|
request,
|
|
61
67
|
routerId,
|
|
@@ -65,12 +71,8 @@ export async function handleAnthropicMessages(request, routerId, selectorBackend
|
|
|
65
71
|
streamBody: anthropicMessagesSseStream,
|
|
66
72
|
errorResponse: anthropicErrorResponse,
|
|
67
73
|
selectorBackend,
|
|
68
|
-
clientHarness:
|
|
69
|
-
|
|
70
|
-
: claimedClientHarness(request.headers),
|
|
71
|
-
harnessConversationIdentity: isClaudeCode
|
|
72
|
-
? claudeCodeConversationIdentity(request.headers, payload.promptCacheKey)
|
|
73
|
-
: undefined,
|
|
74
|
+
clientHarness: harness.clientHarness,
|
|
75
|
+
harnessConversationIdentity: harness.conversationIdentity,
|
|
74
76
|
});
|
|
75
77
|
}
|
|
76
78
|
catch (error) {
|
|
@@ -123,15 +125,6 @@ function anthropicBetas(headers) {
|
|
|
123
125
|
.map((value) => value.trim().toLowerCase())
|
|
124
126
|
.filter(Boolean));
|
|
125
127
|
}
|
|
126
|
-
function isClaudeCodeRequest(headers) {
|
|
127
|
-
const userAgent = headers.get("user-agent")?.trim().toLowerCase() ?? "";
|
|
128
|
-
const app = headers.get("x-app")?.trim().toLowerCase();
|
|
129
|
-
const betas = anthropicBetas(headers);
|
|
130
|
-
return (userAgent.startsWith("claude-cli/") &&
|
|
131
|
-
(app === "cli" || app === "cli-bg") &&
|
|
132
|
-
(Boolean(headers.get("x-claude-code-session-id")?.trim()) ||
|
|
133
|
-
betas.has(LEGACY_CLAUDE_CODE_BETA)));
|
|
134
|
-
}
|
|
135
128
|
// Dari-specific codes clients act on; every other code stays internal.
|
|
136
129
|
const CLIENT_VISIBLE_ERROR_CODES = new Set([
|
|
137
130
|
...LINK_GRANT_ERROR_CODES,
|
|
@@ -5,10 +5,8 @@ import { chatCompletionResponse, chatCompletionsSseStream } from "../protocol/ou
|
|
|
5
5
|
import { chatCompletionsToInteraction } from "../protocol/input/chat_completions.js";
|
|
6
6
|
import { linkTokenModel } from "../protocol/input/router_model.js";
|
|
7
7
|
import { handleRoutedCompletion } from "../runtime/routed_completion.js";
|
|
8
|
-
import {
|
|
9
|
-
import { claimedClientHarness } from "./client_harness.js";
|
|
8
|
+
import { harnessRequest } from "./harness_request.js";
|
|
10
9
|
import { parseJsonRequest } from "./json.js";
|
|
11
|
-
import { museCodeClientId } from "./muse_code.js";
|
|
12
10
|
export async function handleChatCompletions(request, routerId, selectorBackend) {
|
|
13
11
|
try {
|
|
14
12
|
const apiKey = bearerToken(request.headers);
|
|
@@ -18,31 +16,26 @@ export async function handleChatCompletions(request, routerId, selectorBackend)
|
|
|
18
16
|
model: linkTokenModel(apiKey, payload.model),
|
|
19
17
|
source_protocol: "openai_chat",
|
|
20
18
|
});
|
|
21
|
-
const
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
// so the Dari CLI sets them up to name themselves.
|
|
27
|
-
const clientHarness = museClientId !== undefined ? "muse_code"
|
|
28
|
-
: piContext !== undefined ? "pi"
|
|
29
|
-
: openCodeContext !== undefined ? "opencode"
|
|
30
|
-
: claimedClientHarness(request.headers);
|
|
19
|
+
const harness = harnessRequest(request.headers, {
|
|
20
|
+
sourceProtocol: "openai_chat",
|
|
21
|
+
payload: payload,
|
|
22
|
+
promptCacheKey: payload.prompt_cache_key,
|
|
23
|
+
});
|
|
31
24
|
return await handleRoutedCompletion({
|
|
32
25
|
request,
|
|
33
26
|
routerId,
|
|
34
27
|
apiKey,
|
|
35
28
|
payload: {
|
|
36
29
|
...interaction,
|
|
37
|
-
...(agentContext === undefined ? {} : { agentContext }),
|
|
38
|
-
...(
|
|
30
|
+
...(harness.agentContext === undefined ? {} : { agentContext: harness.agentContext }),
|
|
31
|
+
...(harness.museCodeClientId === undefined ? {} : { museCodeClientId: harness.museCodeClientId }),
|
|
39
32
|
},
|
|
40
33
|
responseBody: chatCompletionResponse,
|
|
41
34
|
streamBody: chatCompletionsSseStream,
|
|
42
35
|
errorResponse,
|
|
43
36
|
selectorBackend,
|
|
44
|
-
clientHarness,
|
|
45
|
-
harnessConversationIdentity:
|
|
37
|
+
clientHarness: harness.clientHarness,
|
|
38
|
+
harnessConversationIdentity: harness.conversationIdentity,
|
|
46
39
|
});
|
|
47
40
|
}
|
|
48
41
|
catch (error) {
|
|
@@ -1,2 +1,4 @@
|
|
|
1
1
|
import type { AgentRequestContext } from "../../interaction/types.js";
|
|
2
|
+
/** Whether a request carries Claude Code's own headers. */
|
|
3
|
+
export declare function isClaudeCodeRequest(headers: Headers): boolean;
|
|
2
4
|
export declare function claudeCodeRequestContext(headers: Headers): AgentRequestContext;
|
|
@@ -2,6 +2,17 @@ import { HttpError } from "../../http/errors.js";
|
|
|
2
2
|
const REQUEST_CLASSES = new Set([
|
|
3
3
|
"main", "subagent", "workflow", "auxiliary", "compaction", "side_reply",
|
|
4
4
|
]);
|
|
5
|
+
const LEGACY_CLAUDE_CODE_BETA = "claude-code-20250219";
|
|
6
|
+
/** Whether a request carries Claude Code's own headers. */
|
|
7
|
+
export function isClaudeCodeRequest(headers) {
|
|
8
|
+
const userAgent = headers.get("user-agent")?.trim().toLowerCase() ?? "";
|
|
9
|
+
const app = headers.get("x-app")?.trim().toLowerCase();
|
|
10
|
+
const betas = (headers.get("anthropic-beta") ?? "").toLowerCase().split(",").map((beta) => beta.trim());
|
|
11
|
+
return (userAgent.startsWith("claude-cli/") &&
|
|
12
|
+
(app === "cli" || app === "cli-bg") &&
|
|
13
|
+
(Boolean(headers.get("x-claude-code-session-id")?.trim()) ||
|
|
14
|
+
betas.includes(LEGACY_CLAUDE_CODE_BETA)));
|
|
15
|
+
}
|
|
5
16
|
// These are client-supplied routing hints, not authentication claims. Never
|
|
6
17
|
// infer them from prompt text: a user can legitimately paste any such prompt.
|
|
7
18
|
export function claudeCodeRequestContext(headers) {
|
|
@@ -3,7 +3,8 @@ export declare const CLIENT_HARNESS_HEADER = "x-dari-client-harness";
|
|
|
3
3
|
export declare const CLIENT_HARNESSES: readonly string[];
|
|
4
4
|
/**
|
|
5
5
|
* The headers of `CLIENT_HEADERS` the request carries, as the client sent
|
|
6
|
-
* them, so hosted Dari serving it for a connected gateway sees the same
|
|
6
|
+
* them, so hosted Dari serving it for a connected gateway sees the same
|
|
7
|
+
* agent, session, and kind of request.
|
|
7
8
|
*/
|
|
8
9
|
export declare function clientHeaders(headers: Headers): Record<string, string>;
|
|
9
10
|
/**
|
|
@@ -8,12 +8,39 @@ export const CLIENT_HARNESSES = [
|
|
|
8
8
|
"openclaw",
|
|
9
9
|
"hermes",
|
|
10
10
|
];
|
|
11
|
-
// The headers a coding agent
|
|
12
|
-
//
|
|
13
|
-
|
|
11
|
+
// The headers a coding agent describes itself and each request with: which
|
|
12
|
+
// agent it is, its session, and what the request is for. harness_request.ts
|
|
13
|
+
// reads every one of them.
|
|
14
|
+
const CLIENT_HEADERS = [
|
|
15
|
+
// Claude Code
|
|
16
|
+
"user-agent",
|
|
17
|
+
"x-app",
|
|
18
|
+
"anthropic-beta",
|
|
19
|
+
"x-claude-code-session-id",
|
|
20
|
+
"x-claude-code-request-class",
|
|
21
|
+
"x-claude-code-agent-id",
|
|
22
|
+
"x-claude-code-parent-agent-id",
|
|
23
|
+
"x-claude-code-agent-type",
|
|
24
|
+
// Codex
|
|
25
|
+
"x-codex-turn-metadata",
|
|
26
|
+
"thread-id",
|
|
27
|
+
// Muse Code
|
|
28
|
+
"x-client-id",
|
|
29
|
+
"x-tbh-thread-id",
|
|
30
|
+
// OpenCode, with the `dari opencode` plugin's request kind and agent
|
|
31
|
+
"x-opencode-session-id",
|
|
32
|
+
"x-opencode-parent-session-id",
|
|
33
|
+
"x-opencode-request-kind",
|
|
34
|
+
"x-opencode-agent",
|
|
35
|
+
"x-session-affinity",
|
|
36
|
+
// Pi
|
|
37
|
+
"x-pi-session-id",
|
|
38
|
+
"x-pi-request-kind",
|
|
39
|
+
];
|
|
14
40
|
/**
|
|
15
41
|
* The headers of `CLIENT_HEADERS` the request carries, as the client sent
|
|
16
|
-
* them, so hosted Dari serving it for a connected gateway sees the same
|
|
42
|
+
* them, so hosted Dari serving it for a connected gateway sees the same
|
|
43
|
+
* agent, session, and kind of request.
|
|
17
44
|
*/
|
|
18
45
|
export function clientHeaders(headers) {
|
|
19
46
|
const found = {};
|
package/dist/ingress/codex.js
CHANGED
|
@@ -5,48 +5,36 @@ import { captureRequestError } from "../observability/errors.js";
|
|
|
5
5
|
import { openAIResponsesResponse } from "../protocol/output/openai_responses.js";
|
|
6
6
|
import { openAIResponsesSseStream } from "../protocol/output/openai_responses_stream.js";
|
|
7
7
|
import { openAIResponsesToInteraction } from "../protocol/input/openai_responses.js";
|
|
8
|
-
import { claimedClientHarness } from "./client_harness.js";
|
|
9
8
|
import { codexModelsEtag } from "./codex_models.js";
|
|
9
|
+
import { harnessRequest } from "./harness_request.js";
|
|
10
10
|
import { parseJsonRequest } from "./json.js";
|
|
11
|
-
import { museCodeClientId } from "./muse_code.js";
|
|
12
11
|
import { handleRoutedCompletion } from "../runtime/routed_completion.js";
|
|
13
|
-
import { codexConversationIdentity, codexRequestPurpose, codexRequestContext, museCodeConversationIdentity, piRequestContext, } from "../runtime/harness_identity/index.js";
|
|
14
12
|
export async function handleResponses(request, routerId, selectorBackend) {
|
|
15
13
|
try {
|
|
16
14
|
const apiKey = bearerToken(request.headers);
|
|
17
15
|
const rawPayload = await parseJsonRequest(request);
|
|
18
16
|
const interaction = openAIResponsesToInteraction({ ...rawPayload, model: linkTokenModel(apiKey, rawPayload.model) });
|
|
19
|
-
const requestPurpose = codexRequestPurpose(request.headers, rawPayload);
|
|
20
|
-
const codexContext = codexRequestContext(request.headers, rawPayload);
|
|
21
17
|
// Pi's turns arrive as chat completions; the Dari extension's web search
|
|
22
18
|
// tool sends an OpenAI hosted search here, marked as Pi's.
|
|
23
|
-
const
|
|
24
|
-
const agentContext = codexContext ?? piContext;
|
|
25
|
-
const museClientId = museCodeClientId(request.headers);
|
|
19
|
+
const harness = harnessRequest(request.headers, { sourceProtocol: "openai_responses", payload: rawPayload });
|
|
26
20
|
const payload = {
|
|
27
21
|
...interaction,
|
|
28
|
-
...(requestPurpose === undefined ? {} : { requestPurpose }),
|
|
29
|
-
...(agentContext === undefined ? {} : { agentContext }),
|
|
30
|
-
...(
|
|
22
|
+
...(harness.requestPurpose === undefined ? {} : { requestPurpose: harness.requestPurpose }),
|
|
23
|
+
...(harness.agentContext === undefined ? {} : { agentContext: harness.agentContext }),
|
|
24
|
+
...(harness.museCodeClientId === undefined ? {} : { museCodeClientId: harness.museCodeClientId }),
|
|
31
25
|
};
|
|
32
|
-
const codexIdentity = codexConversationIdentity(request.headers, rawPayload);
|
|
33
26
|
// Codex and Muse Code apply their session effort to custom model
|
|
34
27
|
// providers. That preference describes a direct model, not a heterogeneous
|
|
35
28
|
// router, so let Dari select the reasoning effort for their routed turns;
|
|
36
29
|
// a `dari/model/<id>` keeps the chosen effort. Parsing above still
|
|
37
30
|
// validates malformed Responses reasoning controls.
|
|
38
|
-
const
|
|
39
|
-
if (
|
|
31
|
+
const sessionEffort = harness.conversationIdentity?.kind === "codex_thread" || harness.museCodeClientId !== undefined;
|
|
32
|
+
if (sessionEffort && explicitModelId(payload.model) === null) {
|
|
40
33
|
// Keep only an explicit thinking-off; a session effort must not force thinking on.
|
|
41
34
|
payload.reasoning = payload.reasoning?.enabled === false ? { enabled: false } : undefined;
|
|
42
35
|
}
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
const clientHarness = museClientId !== undefined ? "muse_code"
|
|
46
|
-
// Codex describes every request in its turn metadata.
|
|
47
|
-
: codexContext !== undefined ? "codex"
|
|
48
|
-
: piContext !== undefined ? "pi"
|
|
49
|
-
: claimedClientHarness(request.headers);
|
|
36
|
+
const clientHarness = harness.clientHarness;
|
|
37
|
+
const harnessConversationIdentity = harness.conversationIdentity;
|
|
50
38
|
return await handleRoutedCompletion({
|
|
51
39
|
request,
|
|
52
40
|
routerId,
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { AgentRequestContext, InteractionRequestPurpose, SourceProtocol } from "../interaction/types.js";
|
|
2
|
+
import { type HarnessConversationIdentity } from "../runtime/harness_identity/index.js";
|
|
3
|
+
import type { ClientHarness } from "../types.js";
|
|
4
|
+
/** The coding agent a request comes from, and what the agent says of it. */
|
|
5
|
+
export type HarnessRequest = {
|
|
6
|
+
clientHarness?: ClientHarness;
|
|
7
|
+
agentContext?: AgentRequestContext;
|
|
8
|
+
conversationIdentity?: HarnessConversationIdentity;
|
|
9
|
+
requestPurpose?: InteractionRequestPurpose;
|
|
10
|
+
museCodeClientId?: string;
|
|
11
|
+
};
|
|
12
|
+
/**
|
|
13
|
+
* Read the coding agent from its own headers.
|
|
14
|
+
*
|
|
15
|
+
* An agent speaks one API, but its headers reach two more: a gateway
|
|
16
|
+
* connected to hosted Dari has hosted Dari serve a model over that model's
|
|
17
|
+
* API (Anthropic's for Claude, Responses for the rest), with the agent's
|
|
18
|
+
* headers passed on (`CLIENT_HEADERS`). So Claude Code's headers arrive on
|
|
19
|
+
* the Responses API when it runs a GPT model, and OpenCode's on Anthropic's
|
|
20
|
+
* when it runs Claude, and each must still be the same agent, request class,
|
|
21
|
+
* and session. Chat completions only ever carries the agents that speak it.
|
|
22
|
+
*/
|
|
23
|
+
export declare function harnessRequest(headers: Headers, body: {
|
|
24
|
+
sourceProtocol: SourceProtocol;
|
|
25
|
+
payload: Record<string, unknown>;
|
|
26
|
+
promptCacheKey?: string;
|
|
27
|
+
}): HarnessRequest;
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import { chatCompletionsConversationIdentity, claudeCodeConversationIdentity, codexConversationIdentity, codexRequestContext, codexRequestPurpose, museCodeConversationIdentity, openCodeRequestContext, piRequestContext, } from "../runtime/harness_identity/index.js";
|
|
2
|
+
import { claudeCodeRequestContext, isClaudeCodeRequest } from "./claude_code/request_context.js";
|
|
3
|
+
import { claimedClientHarness } from "./client_harness.js";
|
|
4
|
+
import { museCodeClientId } from "./muse_code.js";
|
|
5
|
+
/**
|
|
6
|
+
* Read the coding agent from its own headers.
|
|
7
|
+
*
|
|
8
|
+
* An agent speaks one API, but its headers reach two more: a gateway
|
|
9
|
+
* connected to hosted Dari has hosted Dari serve a model over that model's
|
|
10
|
+
* API (Anthropic's for Claude, Responses for the rest), with the agent's
|
|
11
|
+
* headers passed on (`CLIENT_HEADERS`). So Claude Code's headers arrive on
|
|
12
|
+
* the Responses API when it runs a GPT model, and OpenCode's on Anthropic's
|
|
13
|
+
* when it runs Claude, and each must still be the same agent, request class,
|
|
14
|
+
* and session. Chat completions only ever carries the agents that speak it.
|
|
15
|
+
*/
|
|
16
|
+
export function harnessRequest(headers, body) {
|
|
17
|
+
const chat = body.sourceProtocol === "openai_chat";
|
|
18
|
+
if (!chat && isClaudeCodeRequest(headers)) {
|
|
19
|
+
return {
|
|
20
|
+
clientHarness: "claude_code",
|
|
21
|
+
agentContext: claudeCodeRequestContext(headers),
|
|
22
|
+
conversationIdentity: claudeCodeConversationIdentity(headers,
|
|
23
|
+
// Only Claude Code's own request body names its session.
|
|
24
|
+
body.sourceProtocol === "anthropic_messages" ? body.promptCacheKey : undefined),
|
|
25
|
+
};
|
|
26
|
+
}
|
|
27
|
+
const museClientId = museCodeClientId(headers);
|
|
28
|
+
// Codex describes every request in its turn metadata.
|
|
29
|
+
const codexContext = chat ? undefined : codexRequestContext(headers, body.payload);
|
|
30
|
+
const piContext = codexContext === undefined ? piRequestContext(headers) : undefined;
|
|
31
|
+
const openCodeContext = openCodeRequestContext(headers);
|
|
32
|
+
const agentContext = codexContext ?? piContext ?? openCodeContext;
|
|
33
|
+
const requestPurpose = chat ? undefined : codexRequestPurpose(headers, body.payload);
|
|
34
|
+
// Any chat completions caller may name its session; on the other APIs only
|
|
35
|
+
// Pi and OpenCode, whose own headers do.
|
|
36
|
+
const session = chat || piContext !== undefined || openCodeContext !== undefined
|
|
37
|
+
? chatCompletionsConversationIdentity(headers, chat ? body.promptCacheKey : undefined)
|
|
38
|
+
: undefined;
|
|
39
|
+
const conversationIdentity = chat ? session
|
|
40
|
+
: codexConversationIdentity(headers, body.payload)
|
|
41
|
+
?? (museClientId === undefined ? undefined : museCodeConversationIdentity(headers))
|
|
42
|
+
?? session;
|
|
43
|
+
// OpenClaw and Hermes send nothing of their own that tells them apart, so
|
|
44
|
+
// the Dari CLI sets them up to name themselves.
|
|
45
|
+
const clientHarness = museClientId !== undefined ? "muse_code"
|
|
46
|
+
: codexContext !== undefined ? "codex"
|
|
47
|
+
: piContext !== undefined ? "pi"
|
|
48
|
+
: openCodeContext !== undefined ? "opencode"
|
|
49
|
+
: claimedClientHarness(headers);
|
|
50
|
+
return {
|
|
51
|
+
...(clientHarness === undefined ? {} : { clientHarness }),
|
|
52
|
+
...(agentContext === undefined ? {} : { agentContext }),
|
|
53
|
+
...(conversationIdentity === undefined ? {} : { conversationIdentity }),
|
|
54
|
+
...(requestPurpose === undefined ? {} : { requestPurpose }),
|
|
55
|
+
...(museClientId === undefined ? {} : { museCodeClientId: museClientId }),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { isRecord } from "@mupt-ai/dari-router/policy-engine";
|
|
2
|
+
import { HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
|
|
3
|
+
import { EXPLICIT_MODEL_PREFIX } from "../protocol/input/router_model.js";
|
|
2
4
|
export const BEDROCK_API = "bedrock-converse-stream";
|
|
3
5
|
export function isBedrockApi(api) {
|
|
4
6
|
return api === BEDROCK_API;
|
|
@@ -42,9 +44,25 @@ export function modelSupportsReasoningConfigurationUpdate(metadata) {
|
|
|
42
44
|
}
|
|
43
45
|
// OpenAI's own Responses endpoints read and write native `compaction` items.
|
|
44
46
|
export function modelSupportsNativeCompaction(metadata) {
|
|
45
|
-
return
|
|
47
|
+
return servedByOpenAIResponses(metadata);
|
|
46
48
|
}
|
|
49
|
+
/* OpenAI runs its web search inside its own Responses endpoints. Hosted Dari
|
|
50
|
+
serving one of OpenAI's models for a connected gateway reaches it there
|
|
51
|
+
too, and refuses the request itself when it cannot. Without this a Codex
|
|
52
|
+
session, which asks for the search on every turn, fails outright the moment
|
|
53
|
+
its ChatGPT plan on this computer is at its limit, instead of moving to Dari. */
|
|
47
54
|
export function modelSupportsHostedWebSearch(metadata) {
|
|
55
|
+
if (servedByOpenAIResponses(metadata))
|
|
56
|
+
return true;
|
|
57
|
+
// The model as hosted Dari is asked for it: a router's config names it in
|
|
58
|
+
// `native_model_id`, and the provider's model in `id`.
|
|
59
|
+
const asked = metadata.model.native_model_id ?? metadata.model.id;
|
|
60
|
+
return metadata.model.provider === HOSTED_DARI_PROVIDER
|
|
61
|
+
&& metadata.model.api === "openai-responses"
|
|
62
|
+
&& typeof asked === "string"
|
|
63
|
+
&& asked.startsWith(`${EXPLICIT_MODEL_PREFIX}openai/`);
|
|
64
|
+
}
|
|
65
|
+
function servedByOpenAIResponses(metadata) {
|
|
48
66
|
return ((metadata.model.provider === "openai" && metadata.model.api === "openai-responses")
|
|
49
67
|
|| (metadata.model.provider === "openai-codex"
|
|
50
68
|
&& metadata.model.api === "openai-codex-responses")
|
|
@@ -13,6 +13,7 @@ import { subscriptionOAuthProviderFor } from "./subscription_limits.js";
|
|
|
13
13
|
import { completeInteractionModel, streamInteractionModel, } from "./pi.js";
|
|
14
14
|
import { promptTokenEstimateFor } from "./cancel_estimate.js";
|
|
15
15
|
import { withSystemPromptSuffix } from "../interaction/system_prompt.js";
|
|
16
|
+
import { HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
|
|
16
17
|
export function prepareProviderExecution(args) {
|
|
17
18
|
const model = args.decision.selectedModel;
|
|
18
19
|
const promptEstimate = promptTokenEstimateFor(args.costEstimates, model, args.decision.reasoningEffort);
|
|
@@ -43,7 +44,8 @@ export function prepareProviderExecution(args) {
|
|
|
43
44
|
: args.conversationId,
|
|
44
45
|
reasoningEffort: args.decision.reasoningEffort,
|
|
45
46
|
promptEstimate,
|
|
46
|
-
|
|
47
|
+
// Hosted Dari serving the model appends the router's role prompt itself.
|
|
48
|
+
...(args.systemPromptSuffix && provider !== HOSTED_DARI_PROVIDER ? { systemPromptSuffix: args.systemPromptSuffix } : {}),
|
|
47
49
|
...(supplied?.baseUrl || supplied?.headers
|
|
48
50
|
? { endpoint: { baseUrl: supplied.baseUrl, headers: supplied.headers } }
|
|
49
51
|
: {}),
|
|
@@ -139,7 +139,7 @@ async function startSession(deps, body, now) {
|
|
|
139
139
|
const isPrivate = body.private ?? reconnecting?.private ?? false;
|
|
140
140
|
if (typeof isPrivate !== "boolean")
|
|
141
141
|
throw new HttpError(400, "private must be true or false.");
|
|
142
|
-
// `dari accounts subscription
|
|
142
|
+
// `dari accounts subscription connect` names the hosted plan it moves here.
|
|
143
143
|
const movingFrom = body.moving_from ?? null;
|
|
144
144
|
if (movingFrom !== null && (typeof movingFrom !== "string" || !movingFrom.trim())) {
|
|
145
145
|
throw new HttpError(400, "moving_from must be a non-empty string.");
|
|
@@ -265,13 +265,23 @@ function usageBody(credential, now) {
|
|
|
265
265
|
})),
|
|
266
266
|
};
|
|
267
267
|
}
|
|
268
|
+
function safeMetadata(credential) {
|
|
269
|
+
const metadata = {};
|
|
270
|
+
if (credential.accountEmail !== null)
|
|
271
|
+
metadata.account_email = credential.accountEmail;
|
|
272
|
+
if (credential.accountId !== null)
|
|
273
|
+
metadata.account_id = credential.accountId;
|
|
274
|
+
return metadata;
|
|
275
|
+
}
|
|
268
276
|
function credentialBody(credential, active, now) {
|
|
269
277
|
const held = isHeld(credential, now);
|
|
270
278
|
return {
|
|
271
279
|
id: credential.id,
|
|
272
280
|
name: credential.name,
|
|
273
281
|
label: credential.label,
|
|
274
|
-
|
|
282
|
+
// The account, as hosted Dari shows a plan's: its email and, where the
|
|
283
|
+
// provider names one, its account (a ChatGPT workspace).
|
|
284
|
+
safe_metadata: safeMetadata(credential),
|
|
275
285
|
// Hosted organizations also hold organization-scoped secrets; every
|
|
276
286
|
// subscription here belongs to the gateway's one user.
|
|
277
287
|
credential_scope: "user",
|
|
@@ -29,18 +29,14 @@ const PROVIDER_LABELS = {
|
|
|
29
29
|
xai_grok: "Grok",
|
|
30
30
|
vercel_token_pass: "Vercel Token Pass",
|
|
31
31
|
};
|
|
32
|
+
const PLACE_NAMES = {
|
|
33
|
+
dari: "on Dari",
|
|
34
|
+
this_computer: "on This Computer",
|
|
35
|
+
private: "Private on This Computer",
|
|
36
|
+
};
|
|
32
37
|
function connectedAccountMessage(account) {
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
const asName = account.name === null ? "" : ` as ${handle}`;
|
|
36
|
-
switch (account.place) {
|
|
37
|
-
case "dari":
|
|
38
|
-
return `This ${label} account is already connected on Dari${asName}. Move it with \`dari accounts subscription move ${handle} --on computer\`, or disconnect it first.`;
|
|
39
|
-
case "this_computer":
|
|
40
|
-
return `This ${label} account is already connected on This Computer${asName}. Move it with \`dari accounts subscription move ${handle} --on dari\`, or disconnect it first.`;
|
|
41
|
-
case "private":
|
|
42
|
-
return `This ${label} account is already connected Private on This Computer${asName}. Move it with \`dari accounts subscription move ${handle} --on dari\` or \`--on computer\`, or disconnect it first.`;
|
|
43
|
-
}
|
|
38
|
+
const asName = account.name === null ? "" : ` as ${account.name}`;
|
|
39
|
+
return `This ${PROVIDER_LABELS[account.provider]} account is already connected ${PLACE_NAMES[account.place]}${asName}. Run \`dari accounts subscription connect\` again and choose Move, or disconnect it first.`;
|
|
44
40
|
}
|
|
45
41
|
const BASE_NAMES = {
|
|
46
42
|
anthropic_claude_code: "ANTHROPIC_CLAUDE_CODE_OAUTH_TOKEN",
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@mupt-ai/dari-gateway",
|
|
3
|
-
"version": "1.0.
|
|
3
|
+
"version": "1.0.363",
|
|
4
4
|
"description": "Self-hostable LLM gateway for coding agents and APIs: one endpoint for Anthropic Messages, OpenAI Chat Completions, and OpenAI Responses, with subscription pooling, failover, and prompt-cache-aware routing.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"repository": {
|
|
@@ -52,7 +52,7 @@
|
|
|
52
52
|
},
|
|
53
53
|
"dependencies": {
|
|
54
54
|
"@aws-sdk/client-sts": "3.1063.0",
|
|
55
|
-
"@mupt-ai/dari-router": "1.0.
|
|
55
|
+
"@mupt-ai/dari-router": "1.0.363",
|
|
56
56
|
"@mupt-ai/pi-ai": "1.5.2-mupt.3"
|
|
57
57
|
},
|
|
58
58
|
"devDependencies": {
|
|
@@ -9,12 +9,7 @@ import { anthropicMessagesToInteraction } from "../protocol/input/anthropic_mess
|
|
|
9
9
|
import { CANONICAL_ROUTER_MODEL, explicitModelId, isLinkToken, linkTokenModel } from "../protocol/input/router_model.js";
|
|
10
10
|
import { handleRoutedCompletion } from "../runtime/routed_completion.js";
|
|
11
11
|
import type { SelectorBackend } from "../strategies/routing.js";
|
|
12
|
-
import {
|
|
13
|
-
import { claimedClientHarness } from "./client_harness.js";
|
|
14
|
-
import {
|
|
15
|
-
claudeCodeConversationIdentity,
|
|
16
|
-
piRequestContext,
|
|
17
|
-
} from "../runtime/harness_identity/index.js";
|
|
12
|
+
import { harnessRequest } from "./harness_request.js";
|
|
18
13
|
import { parseJsonRequest } from "./json.js";
|
|
19
14
|
import { anthropicWebSearchTool } from "../interaction/capabilities.js";
|
|
20
15
|
import { isBackgroundRequest } from "../interaction/types.js";
|
|
@@ -28,7 +23,6 @@ type AnthropicErrorType =
|
|
|
28
23
|
| "api_error"
|
|
29
24
|
| "invalid_request_error";
|
|
30
25
|
|
|
31
|
-
const LEGACY_CLAUDE_CODE_BETA = "claude-code-20250219";
|
|
32
26
|
const SAFEGUARDS_BETA_PREFIX = "dangerous-tool-use-";
|
|
33
27
|
const CONTEXT_MANAGEMENT_BETA_PREFIX = "context-management-";
|
|
34
28
|
|
|
@@ -41,13 +35,17 @@ export async function handleAnthropicMessages(
|
|
|
41
35
|
const apiKey = anthropicToken(request.headers);
|
|
42
36
|
const rawPayload = await parseJsonRequest<Record<string, unknown>>(request);
|
|
43
37
|
const interaction = anthropicMessagesToInteraction({ ...rawPayload, model: linkTokenModel(apiKey, rawPayload.model) });
|
|
44
|
-
const isClaudeCode = isClaudeCodeRequest(request.headers);
|
|
45
|
-
const anthropicSafeguards = safeguardsFrom(rawPayload, request.headers);
|
|
46
|
-
const anthropicContextManagement = contextManagementFrom(rawPayload, request.headers);
|
|
47
38
|
// Pi's turns arrive as chat completions; the Dari extension's web search
|
|
48
39
|
// tool sends its search here, marked as Pi's.
|
|
49
|
-
const
|
|
50
|
-
|
|
40
|
+
const harness = harnessRequest(request.headers, {
|
|
41
|
+
sourceProtocol: "anthropic_messages",
|
|
42
|
+
payload: rawPayload,
|
|
43
|
+
promptCacheKey: interaction.promptCacheKey,
|
|
44
|
+
});
|
|
45
|
+
const isClaudeCode = harness.clientHarness === "claude_code";
|
|
46
|
+
const agentContext = harness.agentContext;
|
|
47
|
+
const anthropicSafeguards = safeguardsFrom(rawPayload, request.headers);
|
|
48
|
+
const anthropicContextManagement = contextManagementFrom(rawPayload, request.headers);
|
|
51
49
|
// Claude Code runs a web search as a background request that names one of
|
|
52
50
|
// the session's models, and Pi's search tool as one that asks for routing.
|
|
53
51
|
// Like other background work, Dari serves it on the cheapest model that
|
|
@@ -74,7 +72,12 @@ export async function handleAnthropicMessages(
|
|
|
74
72
|
? { requestPurpose: "tool_continuation" as const } : {}),
|
|
75
73
|
claudeCodeUserAgent: request.headers.get("user-agent")!.trim(),
|
|
76
74
|
}
|
|
77
|
-
: {
|
|
75
|
+
: {
|
|
76
|
+
...forwarded,
|
|
77
|
+
...(agentContext === undefined ? {} : { agentContext }),
|
|
78
|
+
...(harness.requestPurpose === undefined ? {} : { requestPurpose: harness.requestPurpose }),
|
|
79
|
+
...(harness.museCodeClientId === undefined ? {} : { museCodeClientId: harness.museCodeClientId }),
|
|
80
|
+
};
|
|
78
81
|
return await handleRoutedCompletion({
|
|
79
82
|
request,
|
|
80
83
|
routerId,
|
|
@@ -84,15 +87,8 @@ export async function handleAnthropicMessages(
|
|
|
84
87
|
streamBody: anthropicMessagesSseStream,
|
|
85
88
|
errorResponse: anthropicErrorResponse,
|
|
86
89
|
selectorBackend,
|
|
87
|
-
clientHarness:
|
|
88
|
-
|
|
89
|
-
: claimedClientHarness(request.headers),
|
|
90
|
-
harnessConversationIdentity: isClaudeCode
|
|
91
|
-
? claudeCodeConversationIdentity(
|
|
92
|
-
request.headers,
|
|
93
|
-
payload.promptCacheKey,
|
|
94
|
-
)
|
|
95
|
-
: undefined,
|
|
90
|
+
clientHarness: harness.clientHarness,
|
|
91
|
+
harnessConversationIdentity: harness.conversationIdentity,
|
|
96
92
|
});
|
|
97
93
|
} catch (error) {
|
|
98
94
|
const response = anthropicErrorResponse(error);
|
|
@@ -161,20 +157,6 @@ function anthropicBetas(headers: Headers): Set<string> {
|
|
|
161
157
|
);
|
|
162
158
|
}
|
|
163
159
|
|
|
164
|
-
function isClaudeCodeRequest(headers: Headers): boolean {
|
|
165
|
-
const userAgent = headers.get("user-agent")?.trim().toLowerCase() ?? "";
|
|
166
|
-
const app = headers.get("x-app")?.trim().toLowerCase();
|
|
167
|
-
const betas = anthropicBetas(headers);
|
|
168
|
-
return (
|
|
169
|
-
userAgent.startsWith("claude-cli/") &&
|
|
170
|
-
(app === "cli" || app === "cli-bg") &&
|
|
171
|
-
(
|
|
172
|
-
Boolean(headers.get("x-claude-code-session-id")?.trim()) ||
|
|
173
|
-
betas.has(LEGACY_CLAUDE_CODE_BETA)
|
|
174
|
-
)
|
|
175
|
-
);
|
|
176
|
-
}
|
|
177
|
-
|
|
178
160
|
// Dari-specific codes clients act on; every other code stays internal.
|
|
179
161
|
const CLIENT_VISIBLE_ERROR_CODES = new Set<string>([
|
|
180
162
|
...LINK_GRANT_ERROR_CODES,
|
|
@@ -7,15 +7,8 @@ import { chatCompletionsToInteraction } from "../protocol/input/chat_completions
|
|
|
7
7
|
import { linkTokenModel } from "../protocol/input/router_model.js";
|
|
8
8
|
import { handleRoutedCompletion } from "../runtime/routed_completion.js";
|
|
9
9
|
import type { SelectorBackend } from "../strategies/routing.js";
|
|
10
|
-
import {
|
|
11
|
-
chatCompletionsConversationIdentity,
|
|
12
|
-
openCodeRequestContext,
|
|
13
|
-
piRequestContext,
|
|
14
|
-
} from "../runtime/harness_identity/index.js";
|
|
15
|
-
import type { ClientHarness } from "../types.js";
|
|
16
|
-
import { claimedClientHarness } from "./client_harness.js";
|
|
10
|
+
import { harnessRequest } from "./harness_request.js";
|
|
17
11
|
import { parseJsonRequest } from "./json.js";
|
|
18
|
-
import { museCodeClientId } from "./muse_code.js";
|
|
19
12
|
|
|
20
13
|
export async function handleChatCompletions(
|
|
21
14
|
request: Request,
|
|
@@ -30,34 +23,26 @@ export async function handleChatCompletions(
|
|
|
30
23
|
model: linkTokenModel(apiKey, payload.model),
|
|
31
24
|
source_protocol: "openai_chat",
|
|
32
25
|
});
|
|
33
|
-
const
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
// so the Dari CLI sets them up to name themselves.
|
|
39
|
-
const clientHarness: ClientHarness | undefined = museClientId !== undefined ? "muse_code"
|
|
40
|
-
: piContext !== undefined ? "pi"
|
|
41
|
-
: openCodeContext !== undefined ? "opencode"
|
|
42
|
-
: claimedClientHarness(request.headers);
|
|
26
|
+
const harness = harnessRequest(request.headers, {
|
|
27
|
+
sourceProtocol: "openai_chat",
|
|
28
|
+
payload: payload as unknown as Record<string, unknown>,
|
|
29
|
+
promptCacheKey: payload.prompt_cache_key,
|
|
30
|
+
});
|
|
43
31
|
return await handleRoutedCompletion({
|
|
44
32
|
request,
|
|
45
33
|
routerId,
|
|
46
34
|
apiKey,
|
|
47
35
|
payload: {
|
|
48
36
|
...interaction,
|
|
49
|
-
...(agentContext === undefined ? {} : { agentContext }),
|
|
50
|
-
...(
|
|
37
|
+
...(harness.agentContext === undefined ? {} : { agentContext: harness.agentContext }),
|
|
38
|
+
...(harness.museCodeClientId === undefined ? {} : { museCodeClientId: harness.museCodeClientId }),
|
|
51
39
|
},
|
|
52
40
|
responseBody: chatCompletionResponse,
|
|
53
41
|
streamBody: chatCompletionsSseStream,
|
|
54
42
|
errorResponse,
|
|
55
43
|
selectorBackend,
|
|
56
|
-
clientHarness,
|
|
57
|
-
harnessConversationIdentity:
|
|
58
|
-
request.headers,
|
|
59
|
-
payload.prompt_cache_key,
|
|
60
|
-
),
|
|
44
|
+
clientHarness: harness.clientHarness,
|
|
45
|
+
harnessConversationIdentity: harness.conversationIdentity,
|
|
61
46
|
});
|
|
62
47
|
} catch (error) {
|
|
63
48
|
const response = errorResponse(error);
|
|
@@ -5,6 +5,23 @@ const REQUEST_CLASSES = new Set<AgentRequestClass>([
|
|
|
5
5
|
"main", "subagent", "workflow", "auxiliary", "compaction", "side_reply",
|
|
6
6
|
]);
|
|
7
7
|
|
|
8
|
+
const LEGACY_CLAUDE_CODE_BETA = "claude-code-20250219";
|
|
9
|
+
|
|
10
|
+
/** Whether a request carries Claude Code's own headers. */
|
|
11
|
+
export function isClaudeCodeRequest(headers: Headers): boolean {
|
|
12
|
+
const userAgent = headers.get("user-agent")?.trim().toLowerCase() ?? "";
|
|
13
|
+
const app = headers.get("x-app")?.trim().toLowerCase();
|
|
14
|
+
const betas = (headers.get("anthropic-beta") ?? "").toLowerCase().split(",").map((beta) => beta.trim());
|
|
15
|
+
return (
|
|
16
|
+
userAgent.startsWith("claude-cli/") &&
|
|
17
|
+
(app === "cli" || app === "cli-bg") &&
|
|
18
|
+
(
|
|
19
|
+
Boolean(headers.get("x-claude-code-session-id")?.trim()) ||
|
|
20
|
+
betas.includes(LEGACY_CLAUDE_CODE_BETA)
|
|
21
|
+
)
|
|
22
|
+
);
|
|
23
|
+
}
|
|
24
|
+
|
|
8
25
|
// These are client-supplied routing hints, not authentication claims. Never
|
|
9
26
|
// infer them from prompt text: a user can legitimately paste any such prompt.
|
|
10
27
|
export function claudeCodeRequestContext(headers: Headers): AgentRequestContext {
|
|
@@ -12,13 +12,40 @@ export const CLIENT_HARNESSES: readonly string[] = [
|
|
|
12
12
|
"hermes",
|
|
13
13
|
] satisfies ClientHarness[];
|
|
14
14
|
|
|
15
|
-
// The headers a coding agent
|
|
16
|
-
//
|
|
17
|
-
|
|
15
|
+
// The headers a coding agent describes itself and each request with: which
|
|
16
|
+
// agent it is, its session, and what the request is for. harness_request.ts
|
|
17
|
+
// reads every one of them.
|
|
18
|
+
const CLIENT_HEADERS = [
|
|
19
|
+
// Claude Code
|
|
20
|
+
"user-agent",
|
|
21
|
+
"x-app",
|
|
22
|
+
"anthropic-beta",
|
|
23
|
+
"x-claude-code-session-id",
|
|
24
|
+
"x-claude-code-request-class",
|
|
25
|
+
"x-claude-code-agent-id",
|
|
26
|
+
"x-claude-code-parent-agent-id",
|
|
27
|
+
"x-claude-code-agent-type",
|
|
28
|
+
// Codex
|
|
29
|
+
"x-codex-turn-metadata",
|
|
30
|
+
"thread-id",
|
|
31
|
+
// Muse Code
|
|
32
|
+
"x-client-id",
|
|
33
|
+
"x-tbh-thread-id",
|
|
34
|
+
// OpenCode, with the `dari opencode` plugin's request kind and agent
|
|
35
|
+
"x-opencode-session-id",
|
|
36
|
+
"x-opencode-parent-session-id",
|
|
37
|
+
"x-opencode-request-kind",
|
|
38
|
+
"x-opencode-agent",
|
|
39
|
+
"x-session-affinity",
|
|
40
|
+
// Pi
|
|
41
|
+
"x-pi-session-id",
|
|
42
|
+
"x-pi-request-kind",
|
|
43
|
+
];
|
|
18
44
|
|
|
19
45
|
/**
|
|
20
46
|
* The headers of `CLIENT_HEADERS` the request carries, as the client sent
|
|
21
|
-
* them, so hosted Dari serving it for a connected gateway sees the same
|
|
47
|
+
* them, so hosted Dari serving it for a connected gateway sees the same
|
|
48
|
+
* agent, session, and kind of request.
|
|
22
49
|
*/
|
|
23
50
|
export function clientHeaders(headers: Headers): Record<string, string> {
|
|
24
51
|
const found: Record<string, string> = {};
|
package/src/ingress/codex.ts
CHANGED
|
@@ -5,19 +5,11 @@ import { captureRequestError } from "../observability/errors.js";
|
|
|
5
5
|
import { openAIResponsesResponse } from "../protocol/output/openai_responses.js";
|
|
6
6
|
import { openAIResponsesSseStream } from "../protocol/output/openai_responses_stream.js";
|
|
7
7
|
import { openAIResponsesToInteraction } from "../protocol/input/openai_responses.js";
|
|
8
|
-
import { claimedClientHarness } from "./client_harness.js";
|
|
9
8
|
import { codexModelsEtag } from "./codex_models.js";
|
|
9
|
+
import { harnessRequest } from "./harness_request.js";
|
|
10
10
|
import { parseJsonRequest } from "./json.js";
|
|
11
|
-
import { museCodeClientId } from "./muse_code.js";
|
|
12
11
|
import { handleRoutedCompletion } from "../runtime/routed_completion.js";
|
|
13
12
|
import type { SelectorBackend } from "../strategies/routing.js";
|
|
14
|
-
import {
|
|
15
|
-
codexConversationIdentity,
|
|
16
|
-
codexRequestPurpose,
|
|
17
|
-
codexRequestContext,
|
|
18
|
-
museCodeConversationIdentity,
|
|
19
|
-
piRequestContext,
|
|
20
|
-
} from "../runtime/harness_identity/index.js";
|
|
21
13
|
|
|
22
14
|
export async function handleResponses(
|
|
23
15
|
request: Request,
|
|
@@ -28,37 +20,27 @@ export async function handleResponses(
|
|
|
28
20
|
const apiKey = bearerToken(request.headers);
|
|
29
21
|
const rawPayload = await parseJsonRequest<Record<string, unknown>>(request);
|
|
30
22
|
const interaction = openAIResponsesToInteraction({ ...rawPayload, model: linkTokenModel(apiKey, rawPayload.model) });
|
|
31
|
-
const requestPurpose = codexRequestPurpose(request.headers, rawPayload);
|
|
32
|
-
const codexContext = codexRequestContext(request.headers, rawPayload);
|
|
33
23
|
// Pi's turns arrive as chat completions; the Dari extension's web search
|
|
34
24
|
// tool sends an OpenAI hosted search here, marked as Pi's.
|
|
35
|
-
const
|
|
36
|
-
const agentContext = codexContext ?? piContext;
|
|
37
|
-
const museClientId = museCodeClientId(request.headers);
|
|
25
|
+
const harness = harnessRequest(request.headers, { sourceProtocol: "openai_responses", payload: rawPayload });
|
|
38
26
|
const payload = {
|
|
39
27
|
...interaction,
|
|
40
|
-
...(requestPurpose === undefined ? {} : { requestPurpose }),
|
|
41
|
-
...(agentContext === undefined ? {} : { agentContext }),
|
|
42
|
-
...(
|
|
28
|
+
...(harness.requestPurpose === undefined ? {} : { requestPurpose: harness.requestPurpose }),
|
|
29
|
+
...(harness.agentContext === undefined ? {} : { agentContext: harness.agentContext }),
|
|
30
|
+
...(harness.museCodeClientId === undefined ? {} : { museCodeClientId: harness.museCodeClientId }),
|
|
43
31
|
};
|
|
44
|
-
const codexIdentity = codexConversationIdentity(request.headers, rawPayload);
|
|
45
32
|
// Codex and Muse Code apply their session effort to custom model
|
|
46
33
|
// providers. That preference describes a direct model, not a heterogeneous
|
|
47
34
|
// router, so let Dari select the reasoning effort for their routed turns;
|
|
48
35
|
// a `dari/model/<id>` keeps the chosen effort. Parsing above still
|
|
49
36
|
// validates malformed Responses reasoning controls.
|
|
50
|
-
const
|
|
51
|
-
if (
|
|
37
|
+
const sessionEffort = harness.conversationIdentity?.kind === "codex_thread" || harness.museCodeClientId !== undefined;
|
|
38
|
+
if (sessionEffort && explicitModelId(payload.model) === null) {
|
|
52
39
|
// Keep only an explicit thinking-off; a session effort must not force thinking on.
|
|
53
40
|
payload.reasoning = payload.reasoning?.enabled === false ? { enabled: false } : undefined;
|
|
54
41
|
}
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
const clientHarness = museClientId !== undefined ? "muse_code"
|
|
58
|
-
// Codex describes every request in its turn metadata.
|
|
59
|
-
: codexContext !== undefined ? "codex"
|
|
60
|
-
: piContext !== undefined ? "pi"
|
|
61
|
-
: claimedClientHarness(request.headers);
|
|
42
|
+
const clientHarness = harness.clientHarness;
|
|
43
|
+
const harnessConversationIdentity = harness.conversationIdentity;
|
|
62
44
|
return await handleRoutedCompletion({
|
|
63
45
|
request,
|
|
64
46
|
routerId,
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
AgentRequestContext,
|
|
3
|
+
InteractionRequestPurpose,
|
|
4
|
+
SourceProtocol,
|
|
5
|
+
} from "../interaction/types.js";
|
|
6
|
+
import {
|
|
7
|
+
chatCompletionsConversationIdentity,
|
|
8
|
+
claudeCodeConversationIdentity,
|
|
9
|
+
codexConversationIdentity,
|
|
10
|
+
codexRequestContext,
|
|
11
|
+
codexRequestPurpose,
|
|
12
|
+
museCodeConversationIdentity,
|
|
13
|
+
openCodeRequestContext,
|
|
14
|
+
piRequestContext,
|
|
15
|
+
type HarnessConversationIdentity,
|
|
16
|
+
} from "../runtime/harness_identity/index.js";
|
|
17
|
+
import type { ClientHarness } from "../types.js";
|
|
18
|
+
import { claudeCodeRequestContext, isClaudeCodeRequest } from "./claude_code/request_context.js";
|
|
19
|
+
import { claimedClientHarness } from "./client_harness.js";
|
|
20
|
+
import { museCodeClientId } from "./muse_code.js";
|
|
21
|
+
|
|
22
|
+
/** The coding agent a request comes from, and what the agent says of it. */
|
|
23
|
+
export type HarnessRequest = {
|
|
24
|
+
clientHarness?: ClientHarness;
|
|
25
|
+
// What the request is for: the main agent's turn, a subagent's, compaction.
|
|
26
|
+
agentContext?: AgentRequestContext;
|
|
27
|
+
// The agent's own session, and the subagent within it.
|
|
28
|
+
conversationIdentity?: HarnessConversationIdentity;
|
|
29
|
+
requestPurpose?: InteractionRequestPurpose;
|
|
30
|
+
museCodeClientId?: string;
|
|
31
|
+
};
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Read the coding agent from its own headers.
|
|
35
|
+
*
|
|
36
|
+
* An agent speaks one API, but its headers reach two more: a gateway
|
|
37
|
+
* connected to hosted Dari has hosted Dari serve a model over that model's
|
|
38
|
+
* API (Anthropic's for Claude, Responses for the rest), with the agent's
|
|
39
|
+
* headers passed on (`CLIENT_HEADERS`). So Claude Code's headers arrive on
|
|
40
|
+
* the Responses API when it runs a GPT model, and OpenCode's on Anthropic's
|
|
41
|
+
* when it runs Claude, and each must still be the same agent, request class,
|
|
42
|
+
* and session. Chat completions only ever carries the agents that speak it.
|
|
43
|
+
*/
|
|
44
|
+
export function harnessRequest(headers: Headers, body: {
|
|
45
|
+
sourceProtocol: SourceProtocol;
|
|
46
|
+
payload: Record<string, unknown>;
|
|
47
|
+
promptCacheKey?: string;
|
|
48
|
+
}): HarnessRequest {
|
|
49
|
+
const chat = body.sourceProtocol === "openai_chat";
|
|
50
|
+
if (!chat && isClaudeCodeRequest(headers)) {
|
|
51
|
+
return {
|
|
52
|
+
clientHarness: "claude_code",
|
|
53
|
+
agentContext: claudeCodeRequestContext(headers),
|
|
54
|
+
conversationIdentity: claudeCodeConversationIdentity(
|
|
55
|
+
headers,
|
|
56
|
+
// Only Claude Code's own request body names its session.
|
|
57
|
+
body.sourceProtocol === "anthropic_messages" ? body.promptCacheKey : undefined,
|
|
58
|
+
),
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
const museClientId = museCodeClientId(headers);
|
|
62
|
+
// Codex describes every request in its turn metadata.
|
|
63
|
+
const codexContext = chat ? undefined : codexRequestContext(headers, body.payload);
|
|
64
|
+
const piContext = codexContext === undefined ? piRequestContext(headers) : undefined;
|
|
65
|
+
const openCodeContext = openCodeRequestContext(headers);
|
|
66
|
+
const agentContext = codexContext ?? piContext ?? openCodeContext;
|
|
67
|
+
const requestPurpose = chat ? undefined : codexRequestPurpose(headers, body.payload);
|
|
68
|
+
// Any chat completions caller may name its session; on the other APIs only
|
|
69
|
+
// Pi and OpenCode, whose own headers do.
|
|
70
|
+
const session = chat || piContext !== undefined || openCodeContext !== undefined
|
|
71
|
+
? chatCompletionsConversationIdentity(headers, chat ? body.promptCacheKey : undefined)
|
|
72
|
+
: undefined;
|
|
73
|
+
const conversationIdentity = chat ? session
|
|
74
|
+
: codexConversationIdentity(headers, body.payload)
|
|
75
|
+
?? (museClientId === undefined ? undefined : museCodeConversationIdentity(headers))
|
|
76
|
+
?? session;
|
|
77
|
+
// OpenClaw and Hermes send nothing of their own that tells them apart, so
|
|
78
|
+
// the Dari CLI sets them up to name themselves.
|
|
79
|
+
const clientHarness: ClientHarness | undefined = museClientId !== undefined ? "muse_code"
|
|
80
|
+
: codexContext !== undefined ? "codex"
|
|
81
|
+
: piContext !== undefined ? "pi"
|
|
82
|
+
: openCodeContext !== undefined ? "opencode"
|
|
83
|
+
: claimedClientHarness(headers);
|
|
84
|
+
return {
|
|
85
|
+
...(clientHarness === undefined ? {} : { clientHarness }),
|
|
86
|
+
...(agentContext === undefined ? {} : { agentContext }),
|
|
87
|
+
...(conversationIdentity === undefined ? {} : { conversationIdentity }),
|
|
88
|
+
...(requestPurpose === undefined ? {} : { requestPurpose }),
|
|
89
|
+
...(museClientId === undefined ? {} : { museCodeClientId: museClientId }),
|
|
90
|
+
};
|
|
91
|
+
}
|
|
@@ -1,5 +1,8 @@
|
|
|
1
1
|
import { isRecord } from "@mupt-ai/dari-router/policy-engine";
|
|
2
2
|
|
|
3
|
+
import { HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
|
|
4
|
+
import { EXPLICIT_MODEL_PREFIX } from "../protocol/input/router_model.js";
|
|
5
|
+
|
|
3
6
|
type ModelCapabilityMetadata = {
|
|
4
7
|
model: Record<string, unknown>;
|
|
5
8
|
};
|
|
@@ -63,10 +66,26 @@ export function modelSupportsReasoningConfigurationUpdate(
|
|
|
63
66
|
|
|
64
67
|
// OpenAI's own Responses endpoints read and write native `compaction` items.
|
|
65
68
|
export function modelSupportsNativeCompaction(metadata: ModelCapabilityMetadata): boolean {
|
|
66
|
-
return
|
|
69
|
+
return servedByOpenAIResponses(metadata);
|
|
67
70
|
}
|
|
68
71
|
|
|
72
|
+
/* OpenAI runs its web search inside its own Responses endpoints. Hosted Dari
|
|
73
|
+
serving one of OpenAI's models for a connected gateway reaches it there
|
|
74
|
+
too, and refuses the request itself when it cannot. Without this a Codex
|
|
75
|
+
session, which asks for the search on every turn, fails outright the moment
|
|
76
|
+
its ChatGPT plan on this computer is at its limit, instead of moving to Dari. */
|
|
69
77
|
export function modelSupportsHostedWebSearch(metadata: ModelCapabilityMetadata): boolean {
|
|
78
|
+
if (servedByOpenAIResponses(metadata)) return true;
|
|
79
|
+
// The model as hosted Dari is asked for it: a router's config names it in
|
|
80
|
+
// `native_model_id`, and the provider's model in `id`.
|
|
81
|
+
const asked = metadata.model.native_model_id ?? metadata.model.id;
|
|
82
|
+
return metadata.model.provider === HOSTED_DARI_PROVIDER
|
|
83
|
+
&& metadata.model.api === "openai-responses"
|
|
84
|
+
&& typeof asked === "string"
|
|
85
|
+
&& asked.startsWith(`${EXPLICIT_MODEL_PREFIX}openai/`);
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function servedByOpenAIResponses(metadata: ModelCapabilityMetadata): boolean {
|
|
70
89
|
return (
|
|
71
90
|
(metadata.model.provider === "openai" && metadata.model.api === "openai-responses")
|
|
72
91
|
|| (
|
|
@@ -52,6 +52,7 @@ import {
|
|
|
52
52
|
} from "./pi.js";
|
|
53
53
|
import { promptTokenEstimateFor, type PromptTokenEstimate } from "./cancel_estimate.js";
|
|
54
54
|
import { withSystemPromptSuffix } from "../interaction/system_prompt.js";
|
|
55
|
+
import { HOSTED_DARI_PROVIDER } from "../platform/routing_contract.js";
|
|
55
56
|
|
|
56
57
|
type ProviderCallConfig = {
|
|
57
58
|
model: string;
|
|
@@ -158,7 +159,8 @@ export function prepareProviderExecution(args: {
|
|
|
158
159
|
: args.conversationId,
|
|
159
160
|
reasoningEffort: args.decision.reasoningEffort,
|
|
160
161
|
promptEstimate,
|
|
161
|
-
|
|
162
|
+
// Hosted Dari serving the model appends the router's role prompt itself.
|
|
163
|
+
...(args.systemPromptSuffix && provider !== HOSTED_DARI_PROVIDER ? { systemPromptSuffix: args.systemPromptSuffix } : {}),
|
|
162
164
|
...(supplied?.baseUrl || supplied?.headers
|
|
163
165
|
? { endpoint: { baseUrl: supplied.baseUrl, headers: supplied.headers } }
|
|
164
166
|
: {}),
|
|
@@ -164,7 +164,7 @@ async function startSession(deps: SubscriptionHttpDeps, body: Record<string, unk
|
|
|
164
164
|
// A reconnected plan stays where it was unless the caller says otherwise.
|
|
165
165
|
const isPrivate = body.private ?? reconnecting?.private ?? false;
|
|
166
166
|
if (typeof isPrivate !== "boolean") throw new HttpError(400, "private must be true or false.");
|
|
167
|
-
// `dari accounts subscription
|
|
167
|
+
// `dari accounts subscription connect` names the hosted plan it moves here.
|
|
168
168
|
const movingFrom = body.moving_from ?? null;
|
|
169
169
|
if (movingFrom !== null && (typeof movingFrom !== "string" || !movingFrom.trim())) {
|
|
170
170
|
throw new HttpError(400, "moving_from must be a non-empty string.");
|
|
@@ -297,13 +297,22 @@ function usageBody(credential: SubscriptionCredential, now: Date) {
|
|
|
297
297
|
};
|
|
298
298
|
}
|
|
299
299
|
|
|
300
|
+
function safeMetadata(credential: SubscriptionCredential): Record<string, string> {
|
|
301
|
+
const metadata: Record<string, string> = {};
|
|
302
|
+
if (credential.accountEmail !== null) metadata.account_email = credential.accountEmail;
|
|
303
|
+
if (credential.accountId !== null) metadata.account_id = credential.accountId;
|
|
304
|
+
return metadata;
|
|
305
|
+
}
|
|
306
|
+
|
|
300
307
|
function credentialBody(credential: SubscriptionCredential, active: boolean, now: Date) {
|
|
301
308
|
const held = isHeld(credential, now);
|
|
302
309
|
return {
|
|
303
310
|
id: credential.id,
|
|
304
311
|
name: credential.name,
|
|
305
312
|
label: credential.label,
|
|
306
|
-
|
|
313
|
+
// The account, as hosted Dari shows a plan's: its email and, where the
|
|
314
|
+
// provider names one, its account (a ChatGPT workspace).
|
|
315
|
+
safe_metadata: safeMetadata(credential),
|
|
307
316
|
// Hosted organizations also hold organization-scoped secrets; every
|
|
308
317
|
// subscription here belongs to the gateway's one user.
|
|
309
318
|
credential_scope: "user",
|
|
@@ -130,18 +130,15 @@ const PROVIDER_LABELS: Record<SubscriptionProvider, string> = {
|
|
|
130
130
|
vercel_token_pass: "Vercel Token Pass",
|
|
131
131
|
};
|
|
132
132
|
|
|
133
|
+
const PLACE_NAMES: Record<ConnectedAccount["place"], string> = {
|
|
134
|
+
dari: "on Dari",
|
|
135
|
+
this_computer: "on This Computer",
|
|
136
|
+
private: "Private on This Computer",
|
|
137
|
+
};
|
|
138
|
+
|
|
133
139
|
function connectedAccountMessage(account: ConnectedAccount): string {
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
const asName = account.name === null ? "" : ` as ${handle}`;
|
|
137
|
-
switch (account.place) {
|
|
138
|
-
case "dari":
|
|
139
|
-
return `This ${label} account is already connected on Dari${asName}. Move it with \`dari accounts subscription move ${handle} --on computer\`, or disconnect it first.`;
|
|
140
|
-
case "this_computer":
|
|
141
|
-
return `This ${label} account is already connected on This Computer${asName}. Move it with \`dari accounts subscription move ${handle} --on dari\`, or disconnect it first.`;
|
|
142
|
-
case "private":
|
|
143
|
-
return `This ${label} account is already connected Private on This Computer${asName}. Move it with \`dari accounts subscription move ${handle} --on dari\` or \`--on computer\`, or disconnect it first.`;
|
|
144
|
-
}
|
|
140
|
+
const asName = account.name === null ? "" : ` as ${account.name}`;
|
|
141
|
+
return `This ${PROVIDER_LABELS[account.provider]} account is already connected ${PLACE_NAMES[account.place]}${asName}. Run \`dari accounts subscription connect\` again and choose Move, or disconnect it first.`;
|
|
145
142
|
}
|
|
146
143
|
|
|
147
144
|
const BASE_NAMES: Record<SubscriptionProvider, string> = {
|