dsh-coding-subscription-oauth 0.5.0
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/CHANGELOG.md +136 -0
- package/CONTRIBUTING.md +109 -0
- package/INSTALL.md +220 -0
- package/LICENSE +19 -0
- package/NOTICE +11 -0
- package/README.de.md +254 -0
- package/README.es.md +254 -0
- package/README.fr.md +254 -0
- package/README.ja.md +254 -0
- package/README.ko.md +254 -0
- package/README.md +286 -0
- package/README.pt-BR.md +254 -0
- package/README.ru.md +254 -0
- package/README.zh-CN.md +271 -0
- package/cordis.patch.yml +13 -0
- package/docs/00-project-rules.md +195 -0
- package/docs/02-architecture.md +132 -0
- package/docs/02-architecture.zh-CN.md +128 -0
- package/lib/adapter.d.ts +24 -0
- package/lib/adapter.d.ts.map +1 -0
- package/lib/alias-adapter.d.ts +43 -0
- package/lib/alias-adapter.d.ts.map +1 -0
- package/lib/auth-routes.d.ts +155 -0
- package/lib/auth-routes.d.ts.map +1 -0
- package/lib/auth.d.ts +29 -0
- package/lib/auth.d.ts.map +1 -0
- package/lib/bin.d.ts +6 -0
- package/lib/bin.d.ts.map +1 -0
- package/lib/bin.js +27591 -0
- package/lib/bin.js.map +7 -0
- package/lib/capability-routes.d.ts +43 -0
- package/lib/capability-routes.d.ts.map +1 -0
- package/lib/capability-runtime.d.ts +56 -0
- package/lib/capability-runtime.d.ts.map +1 -0
- package/lib/capability-settings.d.ts +263 -0
- package/lib/capability-settings.d.ts.map +1 -0
- package/lib/capability-tools.d.ts +50 -0
- package/lib/capability-tools.d.ts.map +1 -0
- package/lib/catalog.d.ts +53 -0
- package/lib/catalog.d.ts.map +1 -0
- package/lib/client.js +3 -0
- package/lib/client.js.map +7 -0
- package/lib/codex-http.d.ts +77 -0
- package/lib/codex-http.d.ts.map +1 -0
- package/lib/codex-images.d.ts +109 -0
- package/lib/codex-images.d.ts.map +1 -0
- package/lib/codex-model-capabilities.d.ts +112 -0
- package/lib/codex-model-capabilities.d.ts.map +1 -0
- package/lib/codex-search.d.ts +96 -0
- package/lib/codex-search.d.ts.map +1 -0
- package/lib/codex-usage.d.ts +79 -0
- package/lib/codex-usage.d.ts.map +1 -0
- package/lib/gateway-anthropic-messages.d.ts +8 -0
- package/lib/gateway-anthropic-messages.d.ts.map +1 -0
- package/lib/gateway-auth.d.ts +22 -0
- package/lib/gateway-auth.d.ts.map +1 -0
- package/lib/gateway-backend.d.ts +62 -0
- package/lib/gateway-backend.d.ts.map +1 -0
- package/lib/gateway-body.d.ts +9 -0
- package/lib/gateway-body.d.ts.map +1 -0
- package/lib/gateway-config.d.ts +24 -0
- package/lib/gateway-config.d.ts.map +1 -0
- package/lib/gateway-http.d.ts +16 -0
- package/lib/gateway-http.d.ts.map +1 -0
- package/lib/gateway-openai-chat.d.ts +8 -0
- package/lib/gateway-openai-chat.d.ts.map +1 -0
- package/lib/gateway-openai-responses.d.ts +8 -0
- package/lib/gateway-openai-responses.d.ts.map +1 -0
- package/lib/gateway-parse.d.ts +10 -0
- package/lib/gateway-parse.d.ts.map +1 -0
- package/lib/gateway-protocol.d.ts +47 -0
- package/lib/gateway-protocol.d.ts.map +1 -0
- package/lib/gateway-routes.d.ts +21 -0
- package/lib/gateway-routes.d.ts.map +1 -0
- package/lib/gateway.d.ts +48 -0
- package/lib/gateway.d.ts.map +1 -0
- package/lib/grok-imagine.d.ts +271 -0
- package/lib/grok-imagine.d.ts.map +1 -0
- package/lib/grok-import.d.ts +21 -0
- package/lib/grok-import.d.ts.map +1 -0
- package/lib/http-json.d.ts +10 -0
- package/lib/http-json.d.ts.map +1 -0
- package/lib/ids.d.ts +33 -0
- package/lib/ids.d.ts.map +1 -0
- package/lib/imagine-routes.d.ts +59 -0
- package/lib/imagine-routes.d.ts.map +1 -0
- package/lib/index.d.ts +69 -0
- package/lib/index.d.ts.map +1 -0
- package/lib/index.js +35355 -0
- package/lib/index.js.map +7 -0
- package/lib/invariant.d.ts +9 -0
- package/lib/invariant.d.ts.map +1 -0
- package/lib/invariant.js +14 -0
- package/lib/invariant.js.map +7 -0
- package/lib/kimi-errors.d.ts +13 -0
- package/lib/kimi-errors.d.ts.map +1 -0
- package/lib/media-store.d.ts +130 -0
- package/lib/media-store.d.ts.map +1 -0
- package/lib/oauth-import-routes.d.ts +52 -0
- package/lib/oauth-import-routes.d.ts.map +1 -0
- package/lib/oauth-providers.d.ts +26 -0
- package/lib/oauth-providers.d.ts.map +1 -0
- package/lib/oauth-session.d.ts +40 -0
- package/lib/oauth-session.d.ts.map +1 -0
- package/lib/oauth-sources.d.ts +205 -0
- package/lib/oauth-sources.d.ts.map +1 -0
- package/lib/oauth.d.ts +79 -0
- package/lib/oauth.d.ts.map +1 -0
- package/lib/provider.d.ts +38 -0
- package/lib/provider.d.ts.map +1 -0
- package/lib/proxy.d.ts +17 -0
- package/lib/proxy.d.ts.map +1 -0
- package/lib/redact.d.ts +5 -0
- package/lib/redact.d.ts.map +1 -0
- package/lib/session.d.ts +40 -0
- package/lib/session.d.ts.map +1 -0
- package/lib/store.d.ts +46 -0
- package/lib/store.d.ts.map +1 -0
- package/lib/web-origin.d.ts +10 -0
- package/lib/web-origin.d.ts.map +1 -0
- package/lib/web-routes.d.ts +20 -0
- package/lib/web-routes.d.ts.map +1 -0
- package/package.json +185 -0
- package/patches/dsh-agy@0.1.2.patch +25 -0
- package/scripts/release.mjs +166 -0
- package/scripts/smoke-deployed-routes.mjs +146 -0
- package/scripts/verify-deployed-catalog.mjs +87 -0
- package/src/adapter.ts +282 -0
- package/src/alias-adapter.ts +152 -0
- package/src/auth-routes.ts +871 -0
- package/src/auth.ts +67 -0
- package/src/bin.ts +350 -0
- package/src/capability-routes.ts +275 -0
- package/src/capability-runtime.ts +313 -0
- package/src/capability-settings.ts +657 -0
- package/src/capability-tools.ts +666 -0
- package/src/catalog.ts +271 -0
- package/src/client/GrokBuildSettings.tsx +2221 -0
- package/src/client/index.tsx +37 -0
- package/src/client/locales.ts +421 -0
- package/src/codex-http.ts +447 -0
- package/src/codex-images.ts +485 -0
- package/src/codex-model-capabilities.ts +320 -0
- package/src/codex-search.ts +245 -0
- package/src/codex-usage.ts +263 -0
- package/src/gateway-anthropic-messages.ts +84 -0
- package/src/gateway-auth.ts +100 -0
- package/src/gateway-backend.ts +274 -0
- package/src/gateway-body.ts +49 -0
- package/src/gateway-config.ts +76 -0
- package/src/gateway-http.ts +104 -0
- package/src/gateway-openai-chat.ts +124 -0
- package/src/gateway-openai-responses.ts +53 -0
- package/src/gateway-parse.ts +224 -0
- package/src/gateway-protocol.ts +52 -0
- package/src/gateway-routes.ts +152 -0
- package/src/gateway.ts +242 -0
- package/src/grok-imagine.ts +1627 -0
- package/src/grok-import.ts +151 -0
- package/src/http-json.ts +82 -0
- package/src/ids.ts +45 -0
- package/src/imagine-routes.ts +461 -0
- package/src/index.ts +598 -0
- package/src/invariant.ts +17 -0
- package/src/kimi-errors.ts +26 -0
- package/src/media-store.ts +927 -0
- package/src/oauth-import-routes.ts +314 -0
- package/src/oauth-providers.ts +152 -0
- package/src/oauth-session.ts +183 -0
- package/src/oauth-sources.ts +1104 -0
- package/src/oauth.ts +620 -0
- package/src/provider.ts +128 -0
- package/src/proxy.ts +99 -0
- package/src/redact.ts +72 -0
- package/src/session.ts +218 -0
- package/src/store.ts +217 -0
- package/src/web-origin.ts +60 -0
- package/src/web-routes.ts +75 -0
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Session-backed model listing and event streaming for the local gateway.
|
|
3
|
+
* @module dsh-coding-subscription-oauth/gateway-backend
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { Api, Context, Message, Model, ThinkingLevel, Tool } from "@earendil-works/pi-ai";
|
|
7
|
+
import {
|
|
8
|
+
type GatewayChatMessage,
|
|
9
|
+
type GatewayCompletionRequest,
|
|
10
|
+
type GatewayStreamPart,
|
|
11
|
+
type GatewayTool,
|
|
12
|
+
isThinkingLevel,
|
|
13
|
+
} from "./gateway-protocol.ts";
|
|
14
|
+
import type { OAuthProviderSession } from "./oauth-session.ts";
|
|
15
|
+
import { safeMessage } from "./redact.ts";
|
|
16
|
+
import type { GrokBuildSession } from "./session.ts";
|
|
17
|
+
|
|
18
|
+
export interface GatewayListedModel {
|
|
19
|
+
id: string;
|
|
20
|
+
owned_by: string;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface GatewayBackend {
|
|
24
|
+
listModels(): Promise<readonly GatewayListedModel[]>;
|
|
25
|
+
stream(request: GatewayCompletionRequest): AsyncIterable<GatewayStreamPart>;
|
|
26
|
+
streamText(modelId: string, messages: readonly GatewayChatMessage[]): AsyncIterable<string>;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
export class GatewayRequestError extends Error {
|
|
30
|
+
constructor(
|
|
31
|
+
readonly status: number,
|
|
32
|
+
readonly code: string,
|
|
33
|
+
message: string,
|
|
34
|
+
) {
|
|
35
|
+
super(message);
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
interface OwnedModel {
|
|
40
|
+
owned_by: string;
|
|
41
|
+
model: Model<Api>;
|
|
42
|
+
stream: (
|
|
43
|
+
model: Model<Api>,
|
|
44
|
+
context: Context,
|
|
45
|
+
options?: { reasoning?: ThinkingLevel },
|
|
46
|
+
) => AsyncIterable<{
|
|
47
|
+
type: string;
|
|
48
|
+
delta?: string;
|
|
49
|
+
errorMessage?: string;
|
|
50
|
+
reason?: string;
|
|
51
|
+
toolCall?: { id: string; name: string; arguments?: unknown };
|
|
52
|
+
partial?: { content?: readonly { type?: string; id?: string; name?: string }[] };
|
|
53
|
+
}>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
const EMPTY_USAGE = {
|
|
57
|
+
input: 0,
|
|
58
|
+
output: 0,
|
|
59
|
+
cacheRead: 0,
|
|
60
|
+
cacheWrite: 0,
|
|
61
|
+
totalTokens: 0,
|
|
62
|
+
cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
|
|
63
|
+
};
|
|
64
|
+
|
|
65
|
+
export function createSessionGatewayBackend(
|
|
66
|
+
grok: GrokBuildSession,
|
|
67
|
+
subscriptions: readonly OAuthProviderSession[],
|
|
68
|
+
): GatewayBackend {
|
|
69
|
+
return {
|
|
70
|
+
async listModels() {
|
|
71
|
+
const listed: GatewayListedModel[] = [];
|
|
72
|
+
const seen = new Map<string, string>();
|
|
73
|
+
for (const owned of await collectOwnedModels(grok, subscriptions)) {
|
|
74
|
+
const previous = seen.get(owned.model.id);
|
|
75
|
+
if (previous !== undefined && previous !== owned.owned_by) continue;
|
|
76
|
+
seen.set(owned.model.id, owned.owned_by);
|
|
77
|
+
listed.push({ id: owned.model.id, owned_by: owned.owned_by });
|
|
78
|
+
}
|
|
79
|
+
return listed;
|
|
80
|
+
},
|
|
81
|
+
async *stream(request) {
|
|
82
|
+
const owned = selectOwnedModel(await collectOwnedModels(grok, subscriptions), request.model);
|
|
83
|
+
const context = buildGatewayContext(request.messages, request.tools);
|
|
84
|
+
const reasoning = resolveReasoning(request.reasoning, owned.owned_by);
|
|
85
|
+
let usedTools = false;
|
|
86
|
+
for await (const event of owned.stream(
|
|
87
|
+
owned.model,
|
|
88
|
+
context,
|
|
89
|
+
reasoning === undefined ? undefined : { reasoning },
|
|
90
|
+
)) {
|
|
91
|
+
if (event.type === "text_delta" && typeof event.delta === "string" && event.delta.length > 0) {
|
|
92
|
+
yield { type: "text", text: event.delta };
|
|
93
|
+
}
|
|
94
|
+
if (event.type === "thinking_delta" && typeof event.delta === "string" && event.delta.length > 0) {
|
|
95
|
+
yield { type: "thinking", text: event.delta };
|
|
96
|
+
}
|
|
97
|
+
if (event.type === "toolcall_end" && event.toolCall !== undefined) {
|
|
98
|
+
usedTools = true;
|
|
99
|
+
yield {
|
|
100
|
+
type: "tool_call",
|
|
101
|
+
index: 0,
|
|
102
|
+
id: event.toolCall.id,
|
|
103
|
+
name: event.toolCall.name,
|
|
104
|
+
arguments: stringifyToolArguments(event.toolCall.arguments),
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
if (event.type === "error") {
|
|
108
|
+
throw new GatewayRequestError(502, "upstream_error", event.errorMessage ?? "upstream stream error");
|
|
109
|
+
}
|
|
110
|
+
if (event.type === "done") {
|
|
111
|
+
const finish =
|
|
112
|
+
event.reason === "length" ? "length" : usedTools || event.reason === "toolUse" ? "tool_calls" : "stop";
|
|
113
|
+
yield { type: "done", finish };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
},
|
|
117
|
+
async *streamText(modelId, messages) {
|
|
118
|
+
for await (const part of this.stream({ model: modelId, messages })) {
|
|
119
|
+
if (part.type === "text") yield part.text;
|
|
120
|
+
}
|
|
121
|
+
},
|
|
122
|
+
};
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
export function selectOwnedModel(owned: readonly OwnedModel[], modelId: string): OwnedModel {
|
|
126
|
+
const matches = owned.filter((item) => item.model.id === modelId);
|
|
127
|
+
if (matches.length === 0) throw new GatewayRequestError(404, "model_not_found", `Unknown model ${modelId}`);
|
|
128
|
+
const owners = new Set(matches.map((item) => item.owned_by));
|
|
129
|
+
if (owners.size > 1) {
|
|
130
|
+
throw new GatewayRequestError(404, "model_not_found", `Model ${modelId} is owned by multiple signed-in providers`);
|
|
131
|
+
}
|
|
132
|
+
return matches[0]!;
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function buildGatewayContext(messages: readonly GatewayChatMessage[], tools?: readonly GatewayTool[]): Context {
|
|
136
|
+
let systemPrompt: string | undefined;
|
|
137
|
+
const mapped: Message[] = [];
|
|
138
|
+
for (const message of messages) {
|
|
139
|
+
if (message.role === "system") {
|
|
140
|
+
systemPrompt = `${systemPrompt === undefined ? "" : `${systemPrompt}\n`}${message.content}`;
|
|
141
|
+
continue;
|
|
142
|
+
}
|
|
143
|
+
if (message.role === "assistant") {
|
|
144
|
+
mapped.push(assistantReplay(message));
|
|
145
|
+
continue;
|
|
146
|
+
}
|
|
147
|
+
if (message.role === "tool") {
|
|
148
|
+
mapped.push({
|
|
149
|
+
role: "toolResult",
|
|
150
|
+
toolCallId: message.tool_call_id ?? "",
|
|
151
|
+
toolName: message.tool_name ?? "tool",
|
|
152
|
+
content: [{ type: "text", text: message.content }],
|
|
153
|
+
isError: false,
|
|
154
|
+
timestamp: Date.now(),
|
|
155
|
+
});
|
|
156
|
+
continue;
|
|
157
|
+
}
|
|
158
|
+
mapped.push({ role: "user", content: message.content, timestamp: Date.now() });
|
|
159
|
+
}
|
|
160
|
+
const context: Context = systemPrompt === undefined ? { messages: mapped } : { systemPrompt, messages: mapped };
|
|
161
|
+
if (tools !== undefined && tools.length > 0) context.tools = tools.map(toPiTool);
|
|
162
|
+
return context;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export function assistantReplay(message: GatewayChatMessage): Message {
|
|
166
|
+
const content: Array<
|
|
167
|
+
| { type: "text"; text: string }
|
|
168
|
+
| { type: "thinking"; thinking: string }
|
|
169
|
+
| { type: "toolCall"; id: string; name: string; arguments: Record<string, unknown> }
|
|
170
|
+
> = [];
|
|
171
|
+
const needsPlaceholder = message.tool_calls !== undefined && message.tool_calls.length > 0;
|
|
172
|
+
const reasoning = message.reasoning_content ?? (needsPlaceholder ? "" : undefined);
|
|
173
|
+
if (reasoning !== undefined) content.push({ type: "thinking", thinking: reasoning });
|
|
174
|
+
if (message.content.length > 0) content.push({ type: "text", text: message.content });
|
|
175
|
+
if (message.tool_calls !== undefined) {
|
|
176
|
+
for (const call of message.tool_calls) {
|
|
177
|
+
content.push({
|
|
178
|
+
type: "toolCall",
|
|
179
|
+
id: call.id,
|
|
180
|
+
name: call.name,
|
|
181
|
+
arguments: parseToolArguments(call.arguments),
|
|
182
|
+
});
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
return {
|
|
186
|
+
role: "assistant",
|
|
187
|
+
content: content.length === 0 ? [{ type: "text", text: "" }] : content,
|
|
188
|
+
api: "openai-responses",
|
|
189
|
+
provider: "gateway",
|
|
190
|
+
model: "gateway",
|
|
191
|
+
usage: EMPTY_USAGE,
|
|
192
|
+
stopReason: needsPlaceholder ? "toolUse" : "stop",
|
|
193
|
+
timestamp: Date.now(),
|
|
194
|
+
};
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function toPiTool(tool: GatewayTool): Tool {
|
|
198
|
+
return {
|
|
199
|
+
name: tool.name,
|
|
200
|
+
description: tool.description,
|
|
201
|
+
parameters: tool.parameters as Tool["parameters"],
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function parseToolArguments(raw: string): Record<string, unknown> {
|
|
206
|
+
try {
|
|
207
|
+
const value = JSON.parse(raw) as unknown;
|
|
208
|
+
return typeof value === "object" && value !== null && !Array.isArray(value)
|
|
209
|
+
? (value as Record<string, unknown>)
|
|
210
|
+
: { value };
|
|
211
|
+
} catch {
|
|
212
|
+
return { value: raw };
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
function stringifyToolArguments(value: unknown): string {
|
|
217
|
+
if (typeof value === "string") return value;
|
|
218
|
+
try {
|
|
219
|
+
return JSON.stringify(value ?? {});
|
|
220
|
+
} catch {
|
|
221
|
+
return "{}";
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
function resolveReasoning(value: string | undefined, ownedBy: string): ThinkingLevel | undefined {
|
|
226
|
+
if (value === undefined || !isThinkingLevel(value)) return undefined;
|
|
227
|
+
if (ownedBy === "kimi-code-oauth" || ownedBy === "claude-code-oauth") return undefined;
|
|
228
|
+
return value as ThinkingLevel;
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async function collectOwnedModels(
|
|
232
|
+
grok: GrokBuildSession,
|
|
233
|
+
subscriptions: readonly OAuthProviderSession[],
|
|
234
|
+
): Promise<OwnedModel[]> {
|
|
235
|
+
const owned: OwnedModel[] = [];
|
|
236
|
+
const grokAuth = await grok.models.getAuth("xai");
|
|
237
|
+
if (grokAuth?.auth.apiKey) {
|
|
238
|
+
for (const model of grok.visibleModels()) {
|
|
239
|
+
owned.push({
|
|
240
|
+
owned_by: "grok-build",
|
|
241
|
+
model,
|
|
242
|
+
stream: (item, context, options) => grok.models.streamSimple(item, context, options),
|
|
243
|
+
});
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
for (const session of subscriptions) {
|
|
247
|
+
const status = await session.status();
|
|
248
|
+
if (!status.authenticated) continue;
|
|
249
|
+
for (const model of session.visibleModels()) {
|
|
250
|
+
owned.push({
|
|
251
|
+
owned_by: session.definition.route,
|
|
252
|
+
model,
|
|
253
|
+
stream: (item, context, options) => session.models.streamSimple(item, context, options),
|
|
254
|
+
});
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
return owned;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
export function gatewayErrorEnvelope(error: unknown): {
|
|
261
|
+
status: number;
|
|
262
|
+
body: { error: { message: string; type: string; code: string } };
|
|
263
|
+
} {
|
|
264
|
+
if (error instanceof GatewayRequestError) {
|
|
265
|
+
return {
|
|
266
|
+
status: error.status,
|
|
267
|
+
body: { error: { message: error.message.slice(0, 1000), type: "invalid_request_error", code: error.code } },
|
|
268
|
+
};
|
|
269
|
+
}
|
|
270
|
+
return {
|
|
271
|
+
status: 500,
|
|
272
|
+
body: { error: { message: safeMessage(error).slice(0, 1000), type: "server_error", code: "internal" } },
|
|
273
|
+
};
|
|
274
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared JSON body reader for isolated gateway endpoints.
|
|
3
|
+
* @module dsh-coding-subscription-oauth/gateway-body
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { IncomingMessage } from "node:http";
|
|
7
|
+
import { GatewayRequestError } from "./gateway-backend.ts";
|
|
8
|
+
|
|
9
|
+
const BODY_LIMIT = 1024 * 1024;
|
|
10
|
+
|
|
11
|
+
export async function readGatewayJsonBody(req: IncomingMessage): Promise<Record<string, unknown>> {
|
|
12
|
+
const chunks: Buffer[] = [];
|
|
13
|
+
let size = 0;
|
|
14
|
+
for await (const chunk of req) {
|
|
15
|
+
const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
|
|
16
|
+
size += buffer.byteLength;
|
|
17
|
+
if (size > BODY_LIMIT) throw new GatewayRequestError(413, "payload_too_large", "request body exceeds 1 MiB");
|
|
18
|
+
chunks.push(buffer);
|
|
19
|
+
}
|
|
20
|
+
if (chunks.length === 0) return {};
|
|
21
|
+
try {
|
|
22
|
+
const value = JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown;
|
|
23
|
+
if (typeof value !== "object" || value === null || Array.isArray(value)) {
|
|
24
|
+
throw new GatewayRequestError(400, "invalid_request", "body must be a JSON object");
|
|
25
|
+
}
|
|
26
|
+
return value as Record<string, unknown>;
|
|
27
|
+
} catch (error) {
|
|
28
|
+
if (error instanceof GatewayRequestError) throw error;
|
|
29
|
+
throw new GatewayRequestError(400, "invalid_request", "body is not valid JSON");
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
export function writeGatewayJson(res: import("node:http").ServerResponse, status: number, value: unknown): void {
|
|
34
|
+
const body = Buffer.from(`${JSON.stringify(value)}\n`);
|
|
35
|
+
res.writeHead(status, {
|
|
36
|
+
"content-type": "application/json; charset=utf-8",
|
|
37
|
+
"content-length": body.byteLength,
|
|
38
|
+
"cache-control": "no-store",
|
|
39
|
+
});
|
|
40
|
+
res.end(body);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export function beginGatewaySse(res: import("node:http").ServerResponse): void {
|
|
44
|
+
res.writeHead(200, {
|
|
45
|
+
"content-type": "text/event-stream; charset=utf-8",
|
|
46
|
+
"cache-control": "no-store",
|
|
47
|
+
connection: "close",
|
|
48
|
+
});
|
|
49
|
+
}
|
|
@@ -0,0 +1,76 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Opt-in local API gateway configuration.
|
|
3
|
+
* @module dsh-coding-subscription-oauth/gateway-config
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import z from "@deepseek-ai/schemastery";
|
|
7
|
+
|
|
8
|
+
export const GATEWAY_DEFAULT_BIND = "127.0.0.1";
|
|
9
|
+
export const GATEWAY_DEFAULT_PORT = 18_080;
|
|
10
|
+
export const GATEWAY_MIN_PORT = 1024;
|
|
11
|
+
export const GATEWAY_MAX_PORT = 65_535;
|
|
12
|
+
export const GATEWAY_RANDOM_PORT_MIN = 18_100;
|
|
13
|
+
export const GATEWAY_RANDOM_PORT_MAX = 18_999;
|
|
14
|
+
const GATEWAY_RANDOM_RESERVED = new Set([22, 53, 3080, 7890, 9090, GATEWAY_DEFAULT_PORT]);
|
|
15
|
+
|
|
16
|
+
export interface GatewayConfig {
|
|
17
|
+
readonly enabled: boolean;
|
|
18
|
+
readonly bind: string;
|
|
19
|
+
readonly port: number;
|
|
20
|
+
readonly apiKey?: string;
|
|
21
|
+
readonly rateLimit: number;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const GatewayConfigSchema: z<Partial<GatewayConfig>> = z.object({
|
|
25
|
+
enabled: z.boolean().default(false),
|
|
26
|
+
bind: z.string().default(GATEWAY_DEFAULT_BIND),
|
|
27
|
+
port: z.number().default(GATEWAY_DEFAULT_PORT),
|
|
28
|
+
apiKey: z.string(),
|
|
29
|
+
rateLimit: z.number().default(0),
|
|
30
|
+
});
|
|
31
|
+
|
|
32
|
+
export function resolveGatewayConfig(raw?: Partial<GatewayConfig>): GatewayConfig {
|
|
33
|
+
const bind = raw?.bind ?? GATEWAY_DEFAULT_BIND;
|
|
34
|
+
const port = raw?.port ?? GATEWAY_DEFAULT_PORT;
|
|
35
|
+
if (typeof bind !== "string" || bind.trim() === "") throw new Error("gateway.bind must be a non-empty host");
|
|
36
|
+
assertGatewayPort(port);
|
|
37
|
+
const rateLimit = raw?.rateLimit ?? 0;
|
|
38
|
+
if (!Number.isSafeInteger(rateLimit) || rateLimit < 0)
|
|
39
|
+
throw new Error("gateway.rateLimit must be a non-negative integer");
|
|
40
|
+
const apiKey = raw?.apiKey;
|
|
41
|
+
if (apiKey !== undefined && (typeof apiKey !== "string" || apiKey.length === 0)) {
|
|
42
|
+
throw new Error("gateway.apiKey must be a non-empty string when set");
|
|
43
|
+
}
|
|
44
|
+
return {
|
|
45
|
+
enabled: raw?.enabled === true,
|
|
46
|
+
bind: bind.trim(),
|
|
47
|
+
port,
|
|
48
|
+
...(apiKey === undefined ? {} : { apiKey }),
|
|
49
|
+
rateLimit,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export function isLoopbackBind(bind: string): boolean {
|
|
54
|
+
return bind === "127.0.0.1" || bind === "::1" || bind === "localhost";
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function assertGatewayPort(port: number): number {
|
|
58
|
+
if (!Number.isSafeInteger(port) || port < GATEWAY_MIN_PORT || port > GATEWAY_MAX_PORT) {
|
|
59
|
+
throw new Error(
|
|
60
|
+
`gateway.port must be an integer between ${String(GATEWAY_MIN_PORT)} and ${String(GATEWAY_MAX_PORT)}`,
|
|
61
|
+
);
|
|
62
|
+
}
|
|
63
|
+
return port;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function randomGatewayPort(exclude: number | readonly number[] = []): number {
|
|
67
|
+
const blocked = new Set(GATEWAY_RANDOM_RESERVED);
|
|
68
|
+
if (typeof exclude === "number") blocked.add(exclude);
|
|
69
|
+
else for (const value of exclude) blocked.add(value);
|
|
70
|
+
for (let attempt = 0; attempt < 32; attempt += 1) {
|
|
71
|
+
const span = GATEWAY_RANDOM_PORT_MAX - GATEWAY_RANDOM_PORT_MIN + 1;
|
|
72
|
+
const candidate = GATEWAY_RANDOM_PORT_MIN + Math.floor(Math.random() * span);
|
|
73
|
+
if (!blocked.has(candidate)) return candidate;
|
|
74
|
+
}
|
|
75
|
+
return GATEWAY_RANDOM_PORT_MIN === exclude ? GATEWAY_RANDOM_PORT_MIN + 1 : GATEWAY_RANDOM_PORT_MIN;
|
|
76
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Isolated node:http server for the opt-in local gateway.
|
|
3
|
+
* @module dsh-coding-subscription-oauth/gateway-http
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import { createServer, type IncomingMessage, type Server, type ServerResponse } from "node:http";
|
|
7
|
+
import { handleAnthropicMessages } from "./gateway-anthropic-messages.ts";
|
|
8
|
+
import { gatewayKeysEqual } from "./gateway-auth.ts";
|
|
9
|
+
import { type GatewayBackend, gatewayErrorEnvelope } from "./gateway-backend.ts";
|
|
10
|
+
import { type GatewayConfig, isLoopbackBind } from "./gateway-config.ts";
|
|
11
|
+
import { handleOpenAiChatCompletions } from "./gateway-openai-chat.ts";
|
|
12
|
+
import { handleOpenAiResponses } from "./gateway-openai-responses.ts";
|
|
13
|
+
|
|
14
|
+
export interface GatewayHttpOptions {
|
|
15
|
+
config: GatewayConfig;
|
|
16
|
+
apiKey: string;
|
|
17
|
+
backend: GatewayBackend;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
export function createGatewayHttpServer(options: GatewayHttpOptions): Server {
|
|
21
|
+
if (!isLoopbackBind(options.config.bind) && options.apiKey.length === 0) {
|
|
22
|
+
throw new Error("gateway bind outside loopback requires a Bearer API key");
|
|
23
|
+
}
|
|
24
|
+
return createServer((req, res) => {
|
|
25
|
+
void route(req, res, options).catch((error) => {
|
|
26
|
+
if (res.headersSent) {
|
|
27
|
+
res.end();
|
|
28
|
+
return;
|
|
29
|
+
}
|
|
30
|
+
const envelope = gatewayErrorEnvelope(error);
|
|
31
|
+
writeJson(res, envelope.status, envelope.body);
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function listenGateway(server: Server, config: GatewayConfig): Promise<void> {
|
|
37
|
+
return new Promise((resolve, reject) => {
|
|
38
|
+
server.once("error", reject);
|
|
39
|
+
server.listen(config.port, config.bind, () => {
|
|
40
|
+
server.off("error", reject);
|
|
41
|
+
resolve();
|
|
42
|
+
});
|
|
43
|
+
});
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
export function closeGateway(server: Server): Promise<void> {
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
server.close((error) => {
|
|
49
|
+
if (error) reject(error);
|
|
50
|
+
else resolve();
|
|
51
|
+
});
|
|
52
|
+
});
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
async function route(req: IncomingMessage, res: ServerResponse, options: GatewayHttpOptions): Promise<void> {
|
|
56
|
+
const url = new URL(req.url ?? "/", "http://gateway.invalid");
|
|
57
|
+
if (req.method === "GET" && url.pathname === "/healthz") {
|
|
58
|
+
writeJson(res, 200, { ok: true, bind: options.config.bind, port: options.config.port });
|
|
59
|
+
return;
|
|
60
|
+
}
|
|
61
|
+
if (!authorize(req, options.apiKey)) {
|
|
62
|
+
writeJson(res, 401, {
|
|
63
|
+
error: { message: "missing or invalid bearer token", type: "invalid_request_error", code: "unauthorized" },
|
|
64
|
+
});
|
|
65
|
+
return;
|
|
66
|
+
}
|
|
67
|
+
if (req.method === "GET" && url.pathname === "/v1/models") {
|
|
68
|
+
const models = await options.backend.listModels();
|
|
69
|
+
writeJson(res, 200, {
|
|
70
|
+
object: "list",
|
|
71
|
+
data: models.map((model) => ({ id: model.id, object: "model", owned_by: model.owned_by })),
|
|
72
|
+
});
|
|
73
|
+
return;
|
|
74
|
+
}
|
|
75
|
+
if (req.method === "POST" && url.pathname === "/v1/chat/completions") {
|
|
76
|
+
await handleOpenAiChatCompletions(req, res, options.backend);
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
if (req.method === "POST" && url.pathname === "/v1/responses") {
|
|
80
|
+
await handleOpenAiResponses(req, res, options.backend);
|
|
81
|
+
return;
|
|
82
|
+
}
|
|
83
|
+
if (req.method === "POST" && url.pathname === "/v1/messages") {
|
|
84
|
+
await handleAnthropicMessages(req, res, options.backend);
|
|
85
|
+
return;
|
|
86
|
+
}
|
|
87
|
+
writeJson(res, 404, { error: { message: "not found", type: "invalid_request_error", code: "not_found" } });
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function authorize(req: IncomingMessage, apiKey: string): boolean {
|
|
91
|
+
const header = req.headers.authorization;
|
|
92
|
+
if (typeof header !== "string" || !header.toLowerCase().startsWith("bearer ")) return false;
|
|
93
|
+
return gatewayKeysEqual(header.slice(7).trim(), apiKey);
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
function writeJson(res: ServerResponse, status: number, value: unknown): void {
|
|
97
|
+
const body = Buffer.from(`${JSON.stringify(value)}\n`);
|
|
98
|
+
res.writeHead(status, {
|
|
99
|
+
"content-type": "application/json; charset=utf-8",
|
|
100
|
+
"content-length": body.byteLength,
|
|
101
|
+
"cache-control": "no-store",
|
|
102
|
+
});
|
|
103
|
+
res.end(body);
|
|
104
|
+
}
|
|
@@ -0,0 +1,124 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI-compatible chat completions for the local gateway.
|
|
3
|
+
* @module dsh-coding-subscription-oauth/gateway-openai-chat
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
7
|
+
import { type GatewayBackend, gatewayErrorEnvelope } from "./gateway-backend.ts";
|
|
8
|
+
import { beginGatewaySse, readGatewayJsonBody, writeGatewayJson } from "./gateway-body.ts";
|
|
9
|
+
import { parseOpenAiChatRequest } from "./gateway-parse.ts";
|
|
10
|
+
import type { GatewayStreamPart } from "./gateway-protocol.ts";
|
|
11
|
+
|
|
12
|
+
export async function handleOpenAiChatCompletions(
|
|
13
|
+
req: IncomingMessage,
|
|
14
|
+
res: ServerResponse,
|
|
15
|
+
backend: GatewayBackend,
|
|
16
|
+
): Promise<void> {
|
|
17
|
+
const payload = await readGatewayJsonBody(req);
|
|
18
|
+
const request = parseOpenAiChatRequest(payload);
|
|
19
|
+
const stream = payload["stream"] !== false;
|
|
20
|
+
const id = `chatcmpl_gateway_${Date.now().toString(36)}`;
|
|
21
|
+
if (!stream) {
|
|
22
|
+
const aggregated = await aggregate(backend, request);
|
|
23
|
+
writeGatewayJson(res, 200, {
|
|
24
|
+
id,
|
|
25
|
+
object: "chat.completion",
|
|
26
|
+
model: request.model,
|
|
27
|
+
choices: [
|
|
28
|
+
{
|
|
29
|
+
index: 0,
|
|
30
|
+
message: aggregated.message,
|
|
31
|
+
finish_reason: aggregated.finish,
|
|
32
|
+
},
|
|
33
|
+
],
|
|
34
|
+
});
|
|
35
|
+
return;
|
|
36
|
+
}
|
|
37
|
+
beginGatewaySse(res);
|
|
38
|
+
try {
|
|
39
|
+
let toolIndex = 0;
|
|
40
|
+
for await (const part of backend.stream(request)) {
|
|
41
|
+
const chunk = sseChunk(id, request.model, part, toolIndex);
|
|
42
|
+
if (chunk === undefined) continue;
|
|
43
|
+
if (part.type === "tool_call") toolIndex += 1;
|
|
44
|
+
res.write(`data: ${JSON.stringify(chunk)}\n\n`);
|
|
45
|
+
}
|
|
46
|
+
res.write("data: [DONE]\n\n");
|
|
47
|
+
res.end();
|
|
48
|
+
} catch (error) {
|
|
49
|
+
res.write(`data: ${JSON.stringify(gatewayErrorEnvelope(error).body)}\n\n`);
|
|
50
|
+
res.end();
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
async function aggregate(backend: GatewayBackend, request: ReturnType<typeof parseOpenAiChatRequest>) {
|
|
55
|
+
let content = "";
|
|
56
|
+
let reasoning = "";
|
|
57
|
+
const toolCalls: Array<{ id: string; type: "function"; function: { name: string; arguments: string } }> = [];
|
|
58
|
+
let finish: "stop" | "tool_calls" | "length" = "stop";
|
|
59
|
+
for await (const part of backend.stream(request)) {
|
|
60
|
+
if (part.type === "text") content += part.text;
|
|
61
|
+
if (part.type === "thinking") reasoning += part.text;
|
|
62
|
+
if (part.type === "tool_call") {
|
|
63
|
+
toolCalls.push({ id: part.id, type: "function", function: { name: part.name, arguments: part.arguments } });
|
|
64
|
+
}
|
|
65
|
+
if (part.type === "done") finish = part.finish;
|
|
66
|
+
}
|
|
67
|
+
return {
|
|
68
|
+
finish,
|
|
69
|
+
message: {
|
|
70
|
+
role: "assistant",
|
|
71
|
+
content,
|
|
72
|
+
...(reasoning.length === 0 ? {} : { reasoning_content: reasoning }),
|
|
73
|
+
...(toolCalls.length === 0 ? {} : { tool_calls: toolCalls }),
|
|
74
|
+
},
|
|
75
|
+
};
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function sseChunk(id: string, model: string, part: GatewayStreamPart, toolIndex: number): unknown {
|
|
79
|
+
if (part.type === "text") {
|
|
80
|
+
return {
|
|
81
|
+
id,
|
|
82
|
+
object: "chat.completion.chunk",
|
|
83
|
+
model,
|
|
84
|
+
choices: [{ index: 0, delta: { content: part.text }, finish_reason: null }],
|
|
85
|
+
};
|
|
86
|
+
}
|
|
87
|
+
if (part.type === "thinking") {
|
|
88
|
+
return {
|
|
89
|
+
id,
|
|
90
|
+
object: "chat.completion.chunk",
|
|
91
|
+
model,
|
|
92
|
+
choices: [{ index: 0, delta: { reasoning_content: part.text }, finish_reason: null }],
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
if (part.type === "tool_call") {
|
|
96
|
+
return {
|
|
97
|
+
id,
|
|
98
|
+
object: "chat.completion.chunk",
|
|
99
|
+
model,
|
|
100
|
+
choices: [
|
|
101
|
+
{
|
|
102
|
+
index: 0,
|
|
103
|
+
delta: {
|
|
104
|
+
tool_calls: [
|
|
105
|
+
{
|
|
106
|
+
index: toolIndex,
|
|
107
|
+
id: part.id,
|
|
108
|
+
type: "function",
|
|
109
|
+
function: { name: part.name, arguments: part.arguments },
|
|
110
|
+
},
|
|
111
|
+
],
|
|
112
|
+
},
|
|
113
|
+
finish_reason: null,
|
|
114
|
+
},
|
|
115
|
+
],
|
|
116
|
+
};
|
|
117
|
+
}
|
|
118
|
+
return {
|
|
119
|
+
id,
|
|
120
|
+
object: "chat.completion.chunk",
|
|
121
|
+
model,
|
|
122
|
+
choices: [{ index: 0, delta: {}, finish_reason: part.finish }],
|
|
123
|
+
};
|
|
124
|
+
}
|
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OpenAI Responses API subset for the local gateway.
|
|
3
|
+
* @module dsh-coding-subscription-oauth/gateway-openai-responses
|
|
4
|
+
*/
|
|
5
|
+
|
|
6
|
+
import type { IncomingMessage, ServerResponse } from "node:http";
|
|
7
|
+
import { type GatewayBackend, gatewayErrorEnvelope } from "./gateway-backend.ts";
|
|
8
|
+
import { beginGatewaySse, readGatewayJsonBody, writeGatewayJson } from "./gateway-body.ts";
|
|
9
|
+
import { parseOpenAiResponsesRequest } from "./gateway-parse.ts";
|
|
10
|
+
|
|
11
|
+
export async function handleOpenAiResponses(
|
|
12
|
+
req: IncomingMessage,
|
|
13
|
+
res: ServerResponse,
|
|
14
|
+
backend: GatewayBackend,
|
|
15
|
+
): Promise<void> {
|
|
16
|
+
const payload = await readGatewayJsonBody(req);
|
|
17
|
+
const request = parseOpenAiResponsesRequest(payload);
|
|
18
|
+
const stream = payload["stream"] !== false;
|
|
19
|
+
const id = `resp_gateway_${Date.now().toString(36)}`;
|
|
20
|
+
if (!stream) {
|
|
21
|
+
let text = "";
|
|
22
|
+
for await (const part of backend.stream(request)) {
|
|
23
|
+
if (part.type === "text") text += part.text;
|
|
24
|
+
}
|
|
25
|
+
writeGatewayJson(res, 200, {
|
|
26
|
+
id,
|
|
27
|
+
object: "response",
|
|
28
|
+
model: request.model,
|
|
29
|
+
status: "completed",
|
|
30
|
+
output: [{ type: "message", role: "assistant", content: [{ type: "output_text", text }] }],
|
|
31
|
+
});
|
|
32
|
+
return;
|
|
33
|
+
}
|
|
34
|
+
beginGatewaySse(res);
|
|
35
|
+
try {
|
|
36
|
+
res.write(
|
|
37
|
+
`event: response.created\ndata: ${JSON.stringify({ id, object: "response", model: request.model, status: "in_progress" })}\n\n`,
|
|
38
|
+
);
|
|
39
|
+
for await (const part of backend.stream(request)) {
|
|
40
|
+
if (part.type === "text") {
|
|
41
|
+
res.write(`event: response.output_text.delta\ndata: ${JSON.stringify({ id, delta: part.text })}\n\n`);
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
res.write(
|
|
45
|
+
`event: response.completed\ndata: ${JSON.stringify({ id, object: "response", status: "completed" })}\n\n`,
|
|
46
|
+
);
|
|
47
|
+
res.write("data: [DONE]\n\n");
|
|
48
|
+
res.end();
|
|
49
|
+
} catch (error) {
|
|
50
|
+
res.write(`event: error\ndata: ${JSON.stringify(gatewayErrorEnvelope(error).body)}\n\n`);
|
|
51
|
+
res.end();
|
|
52
|
+
}
|
|
53
|
+
}
|