dsh-coding-subscription-oauth 0.6.3 → 0.6.4

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