xjackkx commited on
Commit
7854ee4
·
verified ·
1 Parent(s): 2a14e5f

Upload 150 files

Browse files
src/gemini/client/index.ts CHANGED
@@ -1,544 +1,606 @@
1
- import { getPageTokens } from "../uploads/index";
2
- import { httpFetch } from "../transport";
3
- import { abortError, isAbortError, throwIfAborted } from "../../shared/abort";
4
- import { log } from "../../shared/logging";
5
- import { uuid } from "../../shared/crypto";
6
- import {
7
- dataAnalysisEmptyResponseError,
8
- invalidGeminiCookieError,
9
- isDataAnalysisEmptyResponseError,
10
- isInvalidGeminiCookieError,
11
- isLargePromptEmptyResponseError,
12
- largePromptEmptyResponseError,
13
- largePromptEmptyResponseThreshold,
14
- upstreamImageGenerationEmptyError,
15
- upstreamImageProviderError,
16
- upstreamEmptyResponseError,
17
- unverifiedGeminiCookieError,
18
- } from "./errors";
19
- import { buildHeaders, buildPayload, getUrl } from "./protocol";
20
- import {
21
- createStreamTextExtractor,
22
- extractResponseParts,
23
- extractResponseText,
24
- richResponseShapeSummary,
25
- wrbResponseShapeSummary,
26
- } from "./parser";
27
- import { hydrateGeneratedImages } from "./generated-images";
28
- import type { GeminiRichImage } from "./generated-images";
29
- import {
30
- configWithCachedGeminiBuildLabel,
31
- refreshGeminiBuildLabelForRetry,
32
- waitBeforeRetry,
33
- } from "./retry";
34
- import {
35
- configWithFreshGeminiCookie,
36
- rotateGeminiCookieForRetryWithReason,
37
- } from "../cookies";
38
- import type { RuntimeConfig } from "../../config";
39
- import type { ErrorWithMetadata } from "../../shared/types";
40
-
41
- type GeminiFileRef =
42
- | string
43
- | {
44
- ref?: unknown;
45
- fileRef?: unknown;
46
- id?: unknown;
47
- name?: unknown;
48
- filename?: unknown;
49
- };
50
-
51
- type GeminiStreamOptions = {
52
- signal?: AbortSignal;
53
- };
54
-
55
- type GeminiRichOptions = {
56
- hydrateGeneratedImageBytes?: boolean;
57
- };
58
-
59
- export type { GeminiRichImage } from "./generated-images";
60
-
61
- export type GeminiRichOutput = {
62
- text: string;
63
- images: GeminiRichImage[];
64
- };
65
-
66
- export {
67
- cleanText,
68
- extractResponseParts,
69
- extractResponseText,
70
- extractTextsFromLine,
71
- richResponseShapeSummary,
72
- wrbResponseShapeSummary,
73
- } from "./parser";
74
- export { buildHeaders, buildPayload, getUrl } from "./protocol";
75
- export { getFreshGeminiBuildLabel } from "./retry";
76
-
77
- async function appendGeminiPageToken(
78
- cfg: RuntimeConfig,
79
- body: string,
80
- ): Promise<string> {
81
- if (cfg.xsrf_token) return `${body}&at=${encodeURIComponent(cfg.xsrf_token)}`;
82
- if (!cfg.cookie) return body;
83
- const tokens = await getPageTokens(cfg);
84
- if (!tokens.at) {
85
- log(cfg, "gemini cookie verification failed reason=missing_page_at_token");
86
- throw unverifiedGeminiCookieError("missing_page_at_token");
87
- }
88
- return `${body}&at=${encodeURIComponent(tokens.at)}`;
89
- }
90
-
91
- async function fetchGeminiStreamGenerate(
92
- cfg: RuntimeConfig,
93
- activeCfg: RuntimeConfig,
94
- body: string,
95
- signal: AbortSignal | null | undefined = undefined,
96
- modelHeaders: Record<string, string> | null = null,
97
- requestId: string | null = null,
98
- ) {
99
- const url = getUrl(activeCfg);
100
- const headers = await buildHeaders(activeCfg, modelHeaders, requestId);
101
- const requestBody = await appendGeminiPageToken(activeCfg, body);
102
- return httpFetch(url, {
103
- method: "POST",
104
- headers,
105
- body: requestBody,
106
- timeoutMs: cfg.request_timeout_sec * 1000,
107
- socket: cfg.upstream_socket,
108
- socketFallback: "never",
109
- signal,
110
- cfg,
111
- });
112
- }
113
-
114
- export async function generate(
115
- cfg: RuntimeConfig,
116
- prompt: string,
117
- modelId: number,
118
- thinkMode: number,
119
- extra: Record<number, unknown> | null,
120
- fileRefs: GeminiFileRef[] | null | undefined,
121
- modelHeaders: Record<string, string> | null = null,
122
- ): Promise<string> {
123
- let lastErr: unknown;
124
- let activeCfg = await configWithCachedGeminiBuildLabel(
125
- await configWithFreshGeminiCookie(cfg),
126
- );
127
- let refreshedBL = false;
128
- let refreshedCookie = false;
129
- const requestId = uuid().toUpperCase();
130
- const body = buildPayload(
131
- prompt,
132
- modelId,
133
- thinkMode,
134
- fileRefs || null,
135
- extra,
136
- requestId,
137
- );
138
- for (let attempt = 0; attempt < cfg.retry_attempts; attempt++) {
139
- try {
140
- const resp = await fetchGeminiStreamGenerate(
141
- cfg,
142
- activeCfg,
143
- body,
144
- undefined,
145
- modelHeaders,
146
- requestId,
147
- );
148
- const cookieErr = invalidGeminiCookieError(cfg, resp.status);
149
- if (cookieErr) throw cookieErr;
150
- const raw = await resp.text();
151
- const text = extractResponseText(raw);
152
- if (!resp.ok || !text) {
153
- const shape =
154
- cfg.log_requests && !text ? ` ${wrbResponseShapeSummary(raw)}` : "";
155
- log(
156
- cfg,
157
- `upstream status=${resp.status} rawLen=${raw.length} parsedLen=${text.length}${shape}`,
158
- );
159
- }
160
- if (!text) {
161
- const dataAnalysisErr = dataAnalysisEmptyResponseError(raw, fileRefs);
162
- if (dataAnalysisErr) throw dataAnalysisErr;
163
- const largePromptErr = largePromptEmptyResponseError(
164
- prompt,
165
- resp.status,
166
- raw.length,
167
- largePromptEmptyResponseThreshold(cfg),
168
- );
169
- if (largePromptErr) throw largePromptErr;
170
- const refreshedCfg = await refreshGeminiBuildLabelForRetry(
171
- cfg,
172
- activeCfg,
173
- refreshedBL,
174
- "",
175
- );
176
- if (refreshedCfg) {
177
- refreshedBL = true;
178
- activeCfg = refreshedCfg;
179
- continue;
180
- }
181
- throw upstreamEmptyResponseError(resp.status, raw.length, "non-stream");
182
- }
183
- return text;
184
- } catch (e) {
185
- if (isInvalidGeminiCookieError(e) && !refreshedCookie) {
186
- const rotated = await rotateGeminiCookieForRetryWithReason(activeCfg);
187
- if (rotated.config) {
188
- refreshedCookie = true;
189
- activeCfg = await configWithCachedGeminiBuildLabel(rotated.config);
190
- continue;
191
- }
192
- throw invalidCookieErrorWithRotationReason(cfg, e, rotated.reason);
193
- }
194
- if (isInvalidGeminiCookieError(e) && refreshedCookie)
195
- throw invalidCookieErrorWithRotationReason(cfg, e, "rotation_updated");
196
- if (
197
- isLargePromptEmptyResponseError(e) ||
198
- isDataAnalysisEmptyResponseError(e) ||
199
- isInvalidGeminiCookieError(e)
200
- )
201
- throw e;
202
- lastErr = e;
203
- await waitBeforeRetry(cfg, attempt, e, "Retry");
204
- }
205
- }
206
- throw lastErr;
207
- }
208
-
209
- export async function generateRich(
210
- cfg: RuntimeConfig,
211
- prompt: string,
212
- modelId: number,
213
- thinkMode: number,
214
- extra: Record<number, unknown> | null,
215
- fileRefs: GeminiFileRef[] | null | undefined,
216
- modelHeaders: Record<string, string> | null = null,
217
- options: GeminiRichOptions = {},
218
- ): Promise<GeminiRichOutput> {
219
- let lastErr: unknown;
220
- let activeCfg = await configWithCachedGeminiBuildLabel(
221
- await configWithFreshGeminiCookie(cfg),
222
- );
223
- let refreshedBL = false;
224
- let refreshedCookie = false;
225
- const requestId = uuid().toUpperCase();
226
- const body = buildPayload(
227
- prompt,
228
- modelId,
229
- thinkMode,
230
- fileRefs || null,
231
- extra,
232
- requestId,
233
- );
234
- for (let attempt = 0; attempt < cfg.retry_attempts; attempt++) {
235
- try {
236
- const resp = await fetchGeminiStreamGenerate(
237
- cfg,
238
- activeCfg,
239
- body,
240
- undefined,
241
- modelHeaders,
242
- requestId,
243
- );
244
- const cookieErr = invalidGeminiCookieError(cfg, resp.status);
245
- if (cookieErr) throw cookieErr;
246
- const raw = await resp.text();
247
- const parts = extractResponseParts(raw);
248
- if (parts.fatalCode) throw upstreamImageProviderError(parts.fatalCode);
249
- if (!resp.ok || (!parts.text && !parts.images.length)) {
250
- const shape = cfg.log_requests
251
- ? ` ${richResponseShapeSummary(raw)}`
252
- : "";
253
- log(
254
- cfg,
255
- `rich upstream status=${resp.status} rawLen=${raw.length} parsedTextLen=${parts.text.length} images=${parts.images.length}${shape}`,
256
- );
257
- }
258
- if (!parts.text && !parts.images.length) {
259
- const dataAnalysisErr = dataAnalysisEmptyResponseError(raw, fileRefs);
260
- if (dataAnalysisErr) throw dataAnalysisErr;
261
- const largePromptErr = largePromptEmptyResponseError(
262
- prompt,
263
- resp.status,
264
- raw.length,
265
- largePromptEmptyResponseThreshold(cfg),
266
- );
267
- if (largePromptErr) throw largePromptErr;
268
- const refreshedCfg = await refreshGeminiBuildLabelForRetry(
269
- cfg,
270
- activeCfg,
271
- refreshedBL,
272
- "",
273
- );
274
- if (refreshedCfg) {
275
- refreshedBL = true;
276
- activeCfg = refreshedCfg;
277
- continue;
278
- }
279
- throw upstreamImageGenerationEmptyError(
280
- resp.status,
281
- raw.length,
282
- "non-stream",
283
- );
284
- }
285
- const images =
286
- options.hydrateGeneratedImageBytes === false
287
- ? parts.images
288
- : await hydrateGeneratedImages(cfg, activeCfg, parts.images);
289
- return { text: parts.text, images };
290
- } catch (e) {
291
- if (isInvalidGeminiCookieError(e) && !refreshedCookie) {
292
- const rotated = await rotateGeminiCookieForRetryWithReason(activeCfg);
293
- if (rotated.config) {
294
- refreshedCookie = true;
295
- activeCfg = await configWithCachedGeminiBuildLabel(rotated.config);
296
- continue;
297
- }
298
- throw invalidCookieErrorWithRotationReason(cfg, e, rotated.reason);
299
- }
300
- if (isInvalidGeminiCookieError(e) && refreshedCookie)
301
- throw invalidCookieErrorWithRotationReason(cfg, e, "rotation_updated");
302
- if (
303
- isLargePromptEmptyResponseError(e) ||
304
- isDataAnalysisEmptyResponseError(e) ||
305
- isInvalidGeminiCookieError(e)
306
- )
307
- throw e;
308
- lastErr = e;
309
- await waitBeforeRetry(cfg, attempt, e, "Rich retry");
310
- }
311
- }
312
- throw lastErr;
313
- }
314
-
315
- export async function* generateStream(
316
- cfg: RuntimeConfig,
317
- prompt: string,
318
- modelId: number,
319
- thinkMode: number,
320
- extra: Record<number, unknown> | null,
321
- fileRefs: GeminiFileRef[] | null | undefined,
322
- options: GeminiStreamOptions = {},
323
- modelHeaders: Record<string, string> | null = null,
324
- ): AsyncIterable<string> {
325
- let lastErr: unknown;
326
- let yielded = false;
327
- let activeCfg = await configWithCachedGeminiBuildLabel(
328
- await configWithFreshGeminiCookie(cfg),
329
- );
330
- let refreshedBL = false;
331
- let refreshedCookie = false;
332
- const requestId = uuid().toUpperCase();
333
- const body = buildPayload(
334
- prompt,
335
- modelId,
336
- thinkMode,
337
- fileRefs || null,
338
- extra,
339
- requestId,
340
- );
341
- const signal = options?.signal;
342
-
343
- for (let attempt = 0; attempt < cfg.retry_attempts; attempt++) {
344
- try {
345
- throwIfAborted(signal);
346
- const resp = await fetchGeminiStreamGenerate(
347
- cfg,
348
- activeCfg,
349
- body,
350
- signal,
351
- modelHeaders,
352
- requestId,
353
- );
354
- const cookieErr = invalidGeminiCookieError(cfg, resp.status);
355
- if (cookieErr) throw cookieErr;
356
- if (!resp.body) {
357
- const raw = await resp.text();
358
- const text = extractResponseText(raw);
359
- if (text) {
360
- yielded = true;
361
- yield text;
362
- }
363
- if (!text) {
364
- const shape = cfg.log_requests
365
- ? ` ${wrbResponseShapeSummary(raw)}`
366
- : "";
367
- log(
368
- cfg,
369
- `stream upstream produced no text without body (status=${resp.status}) rawLen=${raw.length}${shape}`,
370
- );
371
- const dataAnalysisErr = dataAnalysisEmptyResponseError(raw, fileRefs);
372
- if (dataAnalysisErr) throw dataAnalysisErr;
373
- const largePromptErr = largePromptEmptyResponseError(
374
- prompt,
375
- resp.status,
376
- raw.length,
377
- largePromptEmptyResponseThreshold(cfg),
378
- );
379
- if (largePromptErr) throw largePromptErr;
380
- const refreshedCfg = await refreshGeminiBuildLabelForRetry(
381
- cfg,
382
- activeCfg,
383
- refreshedBL,
384
- "stream without body",
385
- );
386
- if (refreshedCfg) {
387
- refreshedBL = true;
388
- activeCfg = refreshedCfg;
389
- continue;
390
- }
391
- throw upstreamEmptyResponseError(
392
- resp.status,
393
- raw.length,
394
- "stream without body",
395
- );
396
- }
397
- return;
398
- }
399
- const reader = resp.body.getReader();
400
- const decoder = new TextDecoder();
401
- const extractor = createStreamTextExtractor();
402
- const lineChunks: string[] = [];
403
- let lineLength = 0;
404
- let rawSnippet = "";
405
- let rawLength = 0;
406
- const takeLine = (piece: string): string => {
407
- if (!lineChunks.length) return piece;
408
- if (piece) {
409
- lineChunks.push(piece);
410
- lineLength += piece.length;
411
- }
412
- const line = lineChunks.join("");
413
- lineChunks.length = 0;
414
- lineLength = 0;
415
- return line;
416
- };
417
- const appendLineRemainder = (piece: string): void => {
418
- if (!piece) return;
419
- lineChunks.push(piece);
420
- lineLength += piece.length;
421
- };
422
- const consumeDecoded = function* (decoded: string): Generator<string> {
423
- let lineStart = 0;
424
- let idx = decoded.indexOf("\n", lineStart);
425
- while (idx >= 0) {
426
- const line = takeLine(decoded.slice(lineStart, idx));
427
- for (const delta of extractor.consumeLine(line)) yield delta;
428
- lineStart = idx + 1;
429
- idx = decoded.indexOf("\n", lineStart);
430
- }
431
- if (lineStart < decoded.length)
432
- appendLineRemainder(decoded.slice(lineStart));
433
- };
434
- while (true) {
435
- throwIfAborted(signal);
436
- const { done, value } = await reader.read();
437
- if (done) break;
438
- const decoded = decoder.decode(value, { stream: true });
439
- rawLength += decoded.length;
440
- if (rawSnippet.length < 500)
441
- rawSnippet += decoded.slice(0, 500 - rawSnippet.length);
442
- for (const delta of consumeDecoded(decoded)) {
443
- yielded = true;
444
- yield delta;
445
- }
446
- }
447
- const tail = decoder.decode();
448
- if (tail) {
449
- rawLength += tail.length;
450
- if (rawSnippet.length < 500)
451
- rawSnippet += tail.slice(0, 500 - rawSnippet.length);
452
- for (const delta of consumeDecoded(tail)) {
453
- yielded = true;
454
- yield delta;
455
- }
456
- }
457
- if (lineLength > 0) {
458
- for (const delta of extractor.consumeLine(takeLine(""))) {
459
- yielded = true;
460
- yield delta;
461
- }
462
- }
463
- if (!yielded) {
464
- const shape = cfg.log_requests
465
- ? ` ${wrbResponseShapeSummary(rawSnippet)}`
466
- : "";
467
- log(
468
- cfg,
469
- `stream upstream produced no text (status=${resp.status}) rawLen=${rawLength}${shape}`,
470
- );
471
- const dataAnalysisErr = dataAnalysisEmptyResponseError(
472
- rawSnippet,
473
- fileRefs,
474
- );
475
- if (dataAnalysisErr) throw dataAnalysisErr;
476
- const largePromptErr = largePromptEmptyResponseError(
477
- prompt,
478
- resp.status,
479
- null,
480
- largePromptEmptyResponseThreshold(cfg),
481
- );
482
- if (largePromptErr) throw largePromptErr;
483
- const refreshedCfg = await refreshGeminiBuildLabelForRetry(
484
- cfg,
485
- activeCfg,
486
- refreshedBL,
487
- "stream",
488
- );
489
- if (refreshedCfg) {
490
- refreshedBL = true;
491
- activeCfg = refreshedCfg;
492
- continue;
493
- }
494
- throw upstreamEmptyResponseError(resp.status, rawLength, "stream");
495
- }
496
- return;
497
- } catch (e) {
498
- if (isAbortError(e) || signal?.aborted) throw abortError(signal);
499
- if (isInvalidGeminiCookieError(e) && !yielded && !refreshedCookie) {
500
- const rotated = await rotateGeminiCookieForRetryWithReason(activeCfg);
501
- if (rotated.config) {
502
- refreshedCookie = true;
503
- activeCfg = await configWithCachedGeminiBuildLabel(rotated.config);
504
- continue;
505
- }
506
- throw invalidCookieErrorWithRotationReason(cfg, e, rotated.reason);
507
- }
508
- if (isInvalidGeminiCookieError(e) && !yielded && refreshedCookie)
509
- throw invalidCookieErrorWithRotationReason(cfg, e, "rotation_updated");
510
- if (
511
- isLargePromptEmptyResponseError(e) ||
512
- isDataAnalysisEmptyResponseError(e) ||
513
- isInvalidGeminiCookieError(e)
514
- )
515
- throw e;
516
- lastErr = e;
517
- if (
518
- !yielded &&
519
- (await waitBeforeRetry(cfg, attempt, e, "Stream retry", signal))
520
- ) {
521
- continue;
522
- }
523
- throw e;
524
- }
525
- }
526
- if (lastErr) throw lastErr;
527
- }
528
-
529
- function invalidCookieErrorWithRotationReason(
530
- cfg: RuntimeConfig,
531
- err: unknown,
532
- reason: unknown,
533
- ): unknown {
534
- const meta =
535
- err && typeof err === "object" ? (err as Partial<ErrorWithMetadata>) : {};
536
- return (
537
- invalidGeminiCookieError(
538
- cfg,
539
- meta.upstreamStatus || meta.status || 401,
540
- typeof meta.rawLength === "number" ? meta.rawLength : null,
541
- reason,
542
- ) || err
543
- );
544
- }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ import { getPageTokens } from "../uploads/index";
2
+ import { httpFetch } from "../transport";
3
+ import { abortError, isAbortError, sleep, throwIfAborted } from "../../shared/abort";
4
+ import { log } from "../../shared/logging";
5
+ import { uuid } from "../../shared/crypto";
6
+ import {
7
+ dataAnalysisEmptyResponseError,
8
+ invalidGeminiCookieError,
9
+ isDataAnalysisEmptyResponseError,
10
+ isInvalidGeminiCookieError,
11
+ isLargePromptEmptyResponseError,
12
+ largePromptEmptyResponseError,
13
+ largePromptEmptyResponseThreshold,
14
+ upstreamImageGenerationEmptyError,
15
+ upstreamImageProviderError,
16
+ upstreamEmptyResponseError,
17
+ unverifiedGeminiCookieError,
18
+ } from "./errors";
19
+ import { buildHeaders, buildPayload, getUrl } from "./protocol";
20
+ import {
21
+ createStreamTextExtractor,
22
+ extractResponseParts,
23
+ extractResponseText,
24
+ richResponseShapeSummary,
25
+ wrbResponseShapeSummary,
26
+ } from "./parser";
27
+ import { hydrateGeneratedImages } from "./generated-images";
28
+ import type { GeminiRichImage } from "./generated-images";
29
+ import {
30
+ configWithCachedGeminiBuildLabel,
31
+ refreshGeminiBuildLabelForRetry,
32
+ waitBeforeRetry,
33
+ } from "./retry";
34
+ import {
35
+ configWithFreshGeminiCookie,
36
+ rotateGeminiCookieForRetryWithReason,
37
+ } from "../cookies";
38
+ import type { RuntimeConfig } from "../../config";
39
+ import type { ErrorWithMetadata } from "../../shared/types";
40
+
41
+ type GeminiFileRef =
42
+ | string
43
+ | {
44
+ ref?: unknown;
45
+ fileRef?: unknown;
46
+ id?: unknown;
47
+ name?: unknown;
48
+ filename?: unknown;
49
+ };
50
+
51
+ type GeminiStreamOptions = {
52
+ signal?: AbortSignal;
53
+ };
54
+
55
+ type GeminiRichOptions = {
56
+ hydrateGeneratedImageBytes?: boolean;
57
+ };
58
+
59
+ export type { GeminiRichImage } from "./generated-images";
60
+
61
+ export type GeminiRichOutput = {
62
+ text: string;
63
+ images: GeminiRichImage[];
64
+ };
65
+
66
+ export {
67
+ cleanText,
68
+ extractResponseParts,
69
+ extractResponseText,
70
+ extractTextsFromLine,
71
+ richResponseShapeSummary,
72
+ wrbResponseShapeSummary,
73
+ } from "./parser";
74
+ export { buildHeaders, buildPayload, getUrl } from "./protocol";
75
+ export { getFreshGeminiBuildLabel } from "./retry";
76
+
77
+ async function appendGeminiPageToken(
78
+ cfg: RuntimeConfig,
79
+ body: string,
80
+ ): Promise<string> {
81
+ if (cfg.xsrf_token) return `${body}&at=${encodeURIComponent(cfg.xsrf_token)}`;
82
+ if (!cfg.cookie) return body;
83
+ const tokens = await getPageTokens(cfg);
84
+ if (!tokens.at) {
85
+ log(cfg, "gemini cookie verification failed reason=missing_page_at_token");
86
+ throw unverifiedGeminiCookieError("missing_page_at_token");
87
+ }
88
+ return `${body}&at=${encodeURIComponent(tokens.at)}`;
89
+ }
90
+
91
+ async function fetchGeminiStreamGenerate(
92
+ cfg: RuntimeConfig,
93
+ activeCfg: RuntimeConfig,
94
+ body: string,
95
+ signal: AbortSignal | null | undefined = undefined,
96
+ modelHeaders: Record<string, string> | null = null,
97
+ requestId: string | null = null,
98
+ ) {
99
+ const url = getUrl(activeCfg);
100
+ const headers = await buildHeaders(activeCfg, modelHeaders, requestId);
101
+ const requestBody = await appendGeminiPageToken(activeCfg, body);
102
+ // resin_proxy 时 httpFetch 内部会强制关闭 socket
103
+ return httpFetch(url, {
104
+ method: "POST",
105
+ headers,
106
+ body: requestBody,
107
+ timeoutMs: cfg.request_timeout_sec * 1000,
108
+ socket: cfg.upstream_socket && !activeCfg.resin_proxy,
109
+ socketFallback: cfg.upstream_socket && !activeCfg.resin_proxy ? "never" : "pre-response",
110
+ signal,
111
+ cfg,
112
+ });
113
+ }
114
+
115
+ export async function generate(
116
+ cfg: RuntimeConfig,
117
+ prompt: string,
118
+ modelId: number,
119
+ thinkMode: number,
120
+ extra: Record<number, unknown> | null,
121
+ fileRefs: GeminiFileRef[] | null | undefined,
122
+ modelHeaders: Record<string, string> | null = null,
123
+ ): Promise<string> {
124
+ let lastErr: unknown;
125
+ let activeCfg = await configWithCachedGeminiBuildLabel(
126
+ await configWithFreshGeminiCookie(cfg),
127
+ );
128
+ let refreshedBL = false;
129
+ let refreshedCookie = false;
130
+ const requestId = uuid().toUpperCase();
131
+ const body = buildPayload(
132
+ prompt,
133
+ modelId,
134
+ thinkMode,
135
+ fileRefs || null,
136
+ extra,
137
+ requestId,
138
+ );
139
+ for (let attempt = 0; attempt < cfg.retry_attempts; attempt++) {
140
+ try {
141
+ const resp = await fetchGeminiStreamGenerate(
142
+ cfg,
143
+ activeCfg,
144
+ body,
145
+ undefined,
146
+ modelHeaders,
147
+ requestId,
148
+ );
149
+ const cookieErr = invalidGeminiCookieError(cfg, resp.status);
150
+ if (cookieErr) throw cookieErr;
151
+ const raw = await resp.text();
152
+ const text = extractResponseText(raw);
153
+ if (!resp.ok || !text) {
154
+ const shape =
155
+ cfg.log_requests && !text ? ` ${wrbResponseShapeSummary(raw)}` : "";
156
+ log(
157
+ cfg,
158
+ `upstream status=${resp.status} rawLen=${raw.length} parsedLen=${text.length}${shape}`,
159
+ );
160
+ }
161
+ if (!text) {
162
+ const dataAnalysisErr = dataAnalysisEmptyResponseError(raw, fileRefs);
163
+ if (dataAnalysisErr) throw dataAnalysisErr;
164
+ const largePromptErr = largePromptEmptyResponseError(
165
+ prompt,
166
+ resp.status,
167
+ raw.length,
168
+ largePromptEmptyResponseThreshold(cfg),
169
+ );
170
+ if (largePromptErr) throw largePromptErr;
171
+ const refreshedCfg = await refreshGeminiBuildLabelForRetry(
172
+ cfg,
173
+ activeCfg,
174
+ refreshedBL,
175
+ "",
176
+ );
177
+ if (refreshedCfg) {
178
+ refreshedBL = true;
179
+ activeCfg = refreshedCfg;
180
+ continue;
181
+ }
182
+ throw upstreamEmptyResponseError(resp.status, raw.length, "non-stream");
183
+ }
184
+ return text;
185
+ } catch (e) {
186
+ if (isInvalidGeminiCookieError(e) && !refreshedCookie) {
187
+ const rotated = await rotateGeminiCookieForRetryWithReason(activeCfg);
188
+ if (rotated.config) {
189
+ refreshedCookie = true;
190
+ activeCfg = await configWithCachedGeminiBuildLabel(rotated.config);
191
+ continue;
192
+ }
193
+ throw invalidCookieErrorWithRotationReason(cfg, e, rotated.reason);
194
+ }
195
+ if (isInvalidGeminiCookieError(e) && refreshedCookie)
196
+ throw invalidCookieErrorWithRotationReason(cfg, e, "rotation_updated");
197
+ if (
198
+ isLargePromptEmptyResponseError(e) ||
199
+ isDataAnalysisEmptyResponseError(e) ||
200
+ isInvalidGeminiCookieError(e)
201
+ )
202
+ throw e;
203
+ lastErr = e;
204
+ await waitBeforeRetry(cfg, attempt, e, "Retry");
205
+ }
206
+ }
207
+ throw lastErr;
208
+ }
209
+
210
+ export async function generateRich(
211
+ cfg: RuntimeConfig,
212
+ prompt: string,
213
+ modelId: number,
214
+ thinkMode: number,
215
+ extra: Record<number, unknown> | null,
216
+ fileRefs: GeminiFileRef[] | null | undefined,
217
+ modelHeaders: Record<string, string> | null = null,
218
+ options: GeminiRichOptions = {},
219
+ ): Promise<GeminiRichOutput> {
220
+ let lastErr: unknown;
221
+ let activeCfg = await configWithCachedGeminiBuildLabel(
222
+ await configWithFreshGeminiCookie(cfg),
223
+ );
224
+ let refreshedBL = false;
225
+ let refreshedCookie = false;
226
+ const requestId = uuid().toUpperCase();
227
+ const body = buildPayload(
228
+ prompt,
229
+ modelId,
230
+ thinkMode,
231
+ fileRefs || null,
232
+ extra,
233
+ requestId,
234
+ );
235
+ for (let attempt = 0; attempt < cfg.retry_attempts; attempt++) {
236
+ try {
237
+ const resp = await fetchGeminiStreamGenerate(
238
+ cfg,
239
+ activeCfg,
240
+ body,
241
+ undefined,
242
+ modelHeaders,
243
+ requestId,
244
+ );
245
+ const cookieErr = invalidGeminiCookieError(cfg, resp.status);
246
+ if (cookieErr) throw cookieErr;
247
+ const raw = await resp.text();
248
+ const parts = extractResponseParts(raw);
249
+ if (parts.fatalCode) throw upstreamImageProviderError(parts.fatalCode);
250
+ if (!resp.ok || (!parts.text && !parts.images.length)) {
251
+ const shape = cfg.log_requests
252
+ ? ` ${richResponseShapeSummary(raw)}`
253
+ : "";
254
+ log(
255
+ cfg,
256
+ `rich upstream status=${resp.status} rawLen=${raw.length} parsedTextLen=${parts.text.length} images=${parts.images.length}${shape}`,
257
+ );
258
+ }
259
+ if (!parts.text && !parts.images.length) {
260
+ const dataAnalysisErr = dataAnalysisEmptyResponseError(raw, fileRefs);
261
+ if (dataAnalysisErr) throw dataAnalysisErr;
262
+ const largePromptErr = largePromptEmptyResponseError(
263
+ prompt,
264
+ resp.status,
265
+ raw.length,
266
+ largePromptEmptyResponseThreshold(cfg),
267
+ );
268
+ if (largePromptErr) throw largePromptErr;
269
+ const refreshedCfg = await refreshGeminiBuildLabelForRetry(
270
+ cfg,
271
+ activeCfg,
272
+ refreshedBL,
273
+ "",
274
+ );
275
+ if (refreshedCfg) {
276
+ refreshedBL = true;
277
+ activeCfg = refreshedCfg;
278
+ continue;
279
+ }
280
+ throw upstreamImageGenerationEmptyError(
281
+ resp.status,
282
+ raw.length,
283
+ "non-stream",
284
+ );
285
+ }
286
+ const images =
287
+ options.hydrateGeneratedImageBytes === false
288
+ ? parts.images
289
+ : await hydrateGeneratedImages(cfg, activeCfg, parts.images);
290
+ return { text: parts.text, images };
291
+ } catch (e) {
292
+ if (isInvalidGeminiCookieError(e) && !refreshedCookie) {
293
+ const rotated = await rotateGeminiCookieForRetryWithReason(activeCfg);
294
+ if (rotated.config) {
295
+ refreshedCookie = true;
296
+ activeCfg = await configWithCachedGeminiBuildLabel(rotated.config);
297
+ continue;
298
+ }
299
+ throw invalidCookieErrorWithRotationReason(cfg, e, rotated.reason);
300
+ }
301
+ if (isInvalidGeminiCookieError(e) && refreshedCookie)
302
+ throw invalidCookieErrorWithRotationReason(cfg, e, "rotation_updated");
303
+ if (
304
+ isLargePromptEmptyResponseError(e) ||
305
+ isDataAnalysisEmptyResponseError(e) ||
306
+ isInvalidGeminiCookieError(e)
307
+ )
308
+ throw e;
309
+ lastErr = e;
310
+ await waitBeforeRetry(cfg, attempt, e, "Rich retry");
311
+ }
312
+ }
313
+ throw lastErr;
314
+ }
315
+
316
+
317
+ // Resin 反代常把上游细粒度流合成大块;在本地按码点切回小片并加微延迟,
318
+ // 恢复接近直连的打字机效果。未配 resin_proxy 时原样透传。
319
+ const RESIN_STREAM_CHUNK_CHARS = 16;
320
+ const RESIN_STREAM_CHUNK_MS = 12;
321
+
322
+ async function* resinSmoothedPieces(
323
+ text: string,
324
+ enabled: boolean,
325
+ signal?: AbortSignal | null,
326
+ ): AsyncGenerator<string> {
327
+ const raw = String(text || "");
328
+ if (!raw) return;
329
+ if (!enabled) {
330
+ yield raw;
331
+ return;
332
+ }
333
+ let i = 0;
334
+ const n = raw.length;
335
+ let first = true;
336
+ while (i < n) {
337
+ throwIfAborted(signal);
338
+ let end = i;
339
+ let count = 0;
340
+ while (end < n && count < RESIN_STREAM_CHUNK_CHARS) {
341
+ const cp = raw.codePointAt(end)!;
342
+ end += cp > 0xffff ? 2 : 1;
343
+ count += 1;
344
+ }
345
+ if (!first) await sleep(RESIN_STREAM_CHUNK_MS, signal);
346
+ first = false;
347
+ yield raw.slice(i, end);
348
+ i = end;
349
+ }
350
+ }
351
+
352
+ export async function* generateStream(
353
+ cfg: RuntimeConfig,
354
+ prompt: string,
355
+ modelId: number,
356
+ thinkMode: number,
357
+ extra: Record<number, unknown> | null,
358
+ fileRefs: GeminiFileRef[] | null | undefined,
359
+ options: GeminiStreamOptions = {},
360
+ modelHeaders: Record<string, string> | null = null,
361
+ ): AsyncIterable<string> {
362
+ let lastErr: unknown;
363
+ let yielded = false;
364
+ let activeCfg = await configWithCachedGeminiBuildLabel(
365
+ await configWithFreshGeminiCookie(cfg),
366
+ );
367
+ let refreshedBL = false;
368
+ let refreshedCookie = false;
369
+ const requestId = uuid().toUpperCase();
370
+ const body = buildPayload(
371
+ prompt,
372
+ modelId,
373
+ thinkMode,
374
+ fileRefs || null,
375
+ extra,
376
+ requestId,
377
+ );
378
+ const signal = options?.signal;
379
+ const resinSmooth = !!cfg.resin_proxy;
380
+
381
+ for (let attempt = 0; attempt < cfg.retry_attempts; attempt++) {
382
+ try {
383
+ throwIfAborted(signal);
384
+ const resp = await fetchGeminiStreamGenerate(
385
+ cfg,
386
+ activeCfg,
387
+ body,
388
+ signal,
389
+ modelHeaders,
390
+ requestId,
391
+ );
392
+ const cookieErr = invalidGeminiCookieError(cfg, resp.status);
393
+ if (cookieErr) throw cookieErr;
394
+ if (!resp.body) {
395
+ const raw = await resp.text();
396
+ const text = extractResponseText(raw);
397
+ if (text) {
398
+ for await (const piece of resinSmoothedPieces(
399
+ text,
400
+ resinSmooth,
401
+ signal,
402
+ )) {
403
+ yielded = true;
404
+ yield piece;
405
+ }
406
+ }
407
+ if (!text) {
408
+ const shape = cfg.log_requests
409
+ ? ` ${wrbResponseShapeSummary(raw)}`
410
+ : "";
411
+ log(
412
+ cfg,
413
+ `stream upstream produced no text without body (status=${resp.status}) rawLen=${raw.length}${shape}`,
414
+ );
415
+ const dataAnalysisErr = dataAnalysisEmptyResponseError(raw, fileRefs);
416
+ if (dataAnalysisErr) throw dataAnalysisErr;
417
+ const largePromptErr = largePromptEmptyResponseError(
418
+ prompt,
419
+ resp.status,
420
+ raw.length,
421
+ largePromptEmptyResponseThreshold(cfg),
422
+ );
423
+ if (largePromptErr) throw largePromptErr;
424
+ const refreshedCfg = await refreshGeminiBuildLabelForRetry(
425
+ cfg,
426
+ activeCfg,
427
+ refreshedBL,
428
+ "stream without body",
429
+ );
430
+ if (refreshedCfg) {
431
+ refreshedBL = true;
432
+ activeCfg = refreshedCfg;
433
+ continue;
434
+ }
435
+ throw upstreamEmptyResponseError(
436
+ resp.status,
437
+ raw.length,
438
+ "stream without body",
439
+ );
440
+ }
441
+ return;
442
+ }
443
+ const reader = resp.body.getReader();
444
+ const decoder = new TextDecoder();
445
+ const extractor = createStreamTextExtractor();
446
+ const lineChunks: string[] = [];
447
+ let lineLength = 0;
448
+ let rawSnippet = "";
449
+ let rawLength = 0;
450
+ const takeLine = (piece: string): string => {
451
+ if (!lineChunks.length) return piece;
452
+ if (piece) {
453
+ lineChunks.push(piece);
454
+ lineLength += piece.length;
455
+ }
456
+ const line = lineChunks.join("");
457
+ lineChunks.length = 0;
458
+ lineLength = 0;
459
+ return line;
460
+ };
461
+ const appendLineRemainder = (piece: string): void => {
462
+ if (!piece) return;
463
+ lineChunks.push(piece);
464
+ lineLength += piece.length;
465
+ };
466
+ const consumeDecoded = function* (decoded: string): Generator<string> {
467
+ let lineStart = 0;
468
+ let idx = decoded.indexOf("\n", lineStart);
469
+ while (idx >= 0) {
470
+ const line = takeLine(decoded.slice(lineStart, idx));
471
+ for (const delta of extractor.consumeLine(line)) yield delta;
472
+ lineStart = idx + 1;
473
+ idx = decoded.indexOf("\n", lineStart);
474
+ }
475
+ if (lineStart < decoded.length)
476
+ appendLineRemainder(decoded.slice(lineStart));
477
+ };
478
+ while (true) {
479
+ throwIfAborted(signal);
480
+ const { done, value } = await reader.read();
481
+ if (done) break;
482
+ const decoded = decoder.decode(value, { stream: true });
483
+ rawLength += decoded.length;
484
+ if (rawSnippet.length < 500)
485
+ rawSnippet += decoded.slice(0, 500 - rawSnippet.length);
486
+ for (const delta of consumeDecoded(decoded)) {
487
+ for await (const piece of resinSmoothedPieces(
488
+ delta,
489
+ resinSmooth,
490
+ signal,
491
+ )) {
492
+ yielded = true;
493
+ yield piece;
494
+ }
495
+ }
496
+ }
497
+ const tail = decoder.decode();
498
+ if (tail) {
499
+ rawLength += tail.length;
500
+ if (rawSnippet.length < 500)
501
+ rawSnippet += tail.slice(0, 500 - rawSnippet.length);
502
+ for (const delta of consumeDecoded(tail)) {
503
+ for await (const piece of resinSmoothedPieces(
504
+ delta,
505
+ resinSmooth,
506
+ signal,
507
+ )) {
508
+ yielded = true;
509
+ yield piece;
510
+ }
511
+ }
512
+ }
513
+ if (lineLength > 0) {
514
+ for (const delta of extractor.consumeLine(takeLine(""))) {
515
+ for await (const piece of resinSmoothedPieces(
516
+ delta,
517
+ resinSmooth,
518
+ signal,
519
+ )) {
520
+ yielded = true;
521
+ yield piece;
522
+ }
523
+ }
524
+ }
525
+ if (!yielded) {
526
+ const shape = cfg.log_requests
527
+ ? ` ${wrbResponseShapeSummary(rawSnippet)}`
528
+ : "";
529
+ log(
530
+ cfg,
531
+ `stream upstream produced no text (status=${resp.status}) rawLen=${rawLength}${shape}`,
532
+ );
533
+ const dataAnalysisErr = dataAnalysisEmptyResponseError(
534
+ rawSnippet,
535
+ fileRefs,
536
+ );
537
+ if (dataAnalysisErr) throw dataAnalysisErr;
538
+ const largePromptErr = largePromptEmptyResponseError(
539
+ prompt,
540
+ resp.status,
541
+ null,
542
+ largePromptEmptyResponseThreshold(cfg),
543
+ );
544
+ if (largePromptErr) throw largePromptErr;
545
+ const refreshedCfg = await refreshGeminiBuildLabelForRetry(
546
+ cfg,
547
+ activeCfg,
548
+ refreshedBL,
549
+ "stream",
550
+ );
551
+ if (refreshedCfg) {
552
+ refreshedBL = true;
553
+ activeCfg = refreshedCfg;
554
+ continue;
555
+ }
556
+ throw upstreamEmptyResponseError(resp.status, rawLength, "stream");
557
+ }
558
+ return;
559
+ } catch (e) {
560
+ if (isAbortError(e) || signal?.aborted) throw abortError(signal);
561
+ if (isInvalidGeminiCookieError(e) && !yielded && !refreshedCookie) {
562
+ const rotated = await rotateGeminiCookieForRetryWithReason(activeCfg);
563
+ if (rotated.config) {
564
+ refreshedCookie = true;
565
+ activeCfg = await configWithCachedGeminiBuildLabel(rotated.config);
566
+ continue;
567
+ }
568
+ throw invalidCookieErrorWithRotationReason(cfg, e, rotated.reason);
569
+ }
570
+ if (isInvalidGeminiCookieError(e) && !yielded && refreshedCookie)
571
+ throw invalidCookieErrorWithRotationReason(cfg, e, "rotation_updated");
572
+ if (
573
+ isLargePromptEmptyResponseError(e) ||
574
+ isDataAnalysisEmptyResponseError(e) ||
575
+ isInvalidGeminiCookieError(e)
576
+ )
577
+ throw e;
578
+ lastErr = e;
579
+ if (
580
+ !yielded &&
581
+ (await waitBeforeRetry(cfg, attempt, e, "Stream retry", signal))
582
+ ) {
583
+ continue;
584
+ }
585
+ throw e;
586
+ }
587
+ }
588
+ if (lastErr) throw lastErr;
589
+ }
590
+
591
+ function invalidCookieErrorWithRotationReason(
592
+ cfg: RuntimeConfig,
593
+ err: unknown,
594
+ reason: unknown,
595
+ ): unknown {
596
+ const meta =
597
+ err && typeof err === "object" ? (err as Partial<ErrorWithMetadata>) : {};
598
+ return (
599
+ invalidGeminiCookieError(
600
+ cfg,
601
+ meta.upstreamStatus || meta.status || 401,
602
+ typeof meta.rawLength === "number" ? meta.rawLength : null,
603
+ reason,
604
+ ) || err
605
+ );
606
+ }
src/gemini/transport/http.ts CHANGED
@@ -1,128 +1,133 @@
1
- import {
2
- abortError,
3
- isAbortError,
4
- throwIfAborted,
5
- timeoutSignal,
6
- } from "../../shared/abort";
7
- import {
8
- canFallbackAfterSocketError,
9
- errorLogSummary,
10
- } from "../../shared/errors";
11
- import { log } from "../../shared/logging";
12
- import { getDefaultSocketPool, resolveConnect, socketHttp } from "./socket";
13
- import type { SocketHttpResponse } from "./socket";
14
-
15
- type HttpBodyInit = BodyInit | ArrayBufferView;
16
-
17
- type HttpFetchOptions = {
18
- method?: string;
19
- headers?: Record<string, string>;
20
- body?: HttpBodyInit | null | undefined;
21
- bodyLength?: number | null | undefined;
22
- timeoutMs?: number;
23
- socket?: boolean;
24
- socketFallback?: "pre-response" | "never";
25
- signal?: AbortSignal | null | undefined;
26
- cfg?: { log_requests?: unknown } | null;
27
- acceptCompressed?: boolean;
28
- };
29
-
30
- // 统一上游入口:socket 优先,失败/不可用则回退 fetch。返回类 Response 对象。
31
- export async function httpFetch(
32
- url: string,
33
- {
34
- method = "GET",
35
- headers = {},
36
- body,
37
- bodyLength = null,
38
- timeoutMs = 180000,
39
- socket = true,
40
- socketFallback = "pre-response",
41
- signal,
42
- cfg,
43
- acceptCompressed,
44
- }: HttpFetchOptions = {},
45
- ): Promise<Response | SocketHttpResponse> {
46
- throwIfAborted(signal);
47
- if (socket) {
48
- const connect = await resolveConnect();
49
- if (connect) {
50
- try {
51
- const resp = await socketHttp(connect, url, {
52
- method,
53
- headers,
54
- body,
55
- bodyLength,
56
- timeoutMs,
57
- signal,
58
- keepAlive: true,
59
- pool: getDefaultSocketPool(),
60
- acceptCompressed: acceptCompressed ?? method.toUpperCase() === "GET",
61
- });
62
- return resp;
63
- } catch (e) {
64
- if (isAbortError(e) || signal?.aborted) throw abortError(signal);
65
- if (socketFallback === "never") {
66
- log(
67
- cfg,
68
- `socket upstream failed; fallback disabled for ${method}: ${errorLogSummary(e)}`,
69
- );
70
- throw e;
71
- }
72
- if (
73
- body instanceof ReadableStream &&
74
- socketErrorConsumedRequestBody(e)
75
- ) {
76
- log(
77
- cfg,
78
- `socket upstream failed; not falling back with streaming request body for ${method}: ${errorLogSummary(e)}`,
79
- );
80
- throw e;
81
- }
82
- if (!canFallbackAfterSocketError(method, e)) {
83
- log(
84
- cfg,
85
- `socket upstream failed; not falling back after upstream response for ${method}: ${errorLogSummary(e)}`,
86
- );
87
- throw e;
88
- }
89
- log(
90
- cfg,
91
- `socket upstream failed; falling back to fetch: ${errorLogSummary(e)}`,
92
- );
93
- }
94
- }
95
- }
96
- const linked = linkedFetchSignal(signal, timeoutSignal(timeoutMs));
97
- try {
98
- const init: RequestInit = { method, headers };
99
- if (body !== undefined) init.body = body as BodyInit;
100
- if (body instanceof ReadableStream)
101
- (init as RequestInit & { duplex?: "half" }).duplex = "half";
102
- if (linked.signal) init.signal = linked.signal;
103
- return await fetch(url, init);
104
- } finally {
105
- linked.cleanup();
106
- }
107
- }
108
-
109
- function socketErrorConsumedRequestBody(error: unknown): boolean {
110
- const err = error as
111
- | { requestBodyStarted?: unknown; code?: unknown }
112
- | null
113
- | undefined;
114
- return (
115
- !!err &&
116
- (err.requestBodyStarted === true ||
117
- err.code === "socket_stream_body_length_required")
118
- );
119
- }
120
-
121
- function linkedFetchSignal(
122
- signal: AbortSignal | null | undefined,
123
- timeout: AbortSignal | undefined,
124
- ): { signal: AbortSignal | undefined; cleanup: () => void } {
125
- if (!signal) return { signal: timeout, cleanup() {} };
126
- if (!timeout) return { signal, cleanup() {} };
127
- return { signal: AbortSignal.any([signal, timeout]), cleanup() {} };
128
- }
 
 
 
 
 
 
1
+ import {
2
+ abortError,
3
+ isAbortError,
4
+ throwIfAborted,
5
+ timeoutSignal,
6
+ } from "../../shared/abort";
7
+ import {
8
+ canFallbackAfterSocketError,
9
+ errorLogSummary,
10
+ } from "../../shared/errors";
11
+ import { log } from "../../shared/logging";
12
+ import { getDefaultSocketPool, resolveConnect, socketHttp } from "./socket";
13
+ import type { SocketHttpResponse } from "./socket";
14
+
15
+ type HttpBodyInit = BodyInit | ArrayBufferView;
16
+
17
+ type HttpFetchOptions = {
18
+ method?: string;
19
+ headers?: Record<string, string>;
20
+ body?: HttpBodyInit | null | undefined;
21
+ bodyLength?: number | null | undefined;
22
+ timeoutMs?: number;
23
+ socket?: boolean;
24
+ socketFallback?: "pre-response" | "never";
25
+ signal?: AbortSignal | null | undefined;
26
+ cfg?: { log_requests?: unknown; resin_proxy?: unknown } | null;
27
+ acceptCompressed?: boolean;
28
+ };
29
+
30
+ // 统一上游入口:socket 优先,失败/不可用则回退 fetch。返回类 Response 对象。
31
+ export async function httpFetch(
32
+ url: string,
33
+ {
34
+ method = "GET",
35
+ headers = {},
36
+ body,
37
+ bodyLength = null,
38
+ timeoutMs = 180000,
39
+ socket = true,
40
+ socketFallback = "pre-response",
41
+ signal,
42
+ cfg,
43
+ acceptCompressed,
44
+ }: HttpFetchOptions = {},
45
+ ): Promise<Response | SocketHttpResponse> {
46
+ throwIfAborted(signal);
47
+ // Resin 反代已提供干净出口;裸 socket 仅用于直连 Gemini 绕 429。
48
+ // 配了 resin_proxy 时强制 fetch,避免 CF socket 路径空响应。
49
+ if (cfg?.resin_proxy) {
50
+ socket = false;
51
+ }
52
+ if (socket) {
53
+ const connect = await resolveConnect();
54
+ if (connect) {
55
+ try {
56
+ const resp = await socketHttp(connect, url, {
57
+ method,
58
+ headers,
59
+ body,
60
+ bodyLength,
61
+ timeoutMs,
62
+ signal,
63
+ keepAlive: true,
64
+ pool: getDefaultSocketPool(),
65
+ acceptCompressed: acceptCompressed ?? method.toUpperCase() === "GET",
66
+ });
67
+ return resp;
68
+ } catch (e) {
69
+ if (isAbortError(e) || signal?.aborted) throw abortError(signal);
70
+ if (socketFallback === "never") {
71
+ log(
72
+ cfg,
73
+ `socket upstream failed; fallback disabled for ${method}: ${errorLogSummary(e)}`,
74
+ );
75
+ throw e;
76
+ }
77
+ if (
78
+ body instanceof ReadableStream &&
79
+ socketErrorConsumedRequestBody(e)
80
+ ) {
81
+ log(
82
+ cfg,
83
+ `socket upstream failed; not falling back with streaming request body for ${method}: ${errorLogSummary(e)}`,
84
+ );
85
+ throw e;
86
+ }
87
+ if (!canFallbackAfterSocketError(method, e)) {
88
+ log(
89
+ cfg,
90
+ `socket upstream failed; not falling back after upstream response for ${method}: ${errorLogSummary(e)}`,
91
+ );
92
+ throw e;
93
+ }
94
+ log(
95
+ cfg,
96
+ `socket upstream failed; falling back to fetch: ${errorLogSummary(e)}`,
97
+ );
98
+ }
99
+ }
100
+ }
101
+ const linked = linkedFetchSignal(signal, timeoutSignal(timeoutMs));
102
+ try {
103
+ const init: RequestInit = { method, headers };
104
+ if (body !== undefined) init.body = body as BodyInit;
105
+ if (body instanceof ReadableStream)
106
+ (init as RequestInit & { duplex?: "half" }).duplex = "half";
107
+ if (linked.signal) init.signal = linked.signal;
108
+ return await fetch(url, init);
109
+ } finally {
110
+ linked.cleanup();
111
+ }
112
+ }
113
+
114
+ function socketErrorConsumedRequestBody(error: unknown): boolean {
115
+ const err = error as
116
+ | { requestBodyStarted?: unknown; code?: unknown }
117
+ | null
118
+ | undefined;
119
+ return (
120
+ !!err &&
121
+ (err.requestBodyStarted === true ||
122
+ err.code === "socket_stream_body_length_required")
123
+ );
124
+ }
125
+
126
+ function linkedFetchSignal(
127
+ signal: AbortSignal | null | undefined,
128
+ timeout: AbortSignal | undefined,
129
+ ): { signal: AbortSignal | undefined; cleanup: () => void } {
130
+ if (!signal) return { signal: timeout, cleanup() {} };
131
+ if (!timeout) return { signal, cleanup() {} };
132
+ return { signal: AbortSignal.any([signal, timeout]), cleanup() {} };
133
+ }
src/http/google/stream.ts CHANGED
@@ -1,152 +1,154 @@
1
- import {
2
- createCompletionStreamLifecycle,
3
- recordCompletionStreamEvent,
4
- streamPlainCompletionEvents,
5
- } from "../../completion";
6
- import type { CompletionProvider } from "../../completion";
7
- import type { RuntimeConfig } from "../../config";
8
- import type { ResolvedModel } from "../../models";
9
- import type { FileRef, LooseRequest } from "../../completion/types";
10
- import { streamGoogleToolCompletionEvents } from "../../completion/google";
11
- import { tokenCountFromCounts } from "../../shared/tokens";
12
- import { errorLogSummary, upstreamErrorCode } from "../../shared/errors";
13
- import { log } from "../../shared/logging";
14
- import type { SSEWrite } from "../core/sse";
15
- import {
16
- streamInterruptedWarningText,
17
- writeStreamWarningEvent,
18
- } from "../core/stream-errors";
19
- import { createDeltaCoalescer } from "../stream/coalescer";
20
- import {
21
- googleStreamDonePayload,
22
- writeGoogleCandidate,
23
- writeGoogleDone,
24
- writeGoogleStreamError,
25
- } from "./format";
26
-
27
- type ResolvedCompletionModel = Extract<ResolvedModel, { name: string }>;
28
- type GooglePlainStreamParams = {
29
- provider: CompletionProvider;
30
- prompt: string;
31
- rm: ResolvedCompletionModel;
32
- fileRefs: FileRef[] | null;
33
- promptTokens: number;
34
- signal: AbortSignal;
35
- };
36
- type GoogleToolStreamParams = GooglePlainStreamParams & {
37
- tools: LooseRequest[] | null;
38
- effectiveReq: LooseRequest;
39
- };
40
-
41
- export async function streamGooglePlain(
42
- write: SSEWrite,
43
- cfg: RuntimeConfig,
44
- params: GooglePlainStreamParams,
45
- ) {
46
- const { provider, prompt, rm, fileRefs, promptTokens, signal } = params;
47
- const lifecycle = createCompletionStreamLifecycle();
48
- const textCoalescer = createDeltaCoalescer(
49
- (delta) => {
50
- const text = delta.text || "";
51
- return write(
52
- `data: ${JSON.stringify({ candidates: [{ content: { parts: [{ text }], role: "model" }, index: 0 }], modelVersion: rm.name })}\n\n`,
53
- );
54
- },
55
- undefined,
56
- undefined,
57
- { emitFirstImmediately: true },
58
- );
59
- for await (const event of streamPlainCompletionEvents(
60
- provider,
61
- { prompt, rm, fileRefs },
62
- { signal, coalesceTextDeltas: true },
63
- )) {
64
- recordCompletionStreamEvent(lifecycle, event);
65
- if (event.type === "text_delta") {
66
- const appended = textCoalescer.append("text", event.text);
67
- if (appended) await appended;
68
- }
69
- }
70
- const flushed = textCoalescer.flush();
71
- if (flushed) await flushed;
72
- if (lifecycle.issue) {
73
- if (!lifecycle.emittedText) {
74
- log(
75
- cfg,
76
- `google stream failed before output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "upstream_error"} error=${errorLogSummary(lifecycle.issue.error)}`,
77
- );
78
- await writeGoogleStreamError(write, rm.name, lifecycle.issue.error);
79
- return;
80
- }
81
- const warning = `\n\n${streamInterruptedWarningText(lifecycle.issue.error)}`;
82
- log(
83
- cfg,
84
- `google stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(lifecycle.issue.error)}`,
85
- );
86
- await writeStreamWarningEvent(write, lifecycle.issue.error, warning.trim());
87
- }
88
- const candidateTokens = tokenCountFromCounts(lifecycle.completionCounts);
89
- await write(
90
- `data: ${JSON.stringify(googleStreamDonePayload(rm.name, promptTokens, candidateTokens, lifecycle.issue ? lifecycle.issue.error : null))}\n\n`,
91
- );
92
- }
93
-
94
- export async function streamGoogleTools(
95
- write: SSEWrite,
96
- cfg: RuntimeConfig,
97
- params: GoogleToolStreamParams,
98
- ) {
99
- const {
100
- provider,
101
- prompt,
102
- rm,
103
- fileRefs,
104
- tools,
105
- effectiveReq,
106
- promptTokens,
107
- signal,
108
- } = params;
109
- for await (const event of streamGoogleToolCompletionEvents(provider, {
110
- prompt,
111
- rm,
112
- fileRefs,
113
- tools,
114
- effectiveReq,
115
- promptTokens,
116
- signal,
117
- })) {
118
- if (event.type === "candidate") {
119
- await writeGoogleCandidate(
120
- write,
121
- rm.name,
122
- event.parts,
123
- event.finishReason,
124
- );
125
- } else if (event.type === "error") {
126
- log(
127
- cfg,
128
- `google tool stream failed before output model=${rm.name} code=${upstreamErrorCode(event.error) || "upstream_error"} error=${errorLogSummary(event.error)}`,
129
- );
130
- await writeGoogleStreamError(write, rm.name, event.error);
131
- return;
132
- } else if (event.type === "warning") {
133
- log(
134
- cfg,
135
- `google tool stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(event.error) || "stream_interrupted"} error=${errorLogSummary(event.error)}`,
136
- );
137
- await writeStreamWarningEvent(write, event.error, event.message);
138
- } else if (event.type === "tool_policy_violation") {
139
- log(
140
- cfg,
141
- `google tool stream policy violation model=${rm.name} code=${event.violation.code}`,
142
- );
143
- await writeGoogleStreamError(write, rm.name, {
144
- message: event.violation.message,
145
- code: event.violation.code,
146
- });
147
- return;
148
- } else if (event.type === "done") {
149
- await writeGoogleDone(write, rm.name, event.usageMetadata);
150
- }
151
- }
152
- }
 
 
 
