qwenproxy-cli 1.0.0 → 1.0.1

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 (108) hide show
  1. package/LICENSE +14 -14
  2. package/README.md +906 -906
  3. package/bin/qwenproxy.js +5 -1
  4. package/package.json +78 -78
  5. package/src/api/error-classifier.ts +159 -159
  6. package/src/api/error-helpers.ts +118 -118
  7. package/src/api/models.ts +261 -261
  8. package/src/api/server.ts +860 -859
  9. package/src/cache/memory-cache.ts +385 -385
  10. package/src/clean-cache.ts +204 -204
  11. package/src/core/account-concurrency.ts +671 -671
  12. package/src/core/account-manager.ts +301 -297
  13. package/src/core/account-priority.ts +163 -163
  14. package/src/core/accounts.ts +186 -186
  15. package/src/core/config.ts +383 -383
  16. package/src/core/crypto-utils.ts +79 -79
  17. package/src/core/database.ts +276 -276
  18. package/src/core/errors.ts +118 -118
  19. package/src/core/logger.ts +269 -269
  20. package/src/core/memory-usage.ts +84 -84
  21. package/src/core/metrics.ts +291 -291
  22. package/src/core/model-alias.ts +77 -77
  23. package/src/core/model-registry.ts +544 -544
  24. package/src/core/mutex.ts +119 -119
  25. package/src/core/paths.ts +199 -199
  26. package/src/core/prompt-limits.ts +214 -214
  27. package/src/core/reasoning-effort.ts +102 -102
  28. package/src/core/stream-registry.ts +96 -96
  29. package/src/core/waf-isolation.ts +117 -117
  30. package/src/core/watchdog.ts +195 -195
  31. package/src/delete-chats.ts +23 -23
  32. package/src/index.ts +65 -64
  33. package/src/login.ts +147 -147
  34. package/src/reset-cooldowns.ts +11 -11
  35. package/src/routes/anthropic/index.ts +355 -355
  36. package/src/routes/anthropic/translate.ts +522 -522
  37. package/src/routes/anthropic/types.ts +154 -154
  38. package/src/routes/anthropic/validation.ts +144 -144
  39. package/src/routes/chat/account.ts +1817 -1817
  40. package/src/routes/chat/context.ts +241 -241
  41. package/src/routes/chat/errors.ts +85 -85
  42. package/src/routes/chat/helpers.ts +268 -268
  43. package/src/routes/chat/index.ts +618 -618
  44. package/src/routes/chat/media.ts +285 -285
  45. package/src/routes/chat/retry-policy.ts +754 -754
  46. package/src/routes/chat/stop.ts +98 -98
  47. package/src/routes/chat/streaming.ts +2710 -2710
  48. package/src/routes/chat/validation.ts +526 -526
  49. package/src/routes/chat.ts +2 -2
  50. package/src/routes/completions.ts +290 -290
  51. package/src/routes/images.ts +139 -139
  52. package/src/routes/responses/adapter.ts +503 -503
  53. package/src/routes/responses/index.ts +405 -405
  54. package/src/routes/responses/state.ts +230 -230
  55. package/src/routes/responses/streaming.ts +528 -528
  56. package/src/routes/responses/types.ts +285 -285
  57. package/src/routes/responses/validation.ts +202 -202
  58. package/src/routes/upload.ts +731 -731
  59. package/src/routes/videos.ts +214 -214
  60. package/src/services/auth-playwright.ts +173 -173
  61. package/src/services/captcha-coordinator.ts +161 -161
  62. package/src/services/captcha-solver.ts +553 -553
  63. package/src/services/chat-cleanup.ts +80 -80
  64. package/src/services/context-meter.ts +317 -317
  65. package/src/services/fingerprint.ts +242 -242
  66. package/src/services/human-behavior.ts +173 -173
  67. package/src/services/media-generation.ts +1748 -1748
  68. package/src/services/playwright.ts +2800 -2800
  69. package/src/services/qwen-chat-pool.ts +345 -345
  70. package/src/services/qwen-errors.ts +133 -133
  71. package/src/services/qwen-headers.ts +79 -79
  72. package/src/services/qwen-thread-state.ts +393 -393
  73. package/src/services/qwen-url.ts +19 -19
  74. package/src/services/qwen.ts +3126 -3126
  75. package/src/services/session-keeper.ts +88 -88
  76. package/src/services/token-estimation-metrics.ts +118 -118
  77. package/src/sync/claude-code.ts +75 -75
  78. package/src/sync/codex.ts +123 -123
  79. package/src/sync/index.ts +362 -362
  80. package/src/sync/omp.ts +105 -105
  81. package/src/sync/opencode.ts +214 -214
  82. package/src/sync/types.ts +53 -53
  83. package/src/sync/utils.ts +27 -27
  84. package/src/sync-clients.ts +189 -189
  85. package/src/tools/instructions.ts +137 -137
  86. package/src/tools/manifest.ts +81 -81
  87. package/src/tools/parser.ts +2989 -2989
  88. package/src/tools/toolcall-tags.ts +142 -142
  89. package/src/tui/app.ts +264 -264
  90. package/src/tui/index.ts +61 -61
  91. package/src/tui/markdown.ts +258 -258
  92. package/src/tui/proxy-client.ts +331 -326
  93. package/src/tui/screen.ts +294 -278
  94. package/src/tui/server-manager.ts +270 -270
  95. package/src/tui/theme.ts +432 -432
  96. package/src/tui/types.ts +33 -33
  97. package/src/tui/views/accounts-view.ts +656 -656
  98. package/src/tui/views/chat-view.ts +1018 -823
  99. package/src/tui/views/logs-view.ts +479 -413
  100. package/src/tui/views/status-view.ts +204 -204
  101. package/src/tui/views/storage-view.ts +304 -291
  102. package/src/tui/views/sync-view.ts +409 -409
  103. package/src/types/ali-oss.d.ts +32 -32
  104. package/src/utils/context-truncation.ts +84 -84
  105. package/src/utils/json.ts +380 -380
  106. package/src/utils/session-id.ts +37 -37
  107. package/src/utils/tool-call-guard.ts +84 -84
  108. package/src/utils/types.ts +109 -109
