dsh-coding-subscription-oauth 0.6.3 → 0.6.5

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.
Files changed (127) hide show
  1. package/CHANGELOG.md +33 -0
  2. package/CONTRIBUTING.md +13 -4
  3. package/INSTALL.md +7 -5
  4. package/README.de.md +6 -6
  5. package/README.es.md +6 -6
  6. package/README.fr.md +6 -6
  7. package/README.ja.md +6 -6
  8. package/README.ko.md +6 -6
  9. package/README.md +6 -6
  10. package/README.pt-BR.md +6 -6
  11. package/README.ru.md +6 -6
  12. package/README.zh-CN.md +6 -6
  13. package/docs/00-project-rules.md +4 -4
  14. package/docs/02-architecture.md +7 -3
  15. package/docs/02-architecture.zh-CN.md +7 -3
  16. package/lib/bin.js +1333 -569
  17. package/lib/bin.js.map +4 -4
  18. package/lib/client.js +1 -1
  19. package/lib/client.js.map +2 -2
  20. package/lib/gateway-protocol.d.ts +3 -46
  21. package/lib/gateway-protocol.d.ts.map +1 -1
  22. package/lib/gateway-routes.d.ts.map +1 -1
  23. package/lib/grok-errors.d.ts +2 -12
  24. package/lib/grok-errors.d.ts.map +1 -1
  25. package/lib/grok-imagine/client.d.ts +73 -0
  26. package/lib/grok-imagine/client.d.ts.map +1 -0
  27. package/lib/grok-imagine/index.d.ts +8 -0
  28. package/lib/grok-imagine/index.d.ts.map +1 -0
  29. package/lib/grok-imagine/net.d.ts +10 -0
  30. package/lib/grok-imagine/net.d.ts.map +1 -0
  31. package/lib/grok-imagine/parse.d.ts +20 -0
  32. package/lib/grok-imagine/parse.d.ts.map +1 -0
  33. package/lib/grok-imagine/types.d.ts +191 -0
  34. package/lib/grok-imagine/types.d.ts.map +1 -0
  35. package/lib/grok-imagine.d.ts +3 -263
  36. package/lib/grok-imagine.d.ts.map +1 -1
  37. package/lib/http-json.d.ts +2 -9
  38. package/lib/http-json.d.ts.map +1 -1
  39. package/lib/index.js +1395 -26178
  40. package/lib/index.js.map +4 -4
  41. package/lib/kimi-errors.d.ts +2 -12
  42. package/lib/kimi-errors.d.ts.map +1 -1
  43. package/lib/runtime/gateway-protocol.d.ts +47 -0
  44. package/lib/runtime/gateway-protocol.d.ts.map +1 -0
  45. package/lib/runtime/grok-errors.d.ts +13 -0
  46. package/lib/runtime/grok-errors.d.ts.map +1 -0
  47. package/lib/runtime/http-json.d.ts +10 -0
  48. package/lib/runtime/http-json.d.ts.map +1 -0
  49. package/lib/runtime/kimi-errors.d.ts +13 -0
  50. package/lib/runtime/kimi-errors.d.ts.map +1 -0
  51. package/package.json +12 -7
  52. package/scripts/release.mjs +1 -0
  53. package/src/adapter.ts +0 -348
  54. package/src/alias-adapter.ts +0 -147
  55. package/src/auth-routes.ts +0 -921
  56. package/src/auth.ts +0 -67
  57. package/src/bin.ts +0 -350
  58. package/src/capability-routes.ts +0 -279
  59. package/src/capability-runtime.ts +0 -314
  60. package/src/capability-settings.ts +0 -671
  61. package/src/capability-tools.ts +0 -685
  62. package/src/catalog.ts +0 -271
  63. package/src/client/GrokBuildSettings.tsx +0 -771
  64. package/src/client/api.ts +0 -88
  65. package/src/client/components/AboutTab.tsx +0 -30
  66. package/src/client/components/AccountsTab.tsx +0 -241
  67. package/src/client/components/Badge.tsx +0 -33
  68. package/src/client/components/CapabilitiesTab.tsx +0 -265
  69. package/src/client/components/CliPullPreview.tsx +0 -116
  70. package/src/client/components/CopyButton.tsx +0 -57
  71. package/src/client/components/GatewayTab.tsx +0 -469
  72. package/src/client/components/NoticeBanner.tsx +0 -46
  73. package/src/client/components/ProgressBar.tsx +0 -53
  74. package/src/client/components/ProviderCard.tsx +0 -606
  75. package/src/client/components/SettingsTabs.tsx +0 -75
  76. package/src/client/components/ToggleSwitch.tsx +0 -71
  77. package/src/client/constants.ts +0 -230
  78. package/src/client/display.ts +0 -61
  79. package/src/client/dshClientAdapter.ts +0 -127
  80. package/src/client/gatewaySnippets.ts +0 -37
  81. package/src/client/index.tsx +0 -156
  82. package/src/client/locales.ts +0 -540
  83. package/src/client/microStyles.ts +0 -52
  84. package/src/client/parsers.ts +0 -398
  85. package/src/client/styles.ts +0 -325
  86. package/src/client/types.ts +0 -199
  87. package/src/codex-http.ts +0 -447
  88. package/src/codex-images.ts +0 -503
  89. package/src/codex-model-capabilities.ts +0 -320
  90. package/src/codex-search.ts +0 -245
  91. package/src/codex-usage.ts +0 -263
  92. package/src/compatibility.ts +0 -55
  93. package/src/dsh-host-adapter.ts +0 -173
  94. package/src/gateway-anthropic-messages.ts +0 -84
  95. package/src/gateway-auth.ts +0 -102
  96. package/src/gateway-backend.ts +0 -274
  97. package/src/gateway-body.ts +0 -49
  98. package/src/gateway-config.ts +0 -76
  99. package/src/gateway-http.ts +0 -104
  100. package/src/gateway-openai-chat.ts +0 -124
  101. package/src/gateway-openai-responses.ts +0 -53
  102. package/src/gateway-parse.ts +0 -224
  103. package/src/gateway-protocol.ts +0 -52
  104. package/src/gateway-routes.ts +0 -158
  105. package/src/gateway.ts +0 -258
  106. package/src/grok-errors.ts +0 -24
  107. package/src/grok-imagine.ts +0 -1627
  108. package/src/grok-import.ts +0 -151
  109. package/src/http-json.ts +0 -82
  110. package/src/ids.ts +0 -59
  111. package/src/imagine-routes.ts +0 -463
  112. package/src/index.ts +0 -735
  113. package/src/invariant.ts +0 -17
  114. package/src/kimi-errors.ts +0 -26
  115. package/src/media-store.ts +0 -927
  116. package/src/oauth-import-routes.ts +0 -324
  117. package/src/oauth-providers.ts +0 -152
  118. package/src/oauth-session.ts +0 -183
  119. package/src/oauth-sources.ts +0 -1104
  120. package/src/oauth.ts +0 -620
  121. package/src/provider.ts +0 -128
  122. package/src/proxy.ts +0 -11
  123. package/src/redact.ts +0 -72
  124. package/src/session.ts +0 -218
  125. package/src/store.ts +0 -217
  126. package/src/web-origin.ts +0 -296
  127. package/src/web-routes.ts +0 -38
@@ -1,274 +0,0 @@
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
- }
@@ -1,49 +0,0 @@
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
- }
@@ -1,76 +0,0 @@
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
- }
@@ -1,104 +0,0 @@
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
- }
@@ -1,124 +0,0 @@
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
- }
@@ -1,53 +0,0 @@
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
- }