1
+ import {
2
+ createCompletionStreamLifecycle,
3
+ recordCompletionStreamEvent,
4
+ streamPlainCompletionEvents,
5
+ } from "../../completion";
6
+ import type { CompletionProvider } from "../../completion";
7
+ import type { RuntimeConfig } from "../../config";
8
+ import type { ResolvedModel } from "../../models";
9
+ import type { FileRef, LooseRequest } from "../../completion/types";
10
+ import { streamGoogleToolCompletionEvents } from "../../completion/google";
11
+ import { tokenCountFromCounts } from "../../shared/tokens";
12
+ import { errorLogSummary, upstreamErrorCode } from "../../shared/errors";
13
+ import { log } from "../../shared/logging";
14
+ import type { SSEWrite } from "../core/sse";
15
+ import {
16
+ streamInterruptedWarningText,
17
+ writeStreamWarningEvent,
18
+ } from "../core/stream-errors";
19
+ import { createDeltaCoalescer } from "../stream/coalescer";
20
+ import {
21
+ googleStreamDonePayload,
22
+ writeGoogleCandidate,
23
+ writeGoogleDone,
24
+ writeGoogleStreamError,
25
+ } from "./format";
26
+
27
+ type ResolvedCompletionModel = Extract<ResolvedModel, { name: string }>;
28
+ type GooglePlainStreamParams = {
29
+ provider: CompletionProvider;
30
+ prompt: string;
31
+ rm: ResolvedCompletionModel;
32
+ fileRefs: FileRef[] | null;
33
+ promptTokens: number;
34
+ signal: AbortSignal;
35
+ };
36
+ type GoogleToolStreamParams = GooglePlainStreamParams & {
37
+ tools: LooseRequest[] | null;
38
+ effectiveReq: LooseRequest;
39
+ };
40
+
41
+ export async function streamGooglePlain(
42
+ write: SSEWrite,
43
+ cfg: RuntimeConfig,
44
+ params: GooglePlainStreamParams,
45
+ ) {
46
+ const { provider, prompt, rm, fileRefs, promptTokens, signal } = params;
47
+ const lifecycle = createCompletionStreamLifecycle();
48
+ const resinSmooth = !!cfg.resin_proxy;
49
+ const textCoalescer = createDeltaCoalescer(
50
+ (delta) => {
51
+ const text = delta.text || "";
52
+ return write(
53
+ `data: ${JSON.stringify({ candidates: [{ content: { parts: [{ text }], role: "model" }, index: 0 }], modelVersion: rm.name })}\n\n`,
54
+ );
55
+ },
56
+ resinSmooth ? 1 : undefined,
57
+ resinSmooth ? 0 : undefined,
58
+ { emitFirstImmediately: true },
59
+ );
60
+ for await (const event of streamPlainCompletionEvents(
61
+ provider,
62
+ { prompt, rm, fileRefs },
63
+ { signal, coalesceTextDeltas: !resinSmooth },
64
+ )) {
65
+ recordCompletionStreamEvent(lifecycle, event);
66
+ if (event.type === "text_delta") {
67
+ const appended = textCoalescer.append("text", event.text);
68
+ if (appended) await appended;
69
+ }
70
+ }
71
+ const flushed = textCoalescer.flush();
72
+ if (flushed) await flushed;
73
+ if (lifecycle.issue) {
74
+ if (!lifecycle.emittedText) {
75
+ log(
76
+ cfg,
77
+ `google stream failed before output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "upstream_error"} error=${errorLogSummary(lifecycle.issue.error)}`,
78
+ );
79
+ await writeGoogleStreamError(write, rm.name, lifecycle.issue.error);
80
+ return;
81
+ }
82
+ const warning = `\n\n${streamInterruptedWarningText(lifecycle.issue.error)}`;
83
+ log(
84
+ cfg,
85
+ `google stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(lifecycle.issue.error)}`,
86
+ );
87
+ await writeStreamWarningEvent(write, lifecycle.issue.error, warning.trim());
88
+ }
89
+ const candidateTokens = tokenCountFromCounts(lifecycle.completionCounts);
90
+ await write(
91
+ `data: ${JSON.stringify(googleStreamDonePayload(rm.name, promptTokens, candidateTokens, lifecycle.issue ? lifecycle.issue.error : null))}\n\n`,
92
+ );
93
+ }
94
+
95
+ export async function streamGoogleTools(
96
+ write: SSEWrite,
97
+ cfg: RuntimeConfig,
98
+ params: GoogleToolStreamParams,
99
+ ) {
100
+ const resinSmooth = !!cfg.resin_proxy;
101
+ const {
102
+ provider,
103
+ prompt,
104
+ rm,
105
+ fileRefs,
106
+ tools,
107
+ effectiveReq,
108
+ promptTokens,
109
+ signal,
110
+ } = params;
111
+ for await (const event of streamGoogleToolCompletionEvents(provider, {
112
+ prompt,
113
+ rm,
114
+ fileRefs,
115
+ tools,
116
+ effectiveReq,
117
+ promptTokens,
118
+ signal,
119
+ })) {
120
+ if (event.type === "candidate") {
121
+ await writeGoogleCandidate(
122
+ write,
123
+ rm.name,
124
+ event.parts,
125
+ event.finishReason,
126
+ );
127
+ } else if (event.type === "error") {
128
+ log(
129
+ cfg,
130
+ `google tool stream failed before output model=${rm.name} code=${upstreamErrorCode(event.error) || "upstream_error"} error=${errorLogSummary(event.error)}`,
131
+ );
132
+ await writeGoogleStreamError(write, rm.name, event.error);
133
+ return;
134
+ } else if (event.type === "warning") {
135
+ log(
136
+ cfg,
137
+ `google tool stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(event.error) || "stream_interrupted"} error=${errorLogSummary(event.error)}`,
138
+ );
139
+ await writeStreamWarningEvent(write, event.error, event.message);
140
+ } else if (event.type === "tool_policy_violation") {
141
+ log(
142
+ cfg,
143
+ `google tool stream policy violation model=${rm.name} code=${event.violation.code}`,
144
+ );
145
+ await writeGoogleStreamError(write, rm.name, {
146
+ message: event.violation.message,
147
+ code: event.violation.code,
148
+ });
149
+ return;
150
+ } else if (event.type === "done") {
151
+ await writeGoogleDone(write, rm.name, event.usageMetadata);
152
+ }
153
+ }
154
+ }
src/http/openai/chat-stream.ts CHANGED
@@ -1,283 +1,285 @@
1
- import { parseJsonObject } from "../core/json";
2
- import type { SSEWrite } from "../core/sse";
3
- import {
4
- streamInterruptedWarningText,
5
- writeStreamWarningEvent,
6
- } from "../core/stream-errors";
7
- import { createDeltaCoalescer } from "../stream/coalescer";
8
- import {
9
- EMPTY_UPSTREAM_MSG,
10
- createCompletionStreamLifecycle,
11
- recordCompletionStreamEvent,
12
- streamPlainCompletionEvents,
13
- streamToolSieveCompletionEvents,
14
- } from "../../completion";
15
- import type {
16
- CompletionProvider,
17
- CompletionStreamEvent,
18
- } from "../../completion";
19
- import type { RuntimeConfig } from "../../config";
20
- import type { ResolvedModel } from "../../models";
21
- import type { FileRef } from "../../completion/types";
22
- import { errorLogSummary, upstreamErrorCode } from "../../shared/errors";
23
- import { log } from "../../shared/logging";
24
- import {
25
- combinedTokenCount,
26
- createTokenCounter,
27
- tokenCountFromCounts,
28
- } from "../../shared/tokens";
29
- import { formatOpenAIStreamToolCalls } from "../../toolcall/openai-format";
30
- import type { OpenAIToolCall } from "../../toolcall/openai-format";
31
- import type { ToolChoicePolicy } from "../../toolcall/policy-openai";
32
- import { openAIChatChunk, writeOpenAIChatUsageTokenChunk } from "./format";
33
- import { writeOpenAIChatStreamError } from "./format";
34
-
35
- type StreamIssue = Extract<
36
- CompletionStreamEvent,
37
- { type: "warning" } | { type: "stream_error" }
38
- >;
39
- type ResolvedCompletionModel = Extract<ResolvedModel, { name: string }>;
40
- type OpenAIChatChunkWriter = (
41
- delta: Record<string, unknown>,
42
- finish: string | null,
43
- ) => void | Promise<void>;
44
- type OpenAIChatDeltaCoalescer = ReturnType<typeof createDeltaCoalescer>;
45
- type OpenAIChatPlainStreamParams = {
46
- provider: CompletionProvider;
47
- id: string;
48
- model: string;
49
- prompt: string;
50
- rm: ResolvedCompletionModel;
51
- fileRefs: FileRef[] | null;
52
- includeUsage: boolean;
53
- promptTokens: number;
54
- signal: AbortSignal;
55
- };
56
- type OpenAIChatToolSieveStreamParams = OpenAIChatPlainStreamParams & {
57
- tools: unknown[];
58
- toolPolicy: ToolChoicePolicy | null | undefined;
59
- };
60
-
61
- export async function streamOpenAIChatPlain(
62
- write: SSEWrite,
63
- cfg: RuntimeConfig,
64
- params: OpenAIChatPlainStreamParams,
65
- ) {
66
- const {
67
- provider,
68
- id,
69
- model,
70
- prompt,
71
- rm,
72
- fileRefs,
73
- includeUsage,
74
- promptTokens,
75
- signal,
76
- } = params;
77
- const lifecycle = createCompletionStreamLifecycle();
78
- const writeChunk = (delta: Record<string, unknown>, finish: string | null) =>
79
- write(
80
- `data: ${JSON.stringify(openAIChatChunk(id, model, delta, finish))}\n\n`,
81
- );
82
- const deltaCoalescer = createDeltaCoalescer(
83
- (delta) => writeChunk(delta, null),
84
- undefined,
85
- undefined,
86
- { emitFirstImmediately: true },
87
- );
88
- await writeChunk({ role: "assistant" }, null);
89
-
90
- for await (const event of streamPlainCompletionEvents(
91
- provider,
92
- { prompt, rm, fileRefs },
93
- { signal, coalesceTextDeltas: true },
94
- )) {
95
- recordCompletionStreamEvent(lifecycle, event);
96
- if (event.type === "text_delta") {
97
- const appended = deltaCoalescer.append("content", event.text);
98
- if (appended) await appended;
99
- }
100
- }
101
- await flushOpenAIChatDeltas(deltaCoalescer);
102
-
103
- if (
104
- (lifecycle.issue && lifecycle.issue.type === "stream_error") ||
105
- lifecycle.empty
106
- ) {
107
- const error = lifecycle.issue?.error || {
108
- message: EMPTY_UPSTREAM_MSG,
109
- code: "upstream_empty",
110
- };
111
- log(
112
- cfg,
113
- lifecycle.issue
114
- ? `openai chat stream failed before output model=${rm.name} code=${upstreamErrorCode(error) || "upstream_error"} error=${errorLogSummary(error)}`
115
- : `openai chat stream produced no content model=${rm.name}`,
116
- );
117
- await writeOpenAIChatStreamError(write, id, model, error);
118
- return;
119
- } else if (lifecycle.issue) {
120
- await writeOpenAIChatInterrupted(write, cfg, rm, lifecycle.issue);
121
- }
122
- await finishOpenAIChatStream(
123
- write,
124
- writeChunk,
125
- id,
126
- model,
127
- includeUsage,
128
- promptTokens,
129
- lifecycle.completionCounts,
130
- );
131
- }
132
-
133
- export async function streamOpenAIChatWithToolSieve(
134
- write: SSEWrite,
135
- _cfg: RuntimeConfig,
136
- params: OpenAIChatToolSieveStreamParams,
137
- ) {
138
- const {
139
- provider,
140
- id,
141
- model,
142
- prompt,
143
- rm,
144
- fileRefs,
145
- tools,
146
- toolPolicy,
147
- includeUsage,
148
- promptTokens,
149
- signal,
150
- } = params;
151
- const extraTokenCounter = createTokenCounter();
152
- const writeChunk = (delta: Record<string, unknown>, finish: string | null) =>
153
- write(
154
- `data: ${JSON.stringify(openAIChatChunk(id, model, delta, finish))}\n\n`,
155
- );
156
- const deltaCoalescer = createDeltaCoalescer(
157
- (delta) => writeChunk(delta, null),
158
- undefined,
159
- undefined,
160
- { emitFirstImmediately: true },
161
- );
162
- const toolLifecycle = createCompletionStreamLifecycle();
163
- await writeChunk({ role: "assistant" }, null);
164
-
165
- for await (const event of streamToolSieveCompletionEvents(
166
- provider,
167
- { prompt, rm, fileRefs, tools, toolPolicy },
168
- { signal, coalesceTextDeltas: true },
169
- )) {
170
- recordCompletionStreamEvent(toolLifecycle, event);
171
- if (event.type === "text_delta") {
172
- const appended = deltaCoalescer.append("content", event.text);
173
- if (appended) await appended;
174
- }
175
- }
176
- await flushOpenAIChatDeltas(deltaCoalescer);
177
-
178
- if (toolLifecycle.violation) {
179
- await flushOpenAIChatDeltas(deltaCoalescer);
180
- log(
181
- _cfg,
182
- `openai chat stream tool policy violation model=${rm.name} code=${toolLifecycle.violation.code}`,
183
- );
184
- await writeOpenAIChatStreamError(write, id, model, toolLifecycle.violation);
185
- return;
186
- }
187
- if (toolLifecycle.toolCalls?.length) {
188
- await flushOpenAIChatDeltas(deltaCoalescer);
189
- if (toolLifecycle.issue) {
190
- log(
191
- _cfg,
192
- `openai chat stream interrupted after tool calls model=${rm.name} code=${upstreamErrorCode(toolLifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(toolLifecycle.issue.error)}`,
193
- );
194
- await writeStreamWarningEvent(write, toolLifecycle.issue.error);
195
- }
196
- const toolCallDeltas = formatOpenAIStreamToolCalls(
197
- toolLifecycle.toolCalls.map(openAIStreamToolCallInput),
198
- new Map(),
199
- tools,
200
- );
201
- await writeChunk({ tool_calls: toolCallDeltas }, "tool_calls");
202
- extraTokenCounter.append(JSON.stringify(toolLifecycle.toolCalls));
203
- } else {
204
- if (!toolLifecycle.emittedText || toolLifecycle.empty) {
205
- const error = toolLifecycle.issue?.error || {
206
- message: EMPTY_UPSTREAM_MSG,
207
- code: "upstream_empty",
208
- };
209
- log(
210
- _cfg,
211
- toolLifecycle.issue
212
- ? `openai chat stream failed before output model=${rm.name} code=${upstreamErrorCode(error) || "upstream_error"} error=${errorLogSummary(error)}`
213
- : `openai chat stream produced no content model=${rm.name}`,
214
- );
215
- await writeOpenAIChatStreamError(write, id, model, error);
216
- return;
217
- } else if (toolLifecycle.issue) {
218
- await writeOpenAIChatInterrupted(write, _cfg, rm, toolLifecycle.issue);
219
- }
220
- await writeChunk({}, "stop");
221
- }
222
- if (includeUsage)
223
- await writeOpenAIChatUsageTokenChunk(
224
- write,
225
- id,
226
- model,
227
- promptTokens,
228
- combinedTokenCount(toolLifecycle.completionCounts, extraTokenCounter),
229
- );
230
- await write("data: [DONE]\n\n");
231
- }
232
-
233
- async function flushOpenAIChatDeltas(
234
- coalescer: OpenAIChatDeltaCoalescer,
235
- ): Promise<void> {
236
- const flushed = coalescer.flush();
237
- if (flushed) await flushed;
238
- }
239
-
240
- async function finishOpenAIChatStream(
241
- write: SSEWrite,
242
- writeChunk: OpenAIChatChunkWriter,
243
- id: string,
244
- model: string,
245
- includeUsage: boolean,
246
- promptTokens: number,
247
- completionCounts: Parameters<typeof tokenCountFromCounts>[0],
248
- ): Promise<void> {
249
- await writeChunk({}, "stop");
250
- if (includeUsage)
251
- await writeOpenAIChatUsageTokenChunk(
252
- write,
253
- id,
254
- model,
255
- promptTokens,
256
- tokenCountFromCounts(completionCounts),
257
- );
258
- await write("data: [DONE]\n\n");
259
- }
260
-
261
- async function writeOpenAIChatInterrupted(
262
- write: SSEWrite,
263
- cfg: RuntimeConfig,
264
- rm: ResolvedCompletionModel,
265
- issue: StreamIssue,
266
- ): Promise<void> {
267
- const warning = `\n\n${streamInterruptedWarningText(issue.error)}`;
268
- log(
269
- cfg,
270
- `openai chat stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(issue.error) || "stream_interrupted"} error=${errorLogSummary(issue.error)}`,
271
- );
272
- await writeStreamWarningEvent(write, issue.error, warning.trim());
273
- }
274
-
275
- function openAIStreamToolCallInput(toolCall: OpenAIToolCall): {
276
- name: unknown;
277
- input: unknown;
278
- } {
279
- return {
280
- name: toolCall.function.name,
281
- input: parseJsonObject(toolCall.function.arguments),
282
- };
283
- }
 
 
 