@@ -1,285 +1,285 @@
1
- /**
2
- * Native image/video generation over /v1/chat/completions. When the client
3
- * selects a generation-specific model (qwen-image-*, wan2.*), the request is
4
- * routed here instead of the text chat flow, mirroring how the Qwen web app
5
- * switches chat_type to t2i/t2v. The media URL is returned as the assistant
6
- * message content in a standard chat.completion / chat.completion.chunk.
7
- */
8
-
9
- import type { Context } from "hono";
10
- import { stream as honoStream } from "hono/streaming";
11
- import type { OpenAIRequest } from "../../utils/types.ts";
12
- import {
13
- generateImage,
14
- generateVideo,
15
- isSupportedMediaSize,
16
- MEDIA_SIZE_OPTIONS,
17
- logMediaError,
18
- logMediaInfo,
19
- mediaLog,
20
- supportsPromptMediaGeneration,
21
- } from "../../services/media-generation.ts";
22
- import { sendOpenAIError } from "../../api/error-helpers.ts";
23
- import { ValidationError } from "../../core/errors.ts";
24
-
25
-
26
- const IMAGE_DEFAULT_SIZE = "auto";
27
- const VIDEO_DEFAULT_SIZE = "16:9";
28
- const STREAM_HEARTBEAT_MS = 15_000;
29
-
30
- interface MediaChatParams {
31
- c: Context;
32
- body: OpenAIRequest;
33
- model: string;
34
- kind: "image" | "video";
35
- isStream: boolean;
36
- }
37
-
38
- /**
39
- * Chatbox renders Markdown images but not HTML/video nodes. Keep the video
40
- * response portable as a clickable Markdown link; the browser can play the
41
- * MP4 when the link is opened.
42
- */
43
- export function formatGeneratedVideoContent(videoUrl: string): string {
44
- return `[🎬 Generated video](${videoUrl})`;
45
- }
46
-
47
- /**
48
- * Extracts the generation prompt from the last user message. Accepts both
49
- * plain-string content and multimodal arrays (using the text parts).
50
- */
51
- function extractPrompt(body: OpenAIRequest): string {
52
- const messages = Array.isArray(body.messages) ? body.messages : [];
53
- for (let i = messages.length - 1; i >= 0; i--) {
54
- const msg = messages[i] as { role?: string; content?: unknown };
55
- if (msg.role !== "user") continue;
56
- const content = msg.content;
57
- if (typeof content === "string") {
58
- const trimmed = content.trim();
59
- if (trimmed) return trimmed;
60
- continue;
61
- }
62
- if (Array.isArray(content)) {
63
- const text = (content as Array<{ type?: string; text?: unknown }>)
64
- .filter((part) => part?.type === "text")
65
- .map((part) => (typeof part.text === "string" ? part.text : ""))
66
- .join("\n")
67
- .trim();
68
- if (text) return text;
69
- }
70
- }
71
- return "";
72
- }
73
-
74
- function estimatePromptTokens(prompt: string): number {
75
- return Math.max(1, Math.ceil(prompt.length / 4));
76
- }
77
-
78
- function makeCompletionId(): string {
79
- return `chatcmpl-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
80
- }
81
-
82
- export async function handleMediaChatCompletion(
83
- params: MediaChatParams,
84
- ): Promise<Response> {
85
- const { c, body, model, kind, isStream } = params;
86
-
87
- const prompt = extractPrompt(body);
88
- if (!prompt) {
89
- const err = new ValidationError(
90
- "The last user message must contain a non-empty prompt for media generation",
91
- );
92
- err.param = "messages";
93
- return sendOpenAIError(c, err);
94
- }
95
-
96
- if (!supportsPromptMediaGeneration(model, kind)) {
97
- const err = new ValidationError(
98
- `Model \`${model}\` requires a reference image and is not available through prompt-only chat generation yet`,
99
- );
100
- err.param = "model";
101
- return sendOpenAIError(c, err);
102
- }
103
-
104
- const requestedSize = body.size;
105
- if (
106
- requestedSize !== undefined &&
107
- !isSupportedMediaSize(requestedSize)
108
- ) {
109
- const err = new ValidationError(
110
- `\`size\` must be one of: ${MEDIA_SIZE_OPTIONS.join(", ")}`,
111
- );
112
- err.param = "size";
113
- return sendOpenAIError(c, err);
114
- }
115
-
116
- const size =
117
- requestedSize ?? (kind === "image" ? IMAGE_DEFAULT_SIZE : VIDEO_DEFAULT_SIZE);
118
- const created = Math.floor(Date.now() / 1000);
119
- const completionId = makeCompletionId();
120
- const requestSignal = c.req.raw?.signal;
121
- const startedAt = Date.now();
122
-
123
- logMediaInfo(
124
- mediaLog(kind, "request_started", {
125
- operation: "chat.completions",
126
- model,
127
- prompt_chars: prompt.length,
128
- size,
129
- stream: isStream,
130
- }),
131
- );
132
-
133
- const generate = async (): Promise<string> => {
134
- if (kind === "image") {
135
- const result = await generateImage({
136
- prompt,
137
- model,
138
- size,
139
- signal: requestSignal,
140
- });
141
- return `![Generated image](${result.url})`;
142
- }
143
- const result = await generateVideo({
144
- prompt,
145
- model,
146
- size,
147
- waitForCompletion: true,
148
- signal: requestSignal,
149
- });
150
- if (result.status === "completed" && result.video_url) {
151
- return formatGeneratedVideoContent(result.video_url);
152
- }
153
- throw new Error(
154
- result.status === "failed"
155
- ? "Video generation failed"
156
- : "Video generation did not complete in time",
157
- );
158
- };
159
-
160
- const promptTokens = estimatePromptTokens(prompt);
161
- const usage = {
162
- prompt_tokens: promptTokens,
163
- completion_tokens: 0,
164
- total_tokens: promptTokens,
165
- };
166
- const includeUsage = body.stream_options?.include_usage === true;
167
-
168
- // ---- Non-streaming: return a complete chat.completion object ----
169
- if (!isStream) {
170
- try {
171
- const content = await generate();
172
- return c.json({
173
- id: completionId,
174
- object: "chat.completion",
175
- created,
176
- model,
177
- choices: [
178
- {
179
- index: 0,
180
- message: { role: "assistant", content },
181
- finish_reason: "stop",
182
- },
183
- ],
184
- usage,
185
- });
186
- } catch (error) {
187
- logMediaError(
188
- mediaLog(kind, "request_failed", {
189
- operation: "chat.completions",
190
- model,
191
- stream: false,
192
- duration_ms: Date.now() - startedAt,
193
- error: error instanceof Error ? error.message : String(error),
194
- }),
195
- );
196
- return sendOpenAIError(c, error, 500);
197
- }
198
- }
199
-
200
- // ---- Streaming: role chunk, heartbeats while generating, then content ----
201
- c.header("Content-Type", "text/event-stream");
202
- c.header("Cache-Control", "no-cache");
203
- c.header("Connection", "keep-alive");
204
- c.header("X-Accel-Buffering", "no");
205
-
206
- return honoStream(c, async (stream) => {
207
- const encoder = new TextEncoder();
208
- const writeChunk = async (payload: Record<string, unknown>) => {
209
- await stream.write(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`));
210
- };
211
-
212
- const baseChunk = {
213
- id: completionId,
214
- object: "chat.completion.chunk",
215
- created,
216
- model,
217
- };
218
-
219
- let heartbeat: ReturnType<typeof setInterval> | undefined;
220
-
221
- try {
222
- await writeChunk({
223
- ...baseChunk,
224
- choices: [
225
- { index: 0, delta: { role: "assistant", content: "" }, finish_reason: null },
226
- ],
227
- });
228
-
229
- // Generation can take up to ~120s (image) / ~300s (video). Keep the
230
- // connection alive so clients do not time out while Qwen renders.
231
- heartbeat = setInterval(() => {
232
- stream.write(encoder.encode(": keep-alive\n\n")).catch(() => {});
233
- }, STREAM_HEARTBEAT_MS);
234
-
235
- let content: string;
236
- try {
237
- content = await generate();
238
- } finally {
239
- clearInterval(heartbeat);
240
- }
241
-
242
- await writeChunk({
243
- ...baseChunk,
244
- choices: [{ index: 0, delta: { content }, finish_reason: null }],
245
- });
246
- await writeChunk({
247
- ...baseChunk,
248
- choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
249
- ...(includeUsage ? { usage } : {}),
250
- });
251
- await stream.write(encoder.encode("data: [DONE]\n\n"));
252
- } catch (error) {
253
- if (heartbeat) clearInterval(heartbeat);
254
- const message = error instanceof Error ? error.message : String(error);
255
- logMediaError(
256
- mediaLog(kind, "request_failed", {
257
- operation: "chat.completions",
258
- model,
259
- stream: true,
260
- duration_ms: Date.now() - startedAt,
261
- error: message,
262
- }),
263
- );
264
- try {
265
- await writeChunk({
266
- ...baseChunk,
267
- choices: [
268
- {
269
- index: 0,
270
- delta: { content: `⚠️ Media generation failed: ${message}` },
271
- finish_reason: null,
272
- },
273
- ],
274
- });
275
- await writeChunk({
276
- ...baseChunk,
277
- choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
278
- });
279
- await stream.write(encoder.encode("data: [DONE]\n\n"));
280
- } catch {
281
- // Client already disconnected; nothing else to do.
282
- }
283
- }
284
- });
285
- }
1
+ /**
2
+ * Native image/video generation over /v1/chat/completions. When the client
3
+ * selects a generation-specific model (qwen-image-*, wan2.*), the request is
4
+ * routed here instead of the text chat flow, mirroring how the Qwen web app
5
+ * switches chat_type to t2i/t2v. The media URL is returned as the assistant
6
+ * message content in a standard chat.completion / chat.completion.chunk.
7
+ */
8
+
9
+ import type { Context } from "hono";
10
+ import { stream as honoStream } from "hono/streaming";
11
+ import type { OpenAIRequest } from "../../utils/types.ts";
12
+ import {
13
+ generateImage,
14
+ generateVideo,
15
+ isSupportedMediaSize,
16
+ MEDIA_SIZE_OPTIONS,
17
+ logMediaError,
18
+ logMediaInfo,
19
+ mediaLog,
20
+ supportsPromptMediaGeneration,
21
+ } from "../../services/media-generation.ts";
22
+ import { sendOpenAIError } from "../../api/error-helpers.ts";
23
+ import { ValidationError } from "../../core/errors.ts";
24
+
25
+
26
+ const IMAGE_DEFAULT_SIZE = "auto";
27
+ const VIDEO_DEFAULT_SIZE = "16:9";
28
+ const STREAM_HEARTBEAT_MS = 15_000;
29
+
30
+ interface MediaChatParams {
31
+ c: Context;
32
+ body: OpenAIRequest;
33
+ model: string;
34
+ kind: "image" | "video";
35
+ isStream: boolean;
36
+ }
37
+
38
+ /**
39
+ * Chatbox renders Markdown images but not HTML/video nodes. Keep the video
40
+ * response portable as a clickable Markdown link; the browser can play the
41
+ * MP4 when the link is opened.
42
+ */
43
+ export function formatGeneratedVideoContent(videoUrl: string): string {
44
+ return `[🎬 Generated video](${videoUrl})`;
45
+ }
46
+
47
+ /**
48
+ * Extracts the generation prompt from the last user message. Accepts both
49
+ * plain-string content and multimodal arrays (using the text parts).
50
+ */
51
+ function extractPrompt(body: OpenAIRequest): string {
52
+ const messages = Array.isArray(body.messages) ? body.messages : [];
53
+ for (let i = messages.length - 1; i >= 0; i--) {
54
+ const msg = messages[i] as { role?: string; content?: unknown };
55
+ if (msg.role !== "user") continue;
56
+ const content = msg.content;
57
+ if (typeof content === "string") {
58
+ const trimmed = content.trim();
59
+ if (trimmed) return trimmed;
60
+ continue;
61
+ }
62
+ if (Array.isArray(content)) {
63
+ const text = (content as Array<{ type?: string; text?: unknown }>)
64
+ .filter((part) => part?.type === "text")
65
+ .map((part) => (typeof part.text === "string" ? part.text : ""))
66
+ .join("\n")
67
+ .trim();
68
+ if (text) return text;
69
+ }
70
+ }
71
+ return "";
72
+ }
73
+
74
+ function estimatePromptTokens(prompt: string): number {
75
+ return Math.max(1, Math.ceil(prompt.length / 4));
76
+ }
77
+
78
+ function makeCompletionId(): string {
79
+ return `chatcmpl-${Math.random().toString(36).slice(2)}${Date.now().toString(36)}`;
80
+ }
81
+
82
+ export async function handleMediaChatCompletion(
83
+ params: MediaChatParams,
84
+ ): Promise<Response> {
85
+ const { c, body, model, kind, isStream } = params;
86
+
87
+ const prompt = extractPrompt(body);
88
+ if (!prompt) {
89
+ const err = new ValidationError(
90
+ "The last user message must contain a non-empty prompt for media generation",
91
+ );
92
+ err.param = "messages";
93
+ return sendOpenAIError(c, err);
94
+ }
95
+
96
+ if (!supportsPromptMediaGeneration(model, kind)) {
97
+ const err = new ValidationError(
98
+ `Model \`${model}\` requires a reference image and is not available through prompt-only chat generation yet`,
99
+ );
100
+ err.param = "model";
101
+ return sendOpenAIError(c, err);
102
+ }
103
+
104
+ const requestedSize = body.size;
105
+ if (
106
+ requestedSize !== undefined &&
107
+ !isSupportedMediaSize(requestedSize)
108
+ ) {
109
+ const err = new ValidationError(
110
+ `\`size\` must be one of: ${MEDIA_SIZE_OPTIONS.join(", ")}`,
111
+ );
112
+ err.param = "size";
113
+ return sendOpenAIError(c, err);
114
+ }
115
+
116
+ const size =
117
+ requestedSize ?? (kind === "image" ? IMAGE_DEFAULT_SIZE : VIDEO_DEFAULT_SIZE);
118
+ const created = Math.floor(Date.now() / 1000);
119
+ const completionId = makeCompletionId();
120
+ const requestSignal = c.req.raw?.signal;
121
+ const startedAt = Date.now();
122
+
123
+ logMediaInfo(
124
+ mediaLog(kind, "request_started", {
125
+ operation: "chat.completions",
126
+ model,
127
+ prompt_chars: prompt.length,
128
+ size,
129
+ stream: isStream,
130
+ }),
131
+ );
132
+
133
+ const generate = async (): Promise<string> => {
134
+ if (kind === "image") {
135
+ const result = await generateImage({
136
+ prompt,
137
+ model,
138
+ size,
139
+ signal: requestSignal,
140
+ });
141
+ return `![Generated image](${result.url})`;
142
+ }
143
+ const result = await generateVideo({
144
+ prompt,
145
+ model,
146
+ size,
147
+ waitForCompletion: true,
148
+ signal: requestSignal,
149
+ });
150
+ if (result.status === "completed" && result.video_url) {
151
+ return formatGeneratedVideoContent(result.video_url);
152
+ }
153
+ throw new Error(
154
+ result.status === "failed"
155
+ ? "Video generation failed"
156
+ : "Video generation did not complete in time",
157
+ );
158
+ };
159
+
160
+ const promptTokens = estimatePromptTokens(prompt);
161
+ const usage = {
162
+ prompt_tokens: promptTokens,
163
+ completion_tokens: 0,
164
+ total_tokens: promptTokens,
165
+ };
166
+ const includeUsage = body.stream_options?.include_usage === true;
167
+
168
+ // ---- Non-streaming: return a complete chat.completion object ----
169
+ if (!isStream) {
170
+ try {
171
+ const content = await generate();
172
+ return c.json({
173
+ id: completionId,
174
+ object: "chat.completion",
175
+ created,
176
+ model,
177
+ choices: [
178
+ {
179
+ index: 0,
180
+ message: { role: "assistant", content },
181
+ finish_reason: "stop",
182
+ },
183
+ ],
184
+ usage,
185
+ });
186
+ } catch (error) {
187
+ logMediaError(
188
+ mediaLog(kind, "request_failed", {
189
+ operation: "chat.completions",
190
+ model,
191
+ stream: false,
192
+ duration_ms: Date.now() - startedAt,
193
+ error: error instanceof Error ? error.message : String(error),
194
+ }),
195
+ );
196
+ return sendOpenAIError(c, error, 500);
197
+ }
198
+ }
199
+
200
+ // ---- Streaming: role chunk, heartbeats while generating, then content ----
201
+ c.header("Content-Type", "text/event-stream");
202
+ c.header("Cache-Control", "no-cache");
203
+ c.header("Connection", "keep-alive");
204
+ c.header("X-Accel-Buffering", "no");
205
+
206
+ return honoStream(c, async (stream) => {
207
+ const encoder = new TextEncoder();
208
+ const writeChunk = async (payload: Record<string, unknown>) => {
209
+ await stream.write(encoder.encode(`data: ${JSON.stringify(payload)}\n\n`));
210
+ };
211
+
212
+ const baseChunk = {
213
+ id: completionId,
214
+ object: "chat.completion.chunk",
215
+ created,
216
+ model,
217
+ };
218
+
219
+ let heartbeat: ReturnType<typeof setInterval> | undefined;
220
+
221
+ try {
222
+ await writeChunk({
223
+ ...baseChunk,
224
+ choices: [
225
+ { index: 0, delta: { role: "assistant", content: "" }, finish_reason: null },
226
+ ],
227
+ });
228
+
229
+ // Generation can take up to ~120s (image) / ~300s (video). Keep the
230
+ // connection alive so clients do not time out while Qwen renders.
231
+ heartbeat = setInterval(() => {
232
+ stream.write(encoder.encode(": keep-alive\n\n")).catch(() => {});
233
+ }, STREAM_HEARTBEAT_MS);
234
+
235
+ let content: string;
236
+ try {
237
+ content = await generate();
238
+ } finally {
239
+ clearInterval(heartbeat);
240
+ }
241
+
242
+ await writeChunk({
243
+ ...baseChunk,
244
+ choices: [{ index: 0, delta: { content }, finish_reason: null }],
245
+ });
246
+ await writeChunk({
247
+ ...baseChunk,
248
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
249
+ ...(includeUsage ? { usage } : {}),
250
+ });
251
+ await stream.write(encoder.encode("data: [DONE]\n\n"));
252
+ } catch (error) {
253
+ if (heartbeat) clearInterval(heartbeat);
254
+ const message = error instanceof Error ? error.message : String(error);
255
+ logMediaError(
256
+ mediaLog(kind, "request_failed", {
257
+ operation: "chat.completions",
258
+ model,
259
+ stream: true,
260
+ duration_ms: Date.now() - startedAt,
261
+ error: message,
262
+ }),
263
+ );
264
+ try {
265
+ await writeChunk({
266
+ ...baseChunk,
267
+ choices: [
268
+ {
269
+ index: 0,
270
+ delta: { content: `⚠️ Media generation failed: ${message}` },
271
+ finish_reason: null,
272
+ },
273
+ ],
274
+ });
275
+ await writeChunk({
276
+ ...baseChunk,
277
+ choices: [{ index: 0, delta: {}, finish_reason: "stop" }],
278
+ });
279
+ await stream.write(encoder.encode("data: [DONE]\n\n"));
280
+ } catch {
281
+ // Client already disconnected; nothing else to do.
282
+ }
283
+ }
284
+ });
285
+ }