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,274 +1,274 @@
1
- /**
2
- * Session-backed model listing and event streaming for the local gateway.
3
- * @module dsh-coding-subscription-oauth/gateway-backend
4
- */
5
-
6
- import type { Api, Context, Message, Model, ThinkingLevel, Tool } from "@earendil-works/pi-ai";
7
- import {
8
- type GatewayChatMessage,
9
- type GatewayCompletionRequest,
10
- type GatewayStreamPart,
11
- type GatewayTool,
12
- isThinkingLevel,
13
- } from "./gateway-protocol.ts";
14
- import type { OAuthProviderSession } from "./oauth-session.ts";
15
- import { safeMessage } from "./redact.ts";
16
- import type { GrokBuildSession } from "./session.ts";
17
-
18
- export interface GatewayListedModel {
19
- id: string;
20
- owned_by: string;
21
- }
22
-
23
- export interface GatewayBackend {
24
- listModels(): Promise<readonly GatewayListedModel[]>;
25
- stream(request: GatewayCompletionRequest): AsyncIterable<GatewayStreamPart>;
26
- streamText(modelId: string, messages: readonly GatewayChatMessage[]): AsyncIterable<string>;
27
- }
28
-
29
- export class GatewayRequestError extends Error {
30
- constructor(
31
- readonly status: number,
32
- readonly code: string,
33
- message: string,
34
- ) {
35
- super(message);
36
- }
37
- }
38
-
39
- interface OwnedModel {
40
- owned_by: string;
41
- model: Model<Api>;
42
- stream: (
43
- model: Model<Api>,
44
- context: Context,
45
- options?: { reasoning?: ThinkingLevel },
46
- ) => AsyncIterable<{
47
- type: string;
48
- delta?: string;
49
- errorMessage?: string;
50
- reason?: string;
51
- toolCall?: { id: string; name: string; arguments?: unknown };
52
- partial?: { content?: readonly { type?: string; id?: string; name?: string }[] };
53
- }>;
54
- }
55
-
56
- const EMPTY_USAGE = {
57
- input: 0,
58
- output: 0,
59
- cacheRead: 0,
60
- cacheWrite: 0,
61
- totalTokens: 0,
62
- cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 },
63
- };
64
-
65
- export function createSessionGatewayBackend(
66
- grok: GrokBuildSession,
67
- subscriptions: readonly OAuthProviderSession[],
68
- ): GatewayBackend {
69
- return {
70
- async listModels() {
71
- const listed: GatewayListedModel[] = [];
72
- const seen = new Map<string, string>();
73
- for (const owned of await collectOwnedModels(grok, subscriptions)) {
74
- const previous = seen.get(owned.model.id);
75
- if (previous !== undefined && previous !== owned.owned_by) continue;
76
- seen.set(owned.model.id, owned.owned_by);
77
- listed.push({ id: owned.model.id, owned_by: owned.owned_by });
78
- }
79
- return listed;
80
- },
81
- async *stream(request) {
82
- const owned = selectOwnedModel(await collectOwnedModels(grok, subscriptions), request.model);
83
- const context = buildGatewayContext(request.messages, request.tools);
84
- const reasoning = resolveReasoning(request.reasoning, owned.owned_by);
85
- let usedTools = false;
86
- for await (const event of owned.stream(
87
- owned.model,
88
- context,
89
- reasoning === undefined ? undefined : { reasoning },
90
- )) {
91
- if (event.type === "text_delta" && typeof event.delta === "string" && event.delta.length > 0) {
92
- yield { type: "text", text: event.delta };
93
- }
94
- if (event.type === "thinking_delta" && typeof event.delta === "string" && event.delta.length > 0) {
95
- yield { type: "thinking", text: event.delta };
96
- }
97
- if (event.type === "toolcall_end" && event.toolCall !== undefined) {
98
- usedTools = true;
99
- yield {
100
- type: "tool_call",
101
- index: 0,
102
- id: event.toolCall.id,
103
- name: event.toolCall.name,
104
- arguments: stringifyToolArguments(event.toolCall.arguments),
105
- };
106
- }
107
- if (event.type === "error") {
108
- throw new GatewayRequestError(502, "upstream_error", event.errorMessage ?? "upstream stream error");
109
- }
110
- if (event.type === "done") {
111
- const finish =
112
- event.reason === "length" ? "length" : usedTools || event.reason === "toolUse" ? "tool_calls" : "stop";
113
- yield { type: "done", finish };
114
- }
115
- }
116
- },
117
- async *streamText(modelId, messages) {
118
- for await (const part of this.stream({ model: modelId, messages })) {
119
- if (part.type === "text") yield part.text;
120
- }
121
- },
122
- };
123
- }
124
-
125
- export function selectOwnedModel(owned: readonly OwnedModel[], modelId: string): OwnedModel {
126
- const matches = owned.filter((item) => item.model.id === modelId);
127
- if (matches.length === 0) throw new GatewayRequestError(404, "model_not_found", `Unknown model ${modelId}`);
128
- const owners = new Set(matches.map((item) => item.owned_by));
129
- if (owners.size > 1) {
130
- throw new GatewayRequestError(404, "model_not_found", `Model ${modelId} is owned by multiple signed-in providers`);
131
- }
132
- return matches[0]!;
133
- }
134
-
135
- export function buildGatewayContext(messages: readonly GatewayChatMessage[], tools?: readonly GatewayTool[]): Context {
136
- let systemPrompt: string | undefined;
137
- const mapped: Message[] = [];
138
- for (const message of messages) {
139
- if (message.role === "system") {
140
- systemPrompt = `${systemPrompt === undefined ? "" : `${systemPrompt}\n`}${message.content}`;
141
- continue;
142
- }
143
- if (message.role === "assistant") {
144
- mapped.push(assistantReplay(message));
145
- continue;
146
- }
147
- if (message.role === "tool") {
148
- mapped.push({
149
- role: "toolResult",
150
- toolCallId: message.tool_call_id ?? "",
151
- toolName: message.tool_name ?? "tool",
152
- content: [{ type: "text", text: message.content }],
153
- isError: false,
154
- timestamp: Date.now(),
155
- });
156
- continue;
157
- }
158
- mapped.push({ role: "user", content: message.content, timestamp: Date.now() });
159
- }
160
- const context: Context = systemPrompt === undefined ? { messages: mapped } : { systemPrompt, messages: mapped };
161
- if (tools !== undefined && tools.length > 0) context.tools = tools.map(toPiTool);
162
- return context;
163
- }
164
-
165
- export function assistantReplay(message: GatewayChatMessage): Message {
166
- const content: Array<
167
- | { type: "text"; text: string }
168
- | { type: "thinking"; thinking: string }
169
- | { type: "toolCall"; id: string; name: string; arguments: Record<string, unknown> }
170
- > = [];
171
- const needsPlaceholder = message.tool_calls !== undefined && message.tool_calls.length > 0;
172
- const reasoning = message.reasoning_content ?? (needsPlaceholder ? "" : undefined);
173
- if (reasoning !== undefined) content.push({ type: "thinking", thinking: reasoning });
174
- if (message.content.length > 0) content.push({ type: "text", text: message.content });
175
- if (message.tool_calls !== undefined) {
176
- for (const call of message.tool_calls) {
177
- content.push({
178
- type: "toolCall",
179
- id: call.id,
180
- name: call.name,
181
- arguments: parseToolArguments(call.arguments),
182
- });
183
- }
184
- }
185
- return {
186
- role: "assistant",
187
- content: content.length === 0 ? [{ type: "text", text: "" }] : content,
188
- api: "openai-responses",
189
- provider: "gateway",
190
- model: "gateway",
191
- usage: EMPTY_USAGE,
192
- stopReason: needsPlaceholder ? "toolUse" : "stop",
193
- timestamp: Date.now(),
194
- };
195
- }
196
-
197
- function toPiTool(tool: GatewayTool): Tool {
198
- return {
199
- name: tool.name,
200
- description: tool.description,
201
- parameters: tool.parameters as Tool["parameters"],
202
- };
203
- }
204
-
205
- function parseToolArguments(raw: string): Record<string, unknown> {
206
- try {
207
- const value = JSON.parse(raw) as unknown;
208
- return typeof value === "object" && value !== null && !Array.isArray(value)
209
- ? (value as Record<string, unknown>)
210
- : { value };
211
- } catch {
212
- return { value: raw };
213
- }
214
- }
215
-
216
- function stringifyToolArguments(value: unknown): string {
217
- if (typeof value === "string") return value;
218
- try {
219
- return JSON.stringify(value ?? {});
220
- } catch {
221
- return "{}";
222
- }
223
- }
224
-
225
- function resolveReasoning(value: string | undefined, ownedBy: string): ThinkingLevel | undefined {
226
- if (value === undefined || !isThinkingLevel(value)) return undefined;
227
- if (ownedBy === "kimi-code-oauth" || ownedBy === "claude-code-oauth") return undefined;
228
- return value as ThinkingLevel;
229
- }
230
-
231
- async function collectOwnedModels(
232
- grok: GrokBuildSession,
233
- subscriptions: readonly OAuthProviderSession[],
234
- ): Promise<OwnedModel[]> {
235
- const owned: OwnedModel[] = [];
236
- const grokAuth = await grok.models.getAuth("xai");
237
- if (grokAuth?.auth.apiKey) {
238
- for (const model of grok.visibleModels()) {
239
- owned.push({
240
- owned_by: "grok-build",
241
- model,
242
- stream: (item, context, options) => grok.models.streamSimple(item, context, options),
243
- });
244
- }
245
- }
246
- for (const session of subscriptions) {
247
- const status = await session.status();
248
- if (!status.authenticated) continue;
249
- for (const model of session.visibleModels()) {
250
- owned.push({
251
- owned_by: session.definition.route,
252
- model,
253
- stream: (item, context, options) => session.models.streamSimple(item, context, options),
254
- });
255
- }
256
- }
257
- return owned;
258
- }
259
-
260
- export function gatewayErrorEnvelope(error: unknown): {
261
- status: number;
262
- body: { error: { message: string; type: string; code: string } };
263
- } {
264
- if (error instanceof GatewayRequestError) {
265
- return {
266
- status: error.status,
267
- body: { error: { message: error.message.slice(0, 1000), type: "invalid_request_error", code: error.code } },
268
- };
269
- }
270
- return {
271
- status: 500,
272
- body: { error: { message: safeMessage(error).slice(0, 1000), type: "server_error", code: "internal" } },
273
- };
274
- }
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 +1,49 @@
1
- /**
2
- * Shared JSON body reader for isolated gateway endpoints.
3
- * @module dsh-coding-subscription-oauth/gateway-body
4
- */
5
-
6
- import type { IncomingMessage } from "node:http";
7
- import { GatewayRequestError } from "./gateway-backend.ts";
8
-
9
- const BODY_LIMIT = 1024 * 1024;
10
-
11
- export async function readGatewayJsonBody(req: IncomingMessage): Promise<Record<string, unknown>> {
12
- const chunks: Buffer[] = [];
13
- let size = 0;
14
- for await (const chunk of req) {
15
- const buffer = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);
16
- size += buffer.byteLength;
17
- if (size > BODY_LIMIT) throw new GatewayRequestError(413, "payload_too_large", "request body exceeds 1 MiB");
18
- chunks.push(buffer);
19
- }
20
- if (chunks.length === 0) return {};
21
- try {
22
- const value = JSON.parse(Buffer.concat(chunks).toString("utf8")) as unknown;
23
- if (typeof value !== "object" || value === null || Array.isArray(value)) {
24
- throw new GatewayRequestError(400, "invalid_request", "body must be a JSON object");
25
- }
26
- return value as Record<string, unknown>;
27
- } catch (error) {
28
- if (error instanceof GatewayRequestError) throw error;
29
- throw new GatewayRequestError(400, "invalid_request", "body is not valid JSON");
30
- }
31
- }
32
-
33
- export function writeGatewayJson(res: import("node:http").ServerResponse, status: number, value: unknown): void {
34
- const body = Buffer.from(`${JSON.stringify(value)}\n`);
35
- res.writeHead(status, {
36
- "content-type": "application/json; charset=utf-8",
37
- "content-length": body.byteLength,
38
- "cache-control": "no-store",
39
- });
40
- res.end(body);
41
- }
42
-
43
- export function beginGatewaySse(res: import("node:http").ServerResponse): void {
44
- res.writeHead(200, {
45
- "content-type": "text/event-stream; charset=utf-8",
46
- "cache-control": "no-store",
47
- connection: "close",
48
- });
49
- }
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
+ }