1
+ import { parseJsonObject } from "../core/json";
2
+ import type { SSEWrite } from "../core/sse";
3
+ import {
4
+ streamInterruptedWarningText,
5
+ writeStreamWarningEvent,
6
+ } from "../core/stream-errors";
7
+ import { createDeltaCoalescer } from "../stream/coalescer";
8
+ import {
9
+ EMPTY_UPSTREAM_MSG,
10
+ createCompletionStreamLifecycle,
11
+ recordCompletionStreamEvent,
12
+ streamPlainCompletionEvents,
13
+ streamToolSieveCompletionEvents,
14
+ } from "../../completion";
15
+ import type {
16
+ CompletionProvider,
17
+ CompletionStreamEvent,
18
+ } from "../../completion";
19
+ import type { RuntimeConfig } from "../../config";
20
+ import type { ResolvedModel } from "../../models";
21
+ import type { FileRef } from "../../completion/types";
22
+ import { errorLogSummary, upstreamErrorCode } from "../../shared/errors";
23
+ import { log } from "../../shared/logging";
24
+ import {
25
+ combinedTokenCount,
26
+ createTokenCounter,
27
+ tokenCountFromCounts,
28
+ } from "../../shared/tokens";
29
+ import { formatOpenAIStreamToolCalls } from "../../toolcall/openai-format";
30
+ import type { OpenAIToolCall } from "../../toolcall/openai-format";
31
+ import type { ToolChoicePolicy } from "../../toolcall/policy-openai";
32
+ import { openAIChatChunk, writeOpenAIChatUsageTokenChunk } from "./format";
33
+ import { writeOpenAIChatStreamError } from "./format";
34
+
35
+ type StreamIssue = Extract<
36
+ CompletionStreamEvent,
37
+ { type: "warning" } | { type: "stream_error" }
38
+ >;
39
+ type ResolvedCompletionModel = Extract<ResolvedModel, { name: string }>;
40
+ type OpenAIChatChunkWriter = (
41
+ delta: Record<string, unknown>,
42
+ finish: string | null,
43
+ ) => void | Promise<void>;
44
+ type OpenAIChatDeltaCoalescer = ReturnType<typeof createDeltaCoalescer>;
45
+ type OpenAIChatPlainStreamParams = {
46
+ provider: CompletionProvider;
47
+ id: string;
48
+ model: string;
49
+ prompt: string;
50
+ rm: ResolvedCompletionModel;
51
+ fileRefs: FileRef[] | null;
52
+ includeUsage: boolean;
53
+ promptTokens: number;
54
+ signal: AbortSignal;
55
+ };
56
+ type OpenAIChatToolSieveStreamParams = OpenAIChatPlainStreamParams & {
57
+ tools: unknown[];
58
+ toolPolicy: ToolChoicePolicy | null | undefined;
59
+ };
60
+
61
+ export async function streamOpenAIChatPlain(
62
+ write: SSEWrite,
63
+ cfg: RuntimeConfig,
64
+ params: OpenAIChatPlainStreamParams,
65
+ ) {
66
+ const {
67
+ provider,
68
+ id,
69
+ model,
70
+ prompt,
71
+ rm,
72
+ fileRefs,
73
+ includeUsage,
74
+ promptTokens,
75
+ signal,
76
+ } = params;
77
+ const lifecycle = createCompletionStreamLifecycle();
78
+ const resinSmooth = !!cfg.resin_proxy;
79
+ const writeChunk = (delta: Record<string, unknown>, finish: string | null) =>
80
+ write(
81
+ `data: ${JSON.stringify(openAIChatChunk(id, model, delta, finish))}\n\n`,
82
+ );
83
+ const deltaCoalescer = createDeltaCoalescer(
84
+ (delta) => writeChunk(delta, null),
85
+ resinSmooth ? 1 : undefined,
86
+ resinSmooth ? 0 : undefined,
87
+ { emitFirstImmediately: true },
88
+ );
89
+ await writeChunk({ role: "assistant" }, null);
90
+
91
+ for await (const event of streamPlainCompletionEvents(
92
+ provider,
93
+ { prompt, rm, fileRefs },
94
+ { signal, coalesceTextDeltas: !resinSmooth },
95
+ )) {
96
+ recordCompletionStreamEvent(lifecycle, event);
97
+ if (event.type === "text_delta") {
98
+ const appended = deltaCoalescer.append("content", event.text);
99
+ if (appended) await appended;
100
+ }
101
+ }
102
+ await flushOpenAIChatDeltas(deltaCoalescer);
103
+
104
+ if (
105
+ (lifecycle.issue && lifecycle.issue.type === "stream_error") ||
106
+ lifecycle.empty
107
+ ) {
108
+ const error = lifecycle.issue?.error || {
109
+ message: EMPTY_UPSTREAM_MSG,
110
+ code: "upstream_empty",
111
+ };
112
+ log(
113
+ cfg,
114
+ lifecycle.issue
115
+ ? `openai chat stream failed before output model=${rm.name} code=${upstreamErrorCode(error) || "upstream_error"} error=${errorLogSummary(error)}`
116
+ : `openai chat stream produced no content model=${rm.name}`,
117
+ );
118
+ await writeOpenAIChatStreamError(write, id, model, error);
119
+ return;
120
+ } else if (lifecycle.issue) {
121
+ await writeOpenAIChatInterrupted(write, cfg, rm, lifecycle.issue);
122
+ }
123
+ await finishOpenAIChatStream(
124
+ write,
125
+ writeChunk,
126
+ id,
127
+ model,
128
+ includeUsage,
129
+ promptTokens,
130
+ lifecycle.completionCounts,
131
+ );
132
+ }
133
+
134
+ export async function streamOpenAIChatWithToolSieve(
135
+ write: SSEWrite,
136
+ _cfg: RuntimeConfig,
137
+ params: OpenAIChatToolSieveStreamParams,
138
+ ) {
139
+ const {
140
+ provider,
141
+ id,
142
+ model,
143
+ prompt,
144
+ rm,
145
+ fileRefs,
146
+ tools,
147
+ toolPolicy,
148
+ includeUsage,
149
+ promptTokens,
150
+ signal,
151
+ } = params;
152
+ const extraTokenCounter = createTokenCounter();
153
+ const writeChunk = (delta: Record<string, unknown>, finish: string | null) =>
154
+ write(
155
+ `data: ${JSON.stringify(openAIChatChunk(id, model, delta, finish))}\n\n`,
156
+ );
157
+ const resinSmooth = !!_cfg.resin_proxy;
158
+ const deltaCoalescer = createDeltaCoalescer(
159
+ (delta) => writeChunk(delta, null),
160
+ resinSmooth ? 1 : undefined,
161
+ resinSmooth ? 0 : undefined,
162
+ { emitFirstImmediately: true },
163
+ );
164
+ const toolLifecycle = createCompletionStreamLifecycle();
165
+ await writeChunk({ role: "assistant" }, null);
166
+
167
+ for await (const event of streamToolSieveCompletionEvents(
168
+ provider,
169
+ { prompt, rm, fileRefs, tools, toolPolicy },
170
+ { signal, coalesceTextDeltas: !resinSmooth },
171
+ )) {
172
+ recordCompletionStreamEvent(toolLifecycle, event);
173
+ if (event.type === "text_delta") {
174
+ const appended = deltaCoalescer.append("content", event.text);
175
+ if (appended) await appended;
176
+ }
177
+ }
178
+ await flushOpenAIChatDeltas(deltaCoalescer);
179
+
180
+ if (toolLifecycle.violation) {
181
+ await flushOpenAIChatDeltas(deltaCoalescer);
182
+ log(
183
+ _cfg,
184
+ `openai chat stream tool policy violation model=${rm.name} code=${toolLifecycle.violation.code}`,
185
+ );
186
+ await writeOpenAIChatStreamError(write, id, model, toolLifecycle.violation);
187
+ return;
188
+ }
189
+ if (toolLifecycle.toolCalls?.length) {
190
+ await flushOpenAIChatDeltas(deltaCoalescer);
191
+ if (toolLifecycle.issue) {
192
+ log(
193
+ _cfg,
194
+ `openai chat stream interrupted after tool calls model=${rm.name} code=${upstreamErrorCode(toolLifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(toolLifecycle.issue.error)}`,
195
+ );
196
+ await writeStreamWarningEvent(write, toolLifecycle.issue.error);
197
+ }
198
+ const toolCallDeltas = formatOpenAIStreamToolCalls(
199
+ toolLifecycle.toolCalls.map(openAIStreamToolCallInput),
200
+ new Map(),
201
+ tools,
202
+ );
203
+ await writeChunk({ tool_calls: toolCallDeltas }, "tool_calls");
204
+ extraTokenCounter.append(JSON.stringify(toolLifecycle.toolCalls));
205
+ } else {
206
+ if (!toolLifecycle.emittedText || toolLifecycle.empty) {
207
+ const error = toolLifecycle.issue?.error || {
208
+ message: EMPTY_UPSTREAM_MSG,
209
+ code: "upstream_empty",
210
+ };
211
+ log(
212
+ _cfg,
213
+ toolLifecycle.issue
214
+ ? `openai chat stream failed before output model=${rm.name} code=${upstreamErrorCode(error) || "upstream_error"} error=${errorLogSummary(error)}`
215
+ : `openai chat stream produced no content model=${rm.name}`,
216
+ );
217
+ await writeOpenAIChatStreamError(write, id, model, error);
218
+ return;
219
+ } else if (toolLifecycle.issue) {
220
+ await writeOpenAIChatInterrupted(write, _cfg, rm, toolLifecycle.issue);
221
+ }
222
+ await writeChunk({}, "stop");
223
+ }
224
+ if (includeUsage)
225
+ await writeOpenAIChatUsageTokenChunk(
226
+ write,
227
+ id,
228
+ model,
229
+ promptTokens,
230
+ combinedTokenCount(toolLifecycle.completionCounts, extraTokenCounter),
231
+ );
232
+ await write("data: [DONE]\n\n");
233
+ }
234
+
235
+ async function flushOpenAIChatDeltas(
236
+ coalescer: OpenAIChatDeltaCoalescer,
237
+ ): Promise<void> {
238
+ const flushed = coalescer.flush();
239
+ if (flushed) await flushed;
240
+ }
241
+
242
+ async function finishOpenAIChatStream(
243
+ write: SSEWrite,
244
+ writeChunk: OpenAIChatChunkWriter,
245
+ id: string,
246
+ model: string,
247
+ includeUsage: boolean,
248
+ promptTokens: number,
249
+ completionCounts: Parameters<typeof tokenCountFromCounts>[0],
250
+ ): Promise<void> {
251
+ await writeChunk({}, "stop");
252
+ if (includeUsage)
253
+ await writeOpenAIChatUsageTokenChunk(
254
+ write,
255
+ id,
256
+ model,
257
+ promptTokens,
258
+ tokenCountFromCounts(completionCounts),
259
+ );
260
+ await write("data: [DONE]\n\n");
261
+ }
262
+
263
+ async function writeOpenAIChatInterrupted(
264
+ write: SSEWrite,
265
+ cfg: RuntimeConfig,
266
+ rm: ResolvedCompletionModel,
267
+ issue: StreamIssue,
268
+ ): Promise<void> {
269
+ const warning = `\n\n${streamInterruptedWarningText(issue.error)}`;
270
+ log(
271
+ cfg,
272
+ `openai chat stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(issue.error) || "stream_interrupted"} error=${errorLogSummary(issue.error)}`,
273
+ );
274
+ await writeStreamWarningEvent(write, issue.error, warning.trim());
275
+ }
276
+
277
+ function openAIStreamToolCallInput(toolCall: OpenAIToolCall): {
278
+ name: unknown;
279
+ input: unknown;
280
+ } {
281
+ return {
282
+ name: toolCall.function.name,
283
+ input: parseJsonObject(toolCall.function.arguments),
284
+ };
285
+ }
src/http/openai/responses-stream.ts CHANGED
@@ -1,339 +1,340 @@
1
- import type { CompletionProvider } from "../../completion";
2
- import {
3
- createCompletionStreamLifecycle,
4
- EMPTY_UPSTREAM_MSG,
5
- recordCompletionStreamEvent,
6
- streamPlainCompletionEvents,
7
- streamToolSieveCompletionEvents,
8
- } from "../../completion";
9
- import type { FileRef } from "../../completion/types";
10
- import type { RuntimeConfig } from "../../config";
11
- import type { ResolvedModel } from "../../models";
12
- import { randHex } from "../../shared/crypto";
13
- import {
14
- errorLogSummary,
15
- upstreamErrorCode,
16
- upstreamErrorMessage,
17
- } from "../../shared/errors";
18
- import { log } from "../../shared/logging";
19
- import { tokenCountFromCounts } from "../../shared/tokens";
20
- import type { ToolChoicePolicy } from "../../toolcall/policy-openai";
21
- import type { SSEWrite } from "../core/sse";
22
- import {
23
- streamInterruptedWarningText,
24
- streamWarningObject,
25
- } from "../core/stream-errors";
26
- import { createDeltaCoalescer } from "../stream/coalescer";
27
- import { isPromiseLike } from "../stream/promise";
28
-
29
- type ResponseOutputItem = Record<string, unknown> & {
30
- id?: string;
31
- status?: string;
32
- content?: unknown;
33
- arguments?: string;
34
- call_id?: string;
35
- name?: string;
36
- };
37
- type StreamResponsesParams = {
38
- provider: CompletionProvider;
39
- rid: string;
40
- rm: Extract<ResolvedModel, { name: string }>;
41
- prompt: string;
42
- fileRefs: FileRef[] | null;
43
- tools: unknown;
44
- toolPolicy: ToolChoicePolicy | null | undefined;
45
- promptTokens: unknown;
46
- signal: AbortSignal;
47
- };
48
-
49
- export async function writeResponsesEvent(
50
- write: SSEWrite,
51
- event: string,
52
- payload: Record<string, unknown> | null | undefined,
53
- ): Promise<void> {
54
- const result = write(
55
- `event: ${event}\ndata: ${JSON.stringify({ type: event, ...(payload || {}) })}\n\n`,
56
- );
57
- if (isPromiseLike(result)) await result;
58
- }
59
-
60
- export async function streamResponsesWithToolSieve(
61
- write: SSEWrite,
62
- cfg: RuntimeConfig,
63
- params: StreamResponsesParams,
64
- ) {
65
- const {
66
- provider,
67
- rid,
68
- rm,
69
- prompt,
70
- fileRefs,
71
- tools,
72
- toolPolicy,
73
- promptTokens,
74
- signal,
75
- } = params;
76
- const output: ResponseOutputItem[] = [];
77
- const mid = `msg_${randHex(12)}`;
78
- const textParts: string[] = [];
79
- let messageStarted = false;
80
- let contentStarted = false;
81
- let outputIndex = 0;
82
- const textDeltaCoalescer = createDeltaCoalescer(
83
- (delta) => {
84
- const piece = delta.output_text || "";
85
- return writeResponsesEvent(write, "response.output_text.delta", {
86
- item_id: mid,
87
- output_index: outputIndex,
88
- content_index: 0,
89
- delta: piece,
90
- });
91
- },
92
- undefined,
93
- undefined,
94
- { emitFirstImmediately: true },
95
- );
96
-
97
- const fail = async (message: unknown, code: unknown) => {
98
- await writeResponsesEvent(write, "response.failed", {
99
- response: {
100
- id: rid,
101
- object: "response",
102
- status: "failed",
103
- model: rm.name,
104
- output,
105
- error: { message, code: code || "upstream_error" },
106
- },
107
- });
108
- };
109
- const startMessage = async () => {
110
- if (!messageStarted) {
111
- messageStarted = true;
112
- const item: ResponseOutputItem = {
113
- type: "message",
114
- id: mid,
115
- role: "assistant",
116
- status: "in_progress",
117
- content: [],
118
- };
119
- output.push(item);
120
- await writeResponsesEvent(write, "response.output_item.added", {
121
- output_index: outputIndex,
122
- item,
123
- });
124
- }
125
- if (!contentStarted) {
126
- contentStarted = true;
127
- await writeResponsesEvent(write, "response.content_part.added", {
128
- item_id: mid,
129
- output_index: outputIndex,
130
- content_index: 0,
131
- part: { type: "output_text", text: "", annotations: [] },
132
- });
133
- }
134
- };
135
- const emitText = async (piece: unknown) => {
136
- if (!piece) return;
137
- const textPiece = String(piece);
138
- await startMessage();
139
- textParts.push(textPiece);
140
- const appended = textDeltaCoalescer.append("output_text", textPiece);
141
- if (appended) await appended;
142
- };
143
- const finishMessage = async () => {
144
- if (!messageStarted) return;
145
- const flushed = textDeltaCoalescer.flush();
146
- if (flushed) await flushed;
147
- const item = output.find((it) => it.id === mid);
148
- const text =
149
- textParts.length === 1 ? textParts[0] || "" : textParts.join("");
150
- const part = { type: "output_text", text, annotations: [] };
151
- if (item) {
152
- item.status = "completed";
153
- item.content = [part];
154
- }
155
- if (contentStarted) {
156
- await writeResponsesEvent(write, "response.output_text.done", {
157
- item_id: mid,
158
- content_index: 0,
159
- text,
160
- });
161
- await writeResponsesEvent(write, "response.content_part.done", {
162
- item_id: mid,
163
- output_index: outputIndex,
164
- content_index: 0,
165
- part,
166
- });
167
- }
168
- await writeResponsesEvent(write, "response.output_item.done", {
169
- output_index: outputIndex,
170
- item,
171
- });
172
- outputIndex += 1;
173
- };
174
-
175
- await writeResponsesEvent(write, "response.created", {
176
- response: {
177
- id: rid,
178
- object: "response",
179
- status: "in_progress",
180
- model: rm.name,
181
- output: [],
182
- },
183
- });
184
- await writeResponsesEvent(write, "response.in_progress", {
185
- response: {
186
- id: rid,
187
- object: "response",
188
- status: "in_progress",
189
- model: rm.name,
190
- output: [],
191
- },
192
- });
193
- const lifecycle = createCompletionStreamLifecycle();
194
- if (tools) {
195
- for await (const event of streamToolSieveCompletionEvents(
196
- provider,
197
- { prompt, rm, fileRefs, tools, toolPolicy },
198
- { signal, coalesceTextDeltas: true },
199
- )) {
200
- recordCompletionStreamEvent(lifecycle, event);
201
- if (event.type === "text_delta") {
202
- await emitText(event.text);
203
- }
204
- }
205
- if (lifecycle.issue) {
206
- if (!lifecycle.emittedText && !lifecycle.toolCalls) {
207
- log(
208
- cfg,
209
- `openai responses stream failed before output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "upstream_error"} error=${errorLogSummary(lifecycle.issue.error)}`,
210
- );
211
- await fail(
212
- `upstream error: ${upstreamErrorMessage(lifecycle.issue.error)}`,
213
- upstreamErrorCode(lifecycle.issue.error) || "upstream_error",
214
- );
215
- return;
216
- }
217
- const warning = `\n\n${streamInterruptedWarningText(lifecycle.issue.error)}`;
218
- log(
219
- cfg,
220
- `openai responses stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(lifecycle.issue.error)}`,
221
- );
222
- await writeResponsesEvent(write, "response.warning", {
223
- warning: streamWarningObject(lifecycle.issue.error, warning.trim()),
224
- });
225
- }
226
- if (lifecycle.violation) {
227
- log(
228
- cfg,
229
- `openai responses stream tool policy violation model=${rm.name} code=${lifecycle.violation.code}`,
230
- );
231
- await fail(lifecycle.violation.message, lifecycle.violation.code);
232
- return;
233
- }
234
- } else {
235
- for await (const event of streamPlainCompletionEvents(
236
- provider,
237
- { prompt, rm, fileRefs },
238
- { signal, coalesceTextDeltas: true },
239
- )) {
240
- recordCompletionStreamEvent(lifecycle, event);
241
- if (event.type === "text_delta") {
242
- await emitText(event.text);
243
- }
244
- }
245
- if (lifecycle.issue) {
246
- if (!lifecycle.emittedText) {
247
- log(
248
- cfg,
249
- `openai responses stream failed before output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "upstream_error"} error=${errorLogSummary(lifecycle.issue.error)}`,
250
- );
251
- await fail(
252
- `upstream error: ${upstreamErrorMessage(lifecycle.issue.error)}`,
253
- upstreamErrorCode(lifecycle.issue.error) || "upstream_error",
254
- );
255
- return;
256
- }
257
- const warning = `\n\n${streamInterruptedWarningText(lifecycle.issue.error)}`;
258
- log(
259
- cfg,
260
- `openai responses stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(lifecycle.issue.error)}`,
261
- );
262
- await writeResponsesEvent(write, "response.warning", {
263
- warning: streamWarningObject(lifecycle.issue.error, warning.trim()),
264
- });
265
- }
266
- }
267
- if (!lifecycle.emittedText && !lifecycle.toolCalls) {
268
- log(cfg, `openai responses stream produced no content model=${rm.name}`);
269
- await fail(EMPTY_UPSTREAM_MSG, "upstream_empty");
270
- return;
271
- }
272
- await finishMessage();
273
-
274
- if (lifecycle.toolCalls?.length) {
275
- for (const tc of lifecycle.toolCalls) {
276
- const args = tc.function.arguments || "";
277
- const id = tc.id || "";
278
- const item: ResponseOutputItem = {
279
- type: "function_call",
280
- id,
281
- call_id: id,
282
- name: String(tc.function.name || ""),
283
- arguments: "",
284
- status: "in_progress",
285
- };
286
- output.push(item);
287
- await writeResponsesEvent(write, "response.output_item.added", {
288
- output_index: outputIndex,
289
- item,
290
- });
291
- if (args)
292
- await writeResponsesEvent(
293
- write,
294
- "response.function_call_arguments.delta",
295
- {
296
- item_id: item.id,
297
- output_index: outputIndex,
298
- call_id: item.call_id,
299
- delta: args,
300
- },
301
- );
302
- item.arguments = args;
303
- item.status = "completed";
304
- await writeResponsesEvent(
305
- write,
306
- "response.function_call_arguments.done",
307
- {
308
- item_id: item.id,
309
- call_id: item.call_id,
310
- name: item.name,
311
- arguments: item.arguments,
312
- },
313
- );
314
- await writeResponsesEvent(write, "response.output_item.done", {
315
- output_index: outputIndex,
316
- item,
317
- });
318
- outputIndex += 1;
319
- }
320
- }
321
-
322
- const inputTokens = Math.max(0, Number(promptTokens) || 0);
323
- const outputTokens = tokenCountFromCounts(lifecycle.completionCounts);
324
- const usage = {
325
- input_tokens: inputTokens,
326
- output_tokens: outputTokens,
327
- total_tokens: inputTokens + outputTokens,
328
- };
329
- await writeResponsesEvent(write, "response.completed", {
330
- response: {
331
- id: rid,
332
- object: "response",
333
- status: "completed",
334
- model: rm.name,
335
- output,
336
- usage,
337
- },
338
- });
339
- }
 
 
1
+ import type { CompletionProvider } from "../../completion";
2
+ import {
3
+ createCompletionStreamLifecycle,
4
+ EMPTY_UPSTREAM_MSG,
5
+ recordCompletionStreamEvent,
6
+ streamPlainCompletionEvents,
7
+ streamToolSieveCompletionEvents,
8
+ } from "../../completion";
9
+ import type { FileRef } from "../../completion/types";
10
+ import type { RuntimeConfig } from "../../config";
11
+ import type { ResolvedModel } from "../../models";
12
+ import { randHex } from "../../shared/crypto";
13
+ import {
14
+ errorLogSummary,
15
+ upstreamErrorCode,
16
+ upstreamErrorMessage,
17
+ } from "../../shared/errors";
18
+ import { log } from "../../shared/logging";
19
+ import { tokenCountFromCounts } from "../../shared/tokens";
20
+ import type { ToolChoicePolicy } from "../../toolcall/policy-openai";
21
+ import type { SSEWrite } from "../core/sse";
22
+ import {
23
+ streamInterruptedWarningText,
24
+ streamWarningObject,
25
+ } from "../core/stream-errors";
26
+ import { createDeltaCoalescer } from "../stream/coalescer";
27
+ import { isPromiseLike } from "../stream/promise";
28
+
29
+ type ResponseOutputItem = Record<string, unknown> & {
30
+ id?: string;
31
+ status?: string;
32
+ content?: unknown;
33
+ arguments?: string;
34
+ call_id?: string;
35
+ name?: string;
36
+ };
37
+ type StreamResponsesParams = {
38
+ provider: CompletionProvider;
39
+ rid: string;
40
+ rm: Extract<ResolvedModel, { name: string }>;
41
+ prompt: string;
42
+ fileRefs: FileRef[] | null;
43
+ tools: unknown;
44
+ toolPolicy: ToolChoicePolicy | null | undefined;
45
+ promptTokens: unknown;
46
+ signal: AbortSignal;
47
+ };
48
+
49
+ export async function writeResponsesEvent(
50
+ write: SSEWrite,
51
+ event: string,
52
+ payload: Record<string, unknown> | null | undefined,
53
+ ): Promise<void> {
54
+ const result = write(
55
+ `event: ${event}\ndata: ${JSON.stringify({ type: event, ...(payload || {}) })}\n\n`,
56
+ );
57
+ if (isPromiseLike(result)) await result;
58
+ }
59
+
60
+ export async function streamResponsesWithToolSieve(
61
+ write: SSEWrite,
62
+ cfg: RuntimeConfig,
63
+ params: StreamResponsesParams,
64
+ ) {
65
+ const {
66
+ provider,
67
+ rid,
68
+ rm,
69
+ prompt,
70
+ fileRefs,
71
+ tools,
72
+ toolPolicy,
73
+ promptTokens,
74
+ signal,
75
+ } = params;
76
+ const output: ResponseOutputItem[] = [];
77
+ const mid = `msg_${randHex(12)}`;
78
+ const textParts: string[] = [];
79
+ let messageStarted = false;
80
+ let contentStarted = false;
81
+ let outputIndex = 0;
82
+ const resinSmooth = !!cfg.resin_proxy;
83
+ const textDeltaCoalescer = createDeltaCoalescer(
84
+ (delta) => {
85
+ const piece = delta.output_text || "";
86
+ return writeResponsesEvent(write, "response.output_text.delta", {
87
+ item_id: mid,
88
+ output_index: outputIndex,
89
+ content_index: 0,
90
+ delta: piece,
91
+ });
92
+ },
93
+ resinSmooth ? 1 : undefined,
94
+ resinSmooth ? 0 : undefined,
95
+ { emitFirstImmediately: true },
96
+ );
97
+
98
+ const fail = async (message: unknown, code: unknown) => {
99
+ await writeResponsesEvent(write, "response.failed", {
100
+ response: {
101
+ id: rid,
102
+ object: "response",
103
+ status: "failed",
104
+ model: rm.name,
105
+ output,
106
+ error: { message, code: code || "upstream_error" },
107
+ },
108
+ });
109
+ };
110
+ const startMessage = async () => {
111
+ if (!messageStarted) {
112
+ messageStarted = true;
113
+ const item: ResponseOutputItem = {
114
+ type: "message",
115
+ id: mid,
116
+ role: "assistant",
117
+ status: "in_progress",
118
+ content: [],
119
+ };
120
+ output.push(item);
121
+ await writeResponsesEvent(write, "response.output_item.added", {
122
+ output_index: outputIndex,
123
+ item,
124
+ });
125
+ }
126
+ if (!contentStarted) {
127
+ contentStarted = true;
128
+ await writeResponsesEvent(write, "response.content_part.added", {
129
+ item_id: mid,
130
+ output_index: outputIndex,
131
+ content_index: 0,
132
+ part: { type: "output_text", text: "", annotations: [] },
133
+ });
134
+ }
135
+ };
136
+ const emitText = async (piece: unknown) => {
137
+ if (!piece) return;
138
+ const textPiece = String(piece);
139
+ await startMessage();
140
+ textParts.push(textPiece);
141
+ const appended = textDeltaCoalescer.append("output_text", textPiece);
142
+ if (appended) await appended;
143
+ };
144
+ const finishMessage = async () => {
145
+ if (!messageStarted) return;
146
+ const flushed = textDeltaCoalescer.flush();
147
+ if (flushed) await flushed;
148
+ const item = output.find((it) => it.id === mid);
149
+ const text =
150
+ textParts.length === 1 ? textParts[0] || "" : textParts.join("");
151
+ const part = { type: "output_text", text, annotations: [] };
152
+ if (item) {
153
+ item.status = "completed";
154
+ item.content = [part];
155
+ }
156
+ if (contentStarted) {
157
+ await writeResponsesEvent(write, "response.output_text.done", {
158
+ item_id: mid,
159
+ content_index: 0,
160
+ text,
161
+ });
162
+ await writeResponsesEvent(write, "response.content_part.done", {
163
+ item_id: mid,
164
+ output_index: outputIndex,
165
+ content_index: 0,
166
+ part,
167
+ });
168
+ }
169
+ await writeResponsesEvent(write, "response.output_item.done", {
170
+ output_index: outputIndex,
171
+ item,
172
+ });
173
+ outputIndex += 1;
174
+ };
175
+
176
+ await writeResponsesEvent(write, "response.created", {
177
+ response: {
178
+ id: rid,
179
+ object: "response",
180
+ status: "in_progress",
181
+ model: rm.name,
182
+ output: [],
183
+ },
184
+ });
185
+ await writeResponsesEvent(write, "response.in_progress", {
186
+ response: {
187
+ id: rid,
188
+ object: "response",
189
+ status: "in_progress",
190
+ model: rm.name,
191
+ output: [],
192
+ },
193
+ });
194
+ const lifecycle = createCompletionStreamLifecycle();
195
+ if (tools) {
196
+ for await (const event of streamToolSieveCompletionEvents(
197
+ provider,
198
+ { prompt, rm, fileRefs, tools, toolPolicy },
199
+ { signal, coalesceTextDeltas: !resinSmooth },
200
+ )) {
201
+ recordCompletionStreamEvent(lifecycle, event);
202
+ if (event.type === "text_delta") {
203
+ await emitText(event.text);
204
+ }
205
+ }
206
+ if (lifecycle.issue) {
207
+ if (!lifecycle.emittedText && !lifecycle.toolCalls) {
208
+ log(
209
+ cfg,
210
+ `openai responses stream failed before output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "upstream_error"} error=${errorLogSummary(lifecycle.issue.error)}`,
211
+ );
212
+ await fail(
213
+ `upstream error: ${upstreamErrorMessage(lifecycle.issue.error)}`,
214
+ upstreamErrorCode(lifecycle.issue.error) || "upstream_error",
215
+ );
216
+ return;
217
+ }
218
+ const warning = `\n\n${streamInterruptedWarningText(lifecycle.issue.error)}`;
219
+ log(
220
+ cfg,
221
+ `openai responses stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(lifecycle.issue.error)}`,
222
+ );
223
+ await writeResponsesEvent(write, "response.warning", {
224
+ warning: streamWarningObject(lifecycle.issue.error, warning.trim()),
225
+ });
226
+ }
227
+ if (lifecycle.violation) {
228
+ log(
229
+ cfg,
230
+ `openai responses stream tool policy violation model=${rm.name} code=${lifecycle.violation.code}`,
231
+ );
232
+ await fail(lifecycle.violation.message, lifecycle.violation.code);
233
+ return;
234
+ }
235
+ } else {
236
+ for await (const event of streamPlainCompletionEvents(
237
+ provider,
238
+ { prompt, rm, fileRefs },
239
+ { signal, coalesceTextDeltas: !resinSmooth },
240
+ )) {
241
+ recordCompletionStreamEvent(lifecycle, event);
242
+ if (event.type === "text_delta") {
243
+ await emitText(event.text);
244
+ }
245
+ }
246
+ if (lifecycle.issue) {
247
+ if (!lifecycle.emittedText) {
248
+ log(
249
+ cfg,
250
+ `openai responses stream failed before output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "upstream_error"} error=${errorLogSummary(lifecycle.issue.error)}`,
251
+ );
252
+ await fail(
253
+ `upstream error: ${upstreamErrorMessage(lifecycle.issue.error)}`,
254
+ upstreamErrorCode(lifecycle.issue.error) || "upstream_error",
255
+ );
256
+ return;
257
+ }
258
+ const warning = `\n\n${streamInterruptedWarningText(lifecycle.issue.error)}`;
259
+ log(
260
+ cfg,
261
+ `openai responses stream interrupted after partial output model=${rm.name} code=${upstreamErrorCode(lifecycle.issue.error) || "stream_interrupted"} error=${errorLogSummary(lifecycle.issue.error)}`,
262
+ );
263
+ await writeResponsesEvent(write, "response.warning", {
264
+ warning: streamWarningObject(lifecycle.issue.error, warning.trim()),
265
+ });
266
+ }
267
+ }
268
+ if (!lifecycle.emittedText && !lifecycle.toolCalls) {
269
+ log(cfg, `openai responses stream produced no content model=${rm.name}`);
270
+ await fail(EMPTY_UPSTREAM_MSG, "upstream_empty");
271
+ return;
272
+ }
273
+ await finishMessage();
274
+
275
+ if (lifecycle.toolCalls?.length) {
276
+ for (const tc of lifecycle.toolCalls) {
277
+ const args = tc.function.arguments || "";
278
+ const id = tc.id || "";
279
+ const item: ResponseOutputItem = {
280
+ type: "function_call",
281
+ id,
282
+ call_id: id,
283
+ name: String(tc.function.name || ""),
284
+ arguments: "",
285
+ status: "in_progress",
286
+ };
287
+ output.push(item);
288
+ await writeResponsesEvent(write, "response.output_item.added", {
289
+ output_index: outputIndex,
290
+ item,
291
+ });
292
+ if (args)
293
+ await writeResponsesEvent(
294
+ write,
295
+ "response.function_call_arguments.delta",
296
+ {
297
+ item_id: item.id,
298
+ output_index: outputIndex,
299
+ call_id: item.call_id,
300
+ delta: args,
301
+ },
302
+ );
303
+ item.arguments = args;
304
+ item.status = "completed";
305
+ await writeResponsesEvent(
306
+ write,
307
+ "response.function_call_arguments.done",
308
+ {
309
+ item_id: item.id,
310
+ call_id: item.call_id,
311
+ name: item.name,
312
+ arguments: item.arguments,
313
+ },
314
+ );
315
+ await writeResponsesEvent(write, "response.output_item.done", {
316
+ output_index: outputIndex,
317
+ item,
318
+ });
319
+ outputIndex += 1;
320
+ }
321
+ }
322
+
323
+ const inputTokens = Math.max(0, Number(promptTokens) || 0);
324
+ const outputTokens = tokenCountFromCounts(lifecycle.completionCounts);
325
+ const usage = {
326
+ input_tokens: inputTokens,
327
+ output_tokens: outputTokens,
328
+ total_tokens: inputTokens + outputTokens,
329
+ };
330
+ await writeResponsesEvent(write, "response.completed", {
331
+ response: {
332
+ id: rid,
333
+ object: "response",
334
+ status: "completed",
335
+ model: rm.name,
336
+ output,
337
+ usage,
338
+ },
339
+ });
340
+ }