dsh-coding-subscription-oauth 0.5.7 → 0.6.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.
Files changed (141) hide show
  1. package/CHANGELOG.md +211 -182
  2. package/CONTRIBUTING.md +120 -109
  3. package/INSTALL.md +240 -209
  4. package/LICENSE +19 -19
  5. package/NOTICE +11 -11
  6. package/README.de.md +298 -293
  7. package/README.es.md +299 -294
  8. package/README.fr.md +299 -294
  9. package/README.ja.md +299 -294
  10. package/README.ko.md +299 -294
  11. package/README.md +313 -306
  12. package/README.pt-BR.md +299 -294
  13. package/README.ru.md +299 -294
  14. package/README.zh-CN.md +311 -304
  15. package/compatibility/dsh-bom.json +43 -0
  16. package/cordis.patch.yml +13 -13
  17. package/docs/00-project-rules.md +195 -195
  18. package/docs/02-architecture.md +134 -129
  19. package/docs/02-architecture.zh-CN.md +134 -129
  20. package/lib/auth-routes.d.ts +8 -15
  21. package/lib/auth-routes.d.ts.map +1 -1
  22. package/lib/bin.js +746 -1402
  23. package/lib/bin.js.map +4 -4
  24. package/lib/capability-routes.d.ts +3 -3
  25. package/lib/capability-routes.d.ts.map +1 -1
  26. package/lib/capability-settings.d.ts +5 -4
  27. package/lib/capability-settings.d.ts.map +1 -1
  28. package/lib/client.js +27 -8
  29. package/lib/client.js.map +4 -4
  30. package/lib/compatibility.d.ts +46 -0
  31. package/lib/compatibility.d.ts.map +1 -0
  32. package/lib/dsh-host-adapter.d.ts +18 -0
  33. package/lib/dsh-host-adapter.d.ts.map +1 -0
  34. package/lib/gateway-auth.d.ts +1 -2
  35. package/lib/gateway-auth.d.ts.map +1 -1
  36. package/lib/gateway-routes.d.ts +3 -4
  37. package/lib/gateway-routes.d.ts.map +1 -1
  38. package/lib/gateway.d.ts +4 -0
  39. package/lib/gateway.d.ts.map +1 -1
  40. package/lib/ids.d.ts +3 -32
  41. package/lib/ids.d.ts.map +1 -1
  42. package/lib/imagine-routes.d.ts +2 -0
  43. package/lib/imagine-routes.d.ts.map +1 -1
  44. package/lib/index.d.ts +19 -4
  45. package/lib/index.d.ts.map +1 -1
  46. package/lib/index.js +26573 -1023
  47. package/lib/index.js.map +4 -4
  48. package/lib/invariant.js.map +1 -1
  49. package/lib/oauth-import-routes.d.ts +3 -4
  50. package/lib/oauth-import-routes.d.ts.map +1 -1
  51. package/lib/proxy.d.ts +3 -16
  52. package/lib/proxy.d.ts.map +1 -1
  53. package/lib/web-origin.d.ts +28 -4
  54. package/lib/web-origin.d.ts.map +1 -1
  55. package/lib/web-routes.d.ts.map +1 -1
  56. package/media/en/settings_accounts.png +0 -0
  57. package/media/en/settings_capabilities.png +0 -0
  58. package/media/en/settings_gateway.png +0 -0
  59. package/media/zh-CN/settings_accounts.png +0 -0
  60. package/media/zh-CN/settings_capabilities.png +0 -0
  61. package/media/zh-CN/settings_gateway.png +0 -0
  62. package/package.json +209 -172
  63. package/patches/dsh-agy@0.1.2.patch +25 -25
  64. package/scripts/release.mjs +186 -166
  65. package/scripts/smoke-deployed-routes.mjs +146 -146
  66. package/scripts/verify-deployed-catalog.mjs +87 -87
  67. package/src/adapter.ts +287 -287
  68. package/src/alias-adapter.ts +153 -153
  69. package/src/auth-routes.ts +921 -871
  70. package/src/auth.ts +67 -67
  71. package/src/bin.ts +350 -350
  72. package/src/capability-routes.ts +279 -275
  73. package/src/capability-runtime.ts +313 -313
  74. package/src/capability-settings.ts +658 -657
  75. package/src/capability-tools.ts +666 -666
  76. package/src/catalog.ts +271 -271
  77. package/src/client/GrokBuildSettings.tsx +770 -718
  78. package/src/client/api.ts +88 -88
  79. package/src/client/components/AboutTab.tsx +30 -20
  80. package/src/client/components/AccountsTab.tsx +241 -224
  81. package/src/client/components/Badge.tsx +33 -33
  82. package/src/client/components/CapabilitiesTab.tsx +265 -227
  83. package/src/client/components/CliPullPreview.tsx +116 -107
  84. package/src/client/components/CopyButton.tsx +57 -57
  85. package/src/client/components/GatewayTab.tsx +469 -364
  86. package/src/client/components/NoticeBanner.tsx +46 -46
  87. package/src/client/components/ProgressBar.tsx +53 -52
  88. package/src/client/components/ProviderCard.tsx +606 -502
  89. package/src/client/components/SettingsTabs.tsx +75 -75
  90. package/src/client/components/ToggleSwitch.tsx +71 -62
  91. package/src/client/constants.ts +224 -206
  92. package/src/client/display.ts +61 -61
  93. package/src/client/dshClientAdapter.ts +109 -0
  94. package/src/client/gatewaySnippets.ts +37 -36
  95. package/src/client/index.tsx +156 -37
  96. package/src/client/locales.ts +535 -487
  97. package/src/client/microStyles.ts +52 -33
  98. package/src/client/parsers.ts +396 -386
  99. package/src/client/styles.ts +325 -312
  100. package/src/client/types.ts +197 -185
  101. package/src/codex-http.ts +447 -447
  102. package/src/codex-images.ts +485 -485
  103. package/src/codex-model-capabilities.ts +320 -320
  104. package/src/codex-search.ts +245 -245
  105. package/src/codex-usage.ts +263 -263
  106. package/src/compatibility.ts +55 -0
  107. package/src/dsh-host-adapter.ts +171 -0
  108. package/src/gateway-anthropic-messages.ts +84 -84
  109. package/src/gateway-auth.ts +102 -100
  110. package/src/gateway-backend.ts +274 -274
  111. package/src/gateway-body.ts +49 -49
  112. package/src/gateway-config.ts +76 -76
  113. package/src/gateway-http.ts +104 -104
  114. package/src/gateway-openai-chat.ts +124 -124
  115. package/src/gateway-openai-responses.ts +53 -53
  116. package/src/gateway-parse.ts +224 -224
  117. package/src/gateway-protocol.ts +52 -52
  118. package/src/gateway-routes.ts +158 -152
  119. package/src/gateway.ts +258 -242
  120. package/src/grok-errors.ts +24 -24
  121. package/src/grok-imagine.ts +1627 -1627
  122. package/src/grok-import.ts +151 -151
  123. package/src/http-json.ts +82 -82
  124. package/src/ids.ts +59 -45
  125. package/src/imagine-routes.ts +463 -461
  126. package/src/index.ts +748 -598
  127. package/src/invariant.ts +17 -17
  128. package/src/kimi-errors.ts +26 -26
  129. package/src/media-store.ts +927 -927
  130. package/src/oauth-import-routes.ts +324 -314
  131. package/src/oauth-providers.ts +152 -152
  132. package/src/oauth-session.ts +183 -183
  133. package/src/oauth-sources.ts +1104 -1104
  134. package/src/oauth.ts +620 -620
  135. package/src/provider.ts +128 -128
  136. package/src/proxy.ts +11 -99
  137. package/src/redact.ts +72 -72
  138. package/src/session.ts +218 -218
  139. package/src/store.ts +217 -217
  140. package/src/web-origin.ts +296 -60
  141. package/src/web-routes.ts +38 -75
@@ -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
+ }