dsh-coding-subscription-oauth 0.6.2 → 0.6.3

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