llm-api-purity-check 0.0.0-stage → 1.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/src/client.mjs ADDED
@@ -0,0 +1,1240 @@
1
+ /**
2
+ * Zero-dependency LLM API client supporting:
3
+ * - openai-chat (/v1/chat/completions)
4
+ * - openai-responses (/v1/responses)
5
+ * - anthropic (/v1/messages)
6
+ *
7
+ * Captures real streaming TTFT, chunk cadence, fake-stream heuristics,
8
+ * thinking/reasoning content & full cryptographic signatures, reasoning_tokens,
9
+ * 16-channel safe whitelisted upstream signature classification, HTTP 400 parameter
10
+ * auto-downgrade retry, multimodal image inputs, structured error classification,
11
+ * secret redaction, and /v1/responses echo fields.
12
+ */
13
+
14
+ import {
15
+ inferCanonicalBankFamily,
16
+ inferCanonicalVendorFamily,
17
+ normalizeModelSlug,
18
+ } from './modelIdNormalize.mjs';
19
+
20
+ export { normalizeModelSlug, inferCanonicalBankFamily, inferCanonicalVendorFamily };
21
+
22
+ export const CHANNEL_TAXONOMY = [
23
+ 'cf_ai_gateway',
24
+ 'openrouter',
25
+ 'litellm',
26
+ 'new_api',
27
+ 'one_api',
28
+ 'aws_bedrock',
29
+ 'gcp_vertex',
30
+ 'azure_openai',
31
+ 'anthropic_official',
32
+ 'openai_official',
33
+ 'deepseek_official',
34
+ 'dashscope',
35
+ 'volcengine_ark',
36
+ 'groq',
37
+ 'together_ai',
38
+ 'siliconflow',
39
+ ];
40
+
41
+ const SAFE_HEADER_EXACT = new Set([
42
+ // OpenAI official
43
+ 'openai-processing-ms',
44
+ 'openai-organization',
45
+ 'openai-version',
46
+ 'openai-project',
47
+ 'x-openai-client-user-agent',
48
+ 'x-ratelimit-limit-requests',
49
+ 'x-ratelimit-remaining-requests',
50
+ 'x-ratelimit-limit-tokens',
51
+ // Anthropic official
52
+ 'anthropic-organization-id',
53
+ 'anthropic-ratelimit-requests-limit',
54
+ 'anthropic-ratelimit-tokens-limit',
55
+ 'anthropic-version',
56
+ 'request-id',
57
+ // AWS Bedrock
58
+ 'x-amzn-requestid',
59
+ 'x-amzn-errortype',
60
+ 'x-amz-apigw-id',
61
+ // Google Vertex AI / Gemini
62
+ 'x-goog-api-client',
63
+ 'x-goog-request-params',
64
+ 'x-cloud-trace-context',
65
+ // OpenRouter
66
+ 'openrouter-processing-ms',
67
+ // Cloudflare / CF AI Gateway
68
+ 'cf-ray',
69
+ 'cf-mitigated',
70
+ // One-API / New-API / Veloera
71
+ 'x-oneapi-request-id',
72
+ 'x-one-api-request-id',
73
+ 'x-newapi-request-id',
74
+ 'x-new-api-request-id',
75
+ 'new-api-request-id',
76
+ 'x-veloera-request-id',
77
+ 'x-relay-request-id',
78
+ // Azure OpenAI
79
+ 'apim-request-id',
80
+ 'x-ms-region',
81
+ 'x-ms-client-request-id',
82
+ 'x-ms-rai-invoked',
83
+ 'azureml-model-session',
84
+ // DeepSeek official
85
+ 'x-ds-trace-id',
86
+ 'x-deepseek-trace-id',
87
+ 'x-bs-request-id',
88
+ // Alibaba DashScope
89
+ 'x-dashscope-request-id',
90
+ 'x-dashscope-call-id',
91
+ 'x-acs-request-id',
92
+ // Volcengine Ark
93
+ 'x-tt-logid',
94
+ 'x-tos-request-id',
95
+ 'x-top-request-id',
96
+ // Groq
97
+ 'x-groq-id',
98
+ // Together AI
99
+ 'x-together-request-id',
100
+ 'x-together-version',
101
+ // SiliconFlow
102
+ 'x-siliconcloud-trace-id',
103
+ 'x-sf-trace-id',
104
+ // Generic diagnostic
105
+ 'server',
106
+ 'via',
107
+ 'x-request-id',
108
+ 'x-trace-id',
109
+ 'x-powered-by',
110
+ 'x-upstream-provider',
111
+ 'x-provider',
112
+ ]);
113
+
114
+ const SAFE_HEADER_PREFIXES = [
115
+ 'cf-aig-',
116
+ 'x-litellm-',
117
+ 'x-openrouter-',
118
+ 'x-amzn-bedrock-',
119
+ 'x-oneapi-',
120
+ 'x-one-api-',
121
+ 'x-newapi-',
122
+ 'x-new-api-',
123
+ 'x-dashscope-',
124
+ 'x-ark-',
125
+ 'x-groq-',
126
+ 'x-together-',
127
+ 'x-siliconflow-',
128
+ 'openai-',
129
+ 'anthropic-',
130
+ ];
131
+
132
+ const SENSITIVE_HEADER_RE =
133
+ /(?:^|[-_])(?:auth|authorization|api[-_]?key|access[-_]?token|refresh[-_]?token|id[-_]?token|secret|cookie|set[-_]?cookie|credential|password|private[-_]?key)/i;
134
+
135
+ export function inferProtocol(model, explicitProtocol) {
136
+ if (explicitProtocol) {
137
+ const p = explicitProtocol.trim().toLowerCase();
138
+ if (['openai-chat', 'openai_chat', 'chat'].includes(p)) return 'openai-chat';
139
+ if (['openai-responses', 'openai_responses', 'responses'].includes(p)) return 'openai-responses';
140
+ if (['anthropic', 'anthropic-messages', 'anthropic_messages', 'claude'].includes(p)) return 'anthropic';
141
+ throw new Error(`Unsupported --protocol "${explicitProtocol}". Use: openai-chat | openai-responses | anthropic`);
142
+ }
143
+ const norm = normalizeModelSlug(model);
144
+ if (/^(?:claude|opus|sonnet|haiku|fable)(?:-|$)/.test(norm) || /claude|opus|sonnet|haiku|fable/.test(norm)) {
145
+ return 'anthropic';
146
+ }
147
+ return 'openai-chat';
148
+ }
149
+
150
+ export function isModernOpenAiReasoningModel(model) {
151
+ const m = normalizeModelSlug(model);
152
+ if (!m) return false;
153
+ if (/chat/.test(m)) return false;
154
+ return /^(?:gpt-[56](?:-|$)|o[134](?:-|$)|codex)/.test(m);
155
+ }
156
+
157
+ export function isReasoningCapableModel(model) {
158
+ const raw = String(model || '').trim().toLowerCase();
159
+ const m = normalizeModelSlug(model);
160
+ if (!m) return false;
161
+ if (isModernOpenAiReasoningModel(m)) return true;
162
+ if (/(?:^|[:\-_])(?:thinking|reasoner)(?:$|[:\-_])/.test(raw)) return true;
163
+ return /^(?:deepseek-(?:r1|v[34]|reasoner)|gemini-(?:2-5|[34])|claude-(?:opus|sonnet|fable)-[45]|qwen-?[34]|kimi-k[23]|glm-[45])/.test(
164
+ m
165
+ );
166
+ }
167
+
168
+ export function buildEndpointUrl(baseUrl, protocol) {
169
+ const clean = String(baseUrl || '').trim().replace(/\/+$/, '');
170
+ if (!clean) throw new Error('Missing --base-url');
171
+ if (protocol === 'anthropic') {
172
+ if (clean.endsWith('/v1/messages')) return clean;
173
+ if (clean.endsWith('/v1')) return `${clean}/messages`;
174
+ return `${clean}/v1/messages`;
175
+ }
176
+ if (protocol === 'openai-responses') {
177
+ if (clean.endsWith('/v1/responses')) return clean;
178
+ if (clean.endsWith('/v1')) return `${clean}/responses`;
179
+ return `${clean}/v1/responses`;
180
+ }
181
+ if (clean.endsWith('/v1/chat/completions')) return clean;
182
+ if (clean.endsWith('/v1')) return `${clean}/chat/completions`;
183
+ return `${clean}/v1/chat/completions`;
184
+ }
185
+
186
+ function buildHeaders(apiKey, protocol) {
187
+ if (protocol === 'anthropic') {
188
+ return {
189
+ 'content-type': 'application/json',
190
+ 'x-api-key': apiKey,
191
+ 'anthropic-version': '2023-06-01',
192
+ };
193
+ }
194
+ return {
195
+ 'content-type': 'application/json',
196
+ authorization: `Bearer ${apiKey}`,
197
+ };
198
+ }
199
+
200
+ export function extractSafeResponseHeaders(headers) {
201
+ const safe = {};
202
+ if (!headers) return safe;
203
+ const entries = typeof headers.entries === 'function' ? headers.entries() : Object.entries(headers);
204
+ for (const [rawKey, rawVal] of entries) {
205
+ const key = String(rawKey || '').toLowerCase().trim();
206
+ if (!key) continue;
207
+ const isExact = SAFE_HEADER_EXACT.has(key);
208
+ if (!isExact) {
209
+ if (SENSITIVE_HEADER_RE.test(key)) continue;
210
+ if (!SAFE_HEADER_PREFIXES.some((prefix) => key.startsWith(prefix))) continue;
211
+ }
212
+ const val = String(rawVal ?? '').trim();
213
+ if (val) safe[key] = val.slice(0, 120);
214
+ }
215
+ return safe;
216
+ }
217
+
218
+ /**
219
+ * 16-channel zero-extra-request upstream channel signature classifier.
220
+ * Purely informational evidence — `unknown` NEVER deducts score or triggers warn/fail.
221
+ */
222
+ export function classifyChannelSignature({
223
+ headers = {},
224
+ responseId = null,
225
+ responseModel = null,
226
+ systemFingerprint = null,
227
+ } = {}) {
228
+ const h = {};
229
+ for (const [k, v] of Object.entries(headers || {})) {
230
+ h[String(k).toLowerCase()] = String(v);
231
+ }
232
+ const keys = Object.keys(h);
233
+ const hasPrefix = (p) => keys.some((k) => k.startsWith(p));
234
+ const idStr = String(responseId || '');
235
+ const modelStr = String(responseModel || '');
236
+ const fpStr = String(systemFingerprint || '');
237
+ const serverStr = (h.server || '').toLowerCase();
238
+ const poweredBy = (h['x-powered-by'] || '').toLowerCase();
239
+ const signals = [];
240
+
241
+ const collect = (list) => {
242
+ for (const k of list) {
243
+ if (h[k]) signals.push(`${k}=${h[k].slice(0, 40)}`);
244
+ }
245
+ };
246
+
247
+ // 1. Cloudflare AI Gateway
248
+ if (hasPrefix('cf-aig-')) {
249
+ collect(keys.filter((k) => k.startsWith('cf-aig-')));
250
+ return { channel: 'cf_ai_gateway', label: 'Cloudflare AI Gateway', confidence: 'high', signals };
251
+ }
252
+
253
+ // 2. LiteLLM Proxy
254
+ if (hasPrefix('x-litellm-')) {
255
+ collect(keys.filter((k) => k.startsWith('x-litellm-')));
256
+ return { channel: 'litellm', label: 'LiteLLM Proxy', confidence: 'high', signals };
257
+ }
258
+
259
+ // 3. OpenRouter
260
+ if (
261
+ hasPrefix('x-openrouter-') ||
262
+ h['openrouter-processing-ms'] ||
263
+ (idStr.startsWith('gen-') && (h['x-provider'] || h['x-upstream-provider'] || serverStr.includes('cloudflare')))
264
+ ) {
265
+ collect(keys.filter((k) => k.startsWith('x-openrouter-') || k === 'openrouter-processing-ms'));
266
+ if (idStr.startsWith('gen-')) signals.push('id=gen-*');
267
+ return {
268
+ channel: 'openrouter',
269
+ label: 'OpenRouter',
270
+ confidence: hasPrefix('x-openrouter-') || h['openrouter-processing-ms'] ? 'high' : 'medium',
271
+ signals,
272
+ };
273
+ }
274
+
275
+ // 4. New-API / Veloera
276
+ if (
277
+ hasPrefix('x-newapi-') ||
278
+ hasPrefix('x-new-api-') ||
279
+ h['new-api-request-id'] ||
280
+ h['x-veloera-request-id'] ||
281
+ /new-?api|veloera/i.test(poweredBy)
282
+ ) {
283
+ collect([
284
+ 'x-newapi-request-id',
285
+ 'x-new-api-request-id',
286
+ 'new-api-request-id',
287
+ 'x-veloera-request-id',
288
+ 'x-powered-by',
289
+ ]);
290
+ return { channel: 'new_api', label: 'New-API', confidence: 'high', signals };
291
+ }
292
+
293
+ // 5. One-API
294
+ if (
295
+ hasPrefix('x-oneapi-') ||
296
+ hasPrefix('x-one-api-') ||
297
+ h['x-relay-request-id'] ||
298
+ /one-?api/i.test(poweredBy)
299
+ ) {
300
+ collect(['x-oneapi-request-id', 'x-one-api-request-id', 'x-relay-request-id', 'x-powered-by']);
301
+ return { channel: 'one_api', label: 'One-API', confidence: 'high', signals };
302
+ }
303
+
304
+ // 6. AWS Bedrock
305
+ if (
306
+ hasPrefix('x-amzn-bedrock-') ||
307
+ h['x-amzn-requestid'] ||
308
+ h['x-amz-apigw-id'] ||
309
+ /^arn:aws:bedrock:/i.test(modelStr) ||
310
+ /^(?:us|eu|ap|global)\.anthropic\..+-v\d+:\d+$/i.test(modelStr)
311
+ ) {
312
+ collect(['x-amzn-requestid', 'x-amz-apigw-id', ...keys.filter((k) => k.startsWith('x-amzn-bedrock-'))]);
313
+ if (/^arn:aws:bedrock:/i.test(modelStr) || /-v\d+:\d+$/i.test(modelStr)) {
314
+ signals.push(`model=${modelStr.slice(0, 48)}`);
315
+ }
316
+ return { channel: 'aws_bedrock', label: 'AWS Bedrock', confidence: 'high', signals };
317
+ }
318
+
319
+ // 7. Google Vertex AI
320
+ if (
321
+ h['x-goog-api-client'] ||
322
+ h['x-goog-request-params'] ||
323
+ h['x-cloud-trace-context'] ||
324
+ /\b(?:scaffolding|esf|gse)\b/i.test(serverStr)
325
+ ) {
326
+ collect(['x-goog-api-client', 'x-goog-request-params', 'x-cloud-trace-context', 'server']);
327
+ return {
328
+ channel: 'gcp_vertex',
329
+ label: 'Google Vertex AI',
330
+ confidence: h['x-goog-api-client'] || h['x-goog-request-params'] ? 'high' : 'medium',
331
+ signals,
332
+ };
333
+ }
334
+
335
+ // 8. Azure OpenAI
336
+ if (
337
+ h['apim-request-id'] ||
338
+ h['x-ms-region'] ||
339
+ h['azureml-model-session'] ||
340
+ h['x-ms-client-request-id'] ||
341
+ h['x-ms-rai-invoked']
342
+ ) {
343
+ collect(['apim-request-id', 'x-ms-region', 'azureml-model-session', 'x-ms-client-request-id', 'x-ms-rai-invoked']);
344
+ return { channel: 'azure_openai', label: 'Azure OpenAI', confidence: 'high', signals };
345
+ }
346
+
347
+ // 9. Alibaba DashScope
348
+ if (
349
+ hasPrefix('x-dashscope-') ||
350
+ h['x-acs-request-id'] ||
351
+ (/dashscope/i.test(serverStr) && Boolean(h['x-request-id']))
352
+ ) {
353
+ collect([...keys.filter((k) => k.startsWith('x-dashscope-')), 'x-acs-request-id', 'server']);
354
+ return { channel: 'dashscope', label: 'Alibaba DashScope', confidence: 'high', signals };
355
+ }
356
+
357
+ // 10. Volcengine Ark
358
+ if (hasPrefix('x-ark-') || h['x-tt-logid'] || h['x-tos-request-id'] || h['x-top-request-id']) {
359
+ collect([...keys.filter((k) => k.startsWith('x-ark-')), 'x-tt-logid', 'x-tos-request-id', 'x-top-request-id']);
360
+ return { channel: 'volcengine_ark', label: 'Volcengine Ark', confidence: 'high', signals };
361
+ }
362
+
363
+ // 11. Groq
364
+ if (hasPrefix('x-groq-') || serverStr.includes('groq')) {
365
+ collect([...keys.filter((k) => k.startsWith('x-groq-')), 'server']);
366
+ return { channel: 'groq', label: 'Groq', confidence: 'high', signals };
367
+ }
368
+
369
+ // 12. Together AI
370
+ if (hasPrefix('x-together-') || serverStr.includes('together')) {
371
+ collect([...keys.filter((k) => k.startsWith('x-together-')), 'server']);
372
+ return { channel: 'together_ai', label: 'Together AI', confidence: 'high', signals };
373
+ }
374
+
375
+ // 13. SiliconFlow
376
+ if (hasPrefix('x-siliconflow-') || h['x-siliconcloud-trace-id'] || h['x-sf-trace-id']) {
377
+ collect([
378
+ ...keys.filter((k) => k.startsWith('x-siliconflow-')),
379
+ 'x-siliconcloud-trace-id',
380
+ 'x-sf-trace-id',
381
+ ]);
382
+ return { channel: 'siliconflow', label: 'SiliconFlow', confidence: 'high', signals };
383
+ }
384
+
385
+ // 14. DeepSeek Official
386
+ if (
387
+ h['x-ds-trace-id'] ||
388
+ h['x-deepseek-trace-id'] ||
389
+ (h['x-bs-request-id'] && /deepseek/i.test(modelStr))
390
+ ) {
391
+ collect(['x-ds-trace-id', 'x-deepseek-trace-id', 'x-bs-request-id']);
392
+ return { channel: 'deepseek_official', label: 'DeepSeek Official', confidence: 'high', signals };
393
+ }
394
+
395
+ // 15. Anthropic Official
396
+ if (
397
+ h['anthropic-organization-id'] ||
398
+ h['anthropic-ratelimit-requests-limit'] ||
399
+ h['anthropic-ratelimit-tokens-limit'] ||
400
+ (h['request-id'] && /^req_/i.test(h['request-id']) && /^msg_/i.test(idStr))
401
+ ) {
402
+ collect([
403
+ 'anthropic-organization-id',
404
+ 'anthropic-ratelimit-requests-limit',
405
+ 'anthropic-ratelimit-tokens-limit',
406
+ 'request-id',
407
+ ]);
408
+ return {
409
+ channel: 'anthropic_official',
410
+ label: 'Anthropic Official',
411
+ confidence: h['anthropic-organization-id'] || h['anthropic-ratelimit-requests-limit'] ? 'high' : 'medium',
412
+ signals,
413
+ };
414
+ }
415
+
416
+ // 16. OpenAI Official
417
+ if (
418
+ h['openai-processing-ms'] ||
419
+ h['openai-organization'] ||
420
+ h['openai-project'] ||
421
+ h['openai-version']
422
+ ) {
423
+ collect(['openai-processing-ms', 'openai-organization', 'openai-project', 'openai-version']);
424
+ if (fpStr) signals.push(`fp=${fpStr.slice(0, 24)}`);
425
+ return { channel: 'openai_official', label: 'OpenAI Official', confidence: 'high', signals };
426
+ }
427
+
428
+ if (h['x-upstream-provider'] || h['x-provider']) {
429
+ collect(['x-upstream-provider', 'x-provider']);
430
+ const prov = h['x-upstream-provider'] || h['x-provider'];
431
+ return { channel: 'custom_provider', label: prov, confidence: 'medium', signals };
432
+ }
433
+
434
+ return { channel: 'unknown', label: 'Unknown / Generic Relay', confidence: 'none', signals: [] };
435
+ }
436
+
437
+ export function detectUpstreamChannel(input = {}) {
438
+ return classifyChannelSignature(input);
439
+ }
440
+
441
+ export function classifyHttpError(httpStatus, bodyText = '', headers = {}) {
442
+ const status = Number(httpStatus) || 0;
443
+ const lower = String(bodyText || '').toLowerCase();
444
+ const h = {};
445
+ for (const [k, v] of Object.entries(headers || {})) {
446
+ h[String(k).toLowerCase()] = String(v).toLowerCase();
447
+ }
448
+
449
+ const looksLikeWaf =
450
+ h['cf-mitigated'] === 'challenge' ||
451
+ lower.includes('just a moment...') ||
452
+ lower.includes('attention required! | cloudflare') ||
453
+ lower.includes('enable javascript and cookies to continue') ||
454
+ lower.includes('cf-browser-verification') ||
455
+ lower.includes('ddos-guard') ||
456
+ lower.includes('sucuri website firewall') ||
457
+ ((status === 403 || status === 503 || status === 405) &&
458
+ (lower.includes('<!doctype html') || lower.includes('<html')) &&
459
+ (lower.includes('cloudflare') || lower.includes('captcha') || lower.includes('access denied') || lower.includes('waf')));
460
+
461
+ if (looksLikeWaf) {
462
+ return {
463
+ errorKind: 'waf_blocked',
464
+ hint: 'Blocked by WAF / Cloudflare challenge (not a model fraud verdict). Check IP/User-Agent or test from an allowed network.',
465
+ };
466
+ }
467
+
468
+ const looksLikeQuota =
469
+ status === 402 ||
470
+ /insufficient_quota|quota_exceeded|insufficient[_\s-]*balance|billing_hard_limit|credit balance is too low|withholding|余额不足|额度不足|额度已用尽/.test(
471
+ lower
472
+ );
473
+ if (looksLikeQuota) {
474
+ return {
475
+ errorKind: 'quota_exhausted',
476
+ hint: 'API key balance or quota is exhausted. Top up or use a funded temporary test key.',
477
+ };
478
+ }
479
+
480
+ const looksLikeAuth =
481
+ status === 401 ||
482
+ /invalid_api_key|incorrect api key|invalid x-api-key|authentication_error|invalid[_\s-]*token|unauthorized|missing api key|invalid auth|密钥无效|令牌无效/.test(
483
+ lower
484
+ );
485
+ if (looksLikeAuth) {
486
+ return {
487
+ errorKind: 'auth_error',
488
+ hint: 'Authentication failed (HTTP 401/403). Verify --api-key and whether the key has permission for this protocol.',
489
+ };
490
+ }
491
+
492
+ const looksLikeModelNotFound =
493
+ status === 404 ||
494
+ /model[_\s-]*not[_\s-]*found|model.*does not exist|no available channel|unknown model|unsupported model|invalid model|无可用渠道|模型不存在/.test(
495
+ lower
496
+ );
497
+ if (looksLikeModelNotFound) {
498
+ return {
499
+ errorKind: 'model_not_found',
500
+ hint: 'Model or endpoint path was not found (404 / no available channel). Verify --model name and --protocol.',
501
+ };
502
+ }
503
+
504
+ if (status === 429 || status === 529 || /rate[_\s-]*limit|too many requests|overloaded_error|server_is_overloaded/.test(lower)) {
505
+ return {
506
+ errorKind: 'rate_limited',
507
+ hint: 'Upstream rate limit or overload (HTTP 429/529). Retry later or lower concurrency.',
508
+ };
509
+ }
510
+
511
+ if (status === 400 || status === 422) {
512
+ return {
513
+ errorKind: 'bad_request',
514
+ hint: 'Request rejected as invalid parameter (HTTP 400/422). Verify --protocol matches the endpoint.',
515
+ };
516
+ }
517
+
518
+ if (status >= 500) {
519
+ return {
520
+ errorKind: 'server_error',
521
+ hint: `Upstream gateway returned HTTP ${status}.`,
522
+ };
523
+ }
524
+
525
+ return {
526
+ errorKind: 'http_error',
527
+ hint: `Upstream returned HTTP ${status}.`,
528
+ };
529
+ }
530
+
531
+ export function buildPayload({
532
+ protocol,
533
+ model,
534
+ system,
535
+ userPrompt,
536
+ messages: customMessages,
537
+ imageBase64,
538
+ imageMediaType = 'image/png',
539
+ thinking,
540
+ stream,
541
+ maxTokens,
542
+ temperature,
543
+ enableAnthropicCacheControl,
544
+ tools,
545
+ }) {
546
+ if (protocol === 'anthropic') {
547
+ const msgs =
548
+ Array.isArray(customMessages) && customMessages.length > 0
549
+ ? customMessages
550
+ : [
551
+ {
552
+ role: 'user',
553
+ content: imageBase64
554
+ ? [
555
+ {
556
+ type: 'image',
557
+ source: { type: 'base64', media_type: imageMediaType, data: imageBase64 },
558
+ },
559
+ { type: 'text', text: userPrompt },
560
+ ]
561
+ : userPrompt,
562
+ },
563
+ ];
564
+ const body = {
565
+ model,
566
+ max_tokens: maxTokens,
567
+ stream: Boolean(stream),
568
+ messages: msgs,
569
+ };
570
+ const thinkingEnabled = Boolean(thinking && typeof thinking === 'object');
571
+ if (thinkingEnabled) body.thinking = thinking;
572
+ if (typeof temperature === 'number' && !thinkingEnabled) body.temperature = temperature;
573
+ if (system) {
574
+ body.system = enableAnthropicCacheControl
575
+ ? [{ type: 'text', text: system, cache_control: { type: 'ephemeral' } }]
576
+ : system;
577
+ }
578
+ if (tools && tools.length > 0) body.tools = tools;
579
+ return body;
580
+ }
581
+
582
+ if (protocol === 'openai-responses') {
583
+ const isGptReasoning = isModernOpenAiReasoningModel(model);
584
+ const input =
585
+ Array.isArray(customMessages) && customMessages.length > 0
586
+ ? customMessages
587
+ : imageBase64
588
+ ? [
589
+ {
590
+ role: 'user',
591
+ content: [
592
+ { type: 'input_text', text: userPrompt },
593
+ { type: 'input_image', image_url: `data:${imageMediaType};base64,${imageBase64}` },
594
+ ],
595
+ },
596
+ ]
597
+ : userPrompt;
598
+ const body = {
599
+ model,
600
+ input,
601
+ max_output_tokens: Math.max(16, Number(maxTokens) || 16),
602
+ stream: Boolean(stream),
603
+ };
604
+ if (system) body.instructions = system;
605
+ if (typeof temperature === 'number' && !isGptReasoning) body.temperature = temperature;
606
+ if (tools && tools.length > 0) body.tools = tools;
607
+ return body;
608
+ }
609
+
610
+ const isGptModern = isModernOpenAiReasoningModel(model);
611
+ const omitTemperature = isGptModern || /deepseek[-_.\s]?(?:r1|reasoner)|reasoner/i.test(String(model || ''));
612
+ const messages = [];
613
+ if (system) messages.push({ role: 'system', content: system });
614
+ if (Array.isArray(customMessages) && customMessages.length > 0) {
615
+ messages.push(...customMessages);
616
+ } else if (imageBase64) {
617
+ messages.push({
618
+ role: 'user',
619
+ content: [
620
+ { type: 'text', text: userPrompt },
621
+ { type: 'image_url', image_url: { url: `data:${imageMediaType};base64,${imageBase64}` } },
622
+ ],
623
+ });
624
+ } else {
625
+ messages.push({ role: 'user', content: userPrompt });
626
+ }
627
+ const body = {
628
+ model,
629
+ messages,
630
+ ...(isGptModern ? { max_completion_tokens: maxTokens } : { max_tokens: maxTokens }),
631
+ stream: Boolean(stream),
632
+ };
633
+ if (stream) body.stream_options = { include_usage: true };
634
+ if (typeof temperature === 'number' && !omitTemperature) body.temperature = temperature;
635
+ if (tools && tools.length > 0) body.tools = tools;
636
+ return body;
637
+ }
638
+
639
+ export function buildCompat400Body(orig, errText = '', protocol = 'openai-chat') {
640
+ const err = String(errText || '');
641
+ const looksLikeParamErr =
642
+ /unsupported|unrecognized|unknown|invalid_request|invalid.*param|extra_forbidden|not allowed|not supported|max_tokens|max_completion_tokens|max_output_tokens|stream_options|reasoning_effort|reasoning|thinking|temperature|top_p|must be <=|must be >=|exceeds.*max|at most|at least|too large|too small|below minimum|range|only.*default.*1/i.test(
643
+ err
644
+ ) &&
645
+ !/model.*not.*found|does not exist|no available channel|insufficient|quota|balance|invalid.*key|invalid.*token|unauthorized|permission|余额|额度|signature|(?:image|vision|multimodal).{0,32}not.*support/i.test(
646
+ err
647
+ );
648
+ if (!looksLikeParamErr) return null;
649
+
650
+ const next = { ...orig };
651
+ const mentionsUpperLimit = /must be <=|exceeds|at most|too large/i.test(err);
652
+ const mentionsLowerLimit = /must be >=|at least|below minimum|too small/i.test(err);
653
+
654
+ if (protocol === 'openai-chat') {
655
+ if ('stream_options' in next && /stream_options|include_usage/i.test(err)) {
656
+ delete next.stream_options;
657
+ }
658
+ if ('temperature' in next && /temperature|only.*default.*1/i.test(err)) {
659
+ delete next.temperature;
660
+ }
661
+ if ('reasoning_effort' in next && /reasoning_effort/i.test(err)) {
662
+ delete next.reasoning_effort;
663
+ }
664
+
665
+ const rawVal = Number(next.max_completion_tokens ?? next.max_tokens ?? 1024);
666
+ let adjustedTokens = rawVal;
667
+ if (mentionsUpperLimit && adjustedTokens > 8192) adjustedTokens = 8192;
668
+ if (mentionsLowerLimit && adjustedTokens < 16) adjustedTokens = 16;
669
+
670
+ if ('max_completion_tokens' in next && /max_completion_tokens/i.test(err)) {
671
+ delete next.max_completion_tokens;
672
+ next.max_tokens = adjustedTokens;
673
+ } else if ('max_tokens' in next && (/max_tokens/i.test(err) || /max_completion_tokens/i.test(err))) {
674
+ delete next.max_tokens;
675
+ next.max_completion_tokens = adjustedTokens;
676
+ if ('temperature' in next) delete next.temperature;
677
+ } else if (adjustedTokens !== rawVal) {
678
+ if ('max_completion_tokens' in next) next.max_completion_tokens = adjustedTokens;
679
+ if ('max_tokens' in next) next.max_tokens = adjustedTokens;
680
+ }
681
+
682
+ // Generic fallback when upstream did not name a specific parameter:
683
+ // drop optional extras first (preserving token field), then swap token field if still unchanged
684
+ if (JSON.stringify(next) === JSON.stringify(orig)) {
685
+ if ('temperature' in next) delete next.temperature;
686
+ if ('reasoning_effort' in next) delete next.reasoning_effort;
687
+ if ('stream_options' in next) delete next.stream_options;
688
+ }
689
+ if (JSON.stringify(next) === JSON.stringify(orig)) {
690
+ if ('max_completion_tokens' in next) {
691
+ delete next.max_completion_tokens;
692
+ next.max_tokens = adjustedTokens;
693
+ } else if ('max_tokens' in next) {
694
+ delete next.max_tokens;
695
+ next.max_completion_tokens = adjustedTokens;
696
+ }
697
+ }
698
+ } else if (protocol === 'openai-responses') {
699
+ if ('temperature' in next) delete next.temperature;
700
+ if (/reasoning/i.test(err) && 'reasoning' in next) delete next.reasoning;
701
+ const rawVal = Number(next.max_output_tokens ?? 1024);
702
+ if (mentionsUpperLimit && rawVal > 8192) next.max_output_tokens = 8192;
703
+ else if (mentionsLowerLimit && rawVal < 16) next.max_output_tokens = 16;
704
+ } else if (protocol === 'anthropic') {
705
+ if ('temperature' in next && /temperature|thinking/i.test(err)) delete next.temperature;
706
+ if ('thinking' in next && /thinking|budget_tokens/i.test(err)) delete next.thinking;
707
+ const rawVal = Number(next.max_tokens ?? 1024);
708
+ if (mentionsUpperLimit && rawVal > 8192) next.max_tokens = 8192;
709
+ else if (mentionsLowerLimit && rawVal < 16) next.max_tokens = 16;
710
+ }
711
+
712
+ return JSON.stringify(next) !== JSON.stringify(orig) ? next : null;
713
+ }
714
+
715
+ export function normalizeUsage(rawUsage, protocol) {
716
+ if (!rawUsage || typeof rawUsage !== 'object') {
717
+ return {
718
+ inputTokens: null,
719
+ outputTokens: null,
720
+ cachedTokens: null,
721
+ cacheCreationTokens: null,
722
+ reasoningTokens: 0,
723
+ };
724
+ }
725
+ const reasoningTokensRaw =
726
+ rawUsage.completion_tokens_details?.reasoning_tokens ??
727
+ rawUsage.completion_tokens_details?.thinking_tokens ??
728
+ rawUsage.output_tokens_details?.reasoning_tokens ??
729
+ rawUsage.thoughts_token_count ??
730
+ rawUsage.thinking_tokens ??
731
+ 0;
732
+ const reasoningTokens = Number(reasoningTokensRaw || 0);
733
+
734
+ if (protocol === 'anthropic') {
735
+ const baseIn = Number(rawUsage.input_tokens ?? 0);
736
+ const cacheRead = rawUsage.cache_read_input_tokens != null ? Number(rawUsage.cache_read_input_tokens) : 0;
737
+ const cacheCreate =
738
+ rawUsage.cache_creation_input_tokens != null ? Number(rawUsage.cache_creation_input_tokens) : 0;
739
+ return {
740
+ inputTokens: baseIn + cacheRead + cacheCreate,
741
+ outputTokens: rawUsage.output_tokens != null ? Number(rawUsage.output_tokens) : null,
742
+ cachedTokens: cacheRead,
743
+ cacheCreationTokens: cacheCreate,
744
+ reasoningTokens,
745
+ };
746
+ }
747
+ const inputTokens = rawUsage.prompt_tokens ?? rawUsage.input_tokens ?? null;
748
+ const outputTokens = rawUsage.completion_tokens ?? rawUsage.output_tokens ?? null;
749
+ const cachedTokens =
750
+ rawUsage.prompt_tokens_details?.cached_tokens ??
751
+ rawUsage.input_tokens_details?.cached_tokens ??
752
+ rawUsage.prompt_cache_hit_tokens ??
753
+ rawUsage.cache_read_input_tokens ??
754
+ 0;
755
+ return {
756
+ inputTokens: inputTokens != null ? Number(inputTokens) : null,
757
+ outputTokens: outputTokens != null ? Number(outputTokens) : null,
758
+ cachedTokens: Number(cachedTokens || 0),
759
+ cacheCreationTokens:
760
+ rawUsage.cache_creation_input_tokens != null ? Number(rawUsage.cache_creation_input_tokens) : null,
761
+ reasoningTokens,
762
+ };
763
+ }
764
+
765
+ function parseJsonResponsePayload(data, protocol) {
766
+ let text = '';
767
+ let thinkingText = '';
768
+ let thinkingSignature = '';
769
+ let redactedThinking = false;
770
+ const responseModel = data.model || null;
771
+ const responseId = data.id || null;
772
+ const systemFingerprint = typeof data.system_fingerprint === 'string' ? data.system_fingerprint : null;
773
+ let echoInstructions = null;
774
+ let echoTools = null;
775
+
776
+ if (protocol === 'anthropic') {
777
+ const blocks = Array.isArray(data.content) ? data.content : [];
778
+ for (const b of blocks) {
779
+ if (b?.type === 'text' && typeof b.text === 'string') {
780
+ text += b.text;
781
+ } else if (b?.type === 'thinking') {
782
+ if (typeof b.thinking === 'string') thinkingText += b.thinking;
783
+ if (typeof b.signature === 'string' && b.signature.length > 0) thinkingSignature += b.signature;
784
+ } else if (b?.type === 'redacted_thinking') {
785
+ redactedThinking = true;
786
+ }
787
+ }
788
+ } else if (protocol === 'openai-responses') {
789
+ const hasDirectOutputText = typeof data.output_text === 'string' && data.output_text.length > 0;
790
+ if (hasDirectOutputText) {
791
+ text = data.output_text;
792
+ }
793
+ if (Array.isArray(data.output)) {
794
+ for (const item of data.output) {
795
+ if (!hasDirectOutputText && item?.type !== 'reasoning' && Array.isArray(item?.content)) {
796
+ for (const c of item.content) {
797
+ if ((c?.type === 'output_text' || c?.type === 'text') && typeof c.text === 'string') {
798
+ text += c.text;
799
+ }
800
+ }
801
+ }
802
+ if (item?.type === 'reasoning') {
803
+ if (Array.isArray(item.summary)) {
804
+ for (const s of item.summary) {
805
+ if (typeof s?.text === 'string') thinkingText += s.text;
806
+ }
807
+ }
808
+ if (Array.isArray(item.content)) {
809
+ for (const c of item.content) {
810
+ if (typeof c?.text === 'string') thinkingText += c.text;
811
+ }
812
+ }
813
+ if (typeof item.encrypted_content === 'string' && item.encrypted_content.length > 0) {
814
+ thinkingSignature = item.encrypted_content;
815
+ }
816
+ }
817
+ }
818
+ }
819
+ if (typeof data.instructions === 'string') echoInstructions = data.instructions;
820
+ if (Array.isArray(data.tools)) echoTools = data.tools;
821
+ } else {
822
+ const msg = data.choices?.[0]?.message;
823
+ if (msg) {
824
+ if (typeof msg.content === 'string') {
825
+ text = msg.content;
826
+ } else if (Array.isArray(msg.content)) {
827
+ for (const part of msg.content) {
828
+ if (typeof part === 'string') text += part;
829
+ else if (part?.type === 'thinking' || part?.type === 'reasoning') {
830
+ thinkingText += String(part.thinking || part.text || '');
831
+ } else if (typeof part?.text === 'string') {
832
+ text += part.text;
833
+ }
834
+ }
835
+ }
836
+ const reason = msg.reasoning_content || msg.reasoning || msg.thinking;
837
+ if (typeof reason === 'string' && reason) thinkingText += reason;
838
+ }
839
+ }
840
+
841
+ return {
842
+ text,
843
+ thinkingText,
844
+ thinkingChars: thinkingText.length,
845
+ thinkingSignature: thinkingSignature || null,
846
+ thinkingSigPresent: thinkingSignature.length >= 16 || redactedThinking,
847
+ redactedThinking,
848
+ responseModel,
849
+ responseId,
850
+ systemFingerprint,
851
+ echoInstructions,
852
+ echoTools,
853
+ usage: normalizeUsage(data.usage, protocol),
854
+ };
855
+ }
856
+
857
+ export function redactSecretsInText(text, apiKey = '') {
858
+ let out = String(text || '');
859
+ const key = String(apiKey || '').trim();
860
+ if (key.length >= 6) {
861
+ out = out.split(key).join('[REDACTED_KEY]');
862
+ }
863
+ out = out.replace(/\b(sk-[A-Za-z0-9_-]{6})[A-Za-z0-9_-]{4,}\b/g, '$1***');
864
+ out = out.replace(/(Bearer\s+)[A-Za-z0-9._-]{8,}/gi, '$1[REDACTED]');
865
+ return out;
866
+ }
867
+
868
+ function createStructuredHttpError(status, url, errBody, safeHeaders, apiKey = '') {
869
+ const classified = classifyHttpError(status, errBody, safeHeaders);
870
+ const channel = classifyChannelSignature({ headers: safeHeaders });
871
+ const sanitizedSnippet = redactSecretsInText(errBody, apiKey).slice(0, 300);
872
+ const err = new Error(`HTTP ${status} [${classified.errorKind}] from ${url}: ${sanitizedSnippet}`);
873
+ err.httpStatus = status;
874
+ err.errorKind = classified.errorKind;
875
+ err.hint = classified.hint;
876
+ err.responseHeaders = safeHeaders;
877
+ err.upstreamChannel = channel;
878
+ return err;
879
+ }
880
+
881
+ export async function callLlm({
882
+ baseUrl,
883
+ apiKey,
884
+ protocol,
885
+ model,
886
+ system = '',
887
+ userPrompt = '',
888
+ messages,
889
+ imageBase64,
890
+ imageMediaType = 'image/png',
891
+ thinking,
892
+ stream = false,
893
+ maxTokens = 1024,
894
+ temperature,
895
+ enableAnthropicCacheControl = false,
896
+ tools,
897
+ extraHeaders,
898
+ disableCompatRetry = false,
899
+ timeoutMs = 90000,
900
+ }) {
901
+ const url = buildEndpointUrl(baseUrl, protocol);
902
+ const headers = {
903
+ ...buildHeaders(apiKey, protocol),
904
+ ...(extraHeaders && typeof extraHeaders === 'object' ? extraHeaders : {}),
905
+ };
906
+ let payload = buildPayload({
907
+ protocol,
908
+ model,
909
+ system,
910
+ userPrompt,
911
+ messages,
912
+ imageBase64,
913
+ imageMediaType,
914
+ thinking,
915
+ stream,
916
+ maxTokens,
917
+ temperature,
918
+ enableAnthropicCacheControl,
919
+ tools,
920
+ });
921
+
922
+ const controller = new AbortController();
923
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
924
+ const startedAt = performance.now();
925
+
926
+ try {
927
+ let compatRetried = false;
928
+ const triedBodies = new Set([JSON.stringify(payload)]);
929
+ let resp = await fetch(url, {
930
+ method: 'POST',
931
+ headers,
932
+ body: JSON.stringify(payload),
933
+ signal: controller.signal,
934
+ });
935
+
936
+ // Up to 2 automatic HTTP 400 parameter-compatibility retries unless disabled (e.g. signature tamper check)
937
+ if (!disableCompatRetry) {
938
+ for (let attempt = 0; attempt < 2 && resp.status === 400; attempt += 1) {
939
+ const errBody = await resp.text().catch(() => '');
940
+ const nextPayload = buildCompat400Body(payload, errBody, protocol);
941
+ const nextSerialized = nextPayload ? JSON.stringify(nextPayload) : null;
942
+ if (!nextPayload || triedBodies.has(nextSerialized)) {
943
+ throw createStructuredHttpError(resp.status, url, errBody, extractSafeResponseHeaders(resp.headers), apiKey);
944
+ }
945
+ triedBodies.add(nextSerialized);
946
+ payload = nextPayload;
947
+ compatRetried = true;
948
+ resp = await fetch(url, {
949
+ method: 'POST',
950
+ headers,
951
+ body: nextSerialized,
952
+ signal: controller.signal,
953
+ });
954
+ }
955
+ }
956
+
957
+ const safeHeaders = extractSafeResponseHeaders(resp.headers);
958
+
959
+ if (!resp.ok) {
960
+ const errBody = await resp.text().catch(() => '');
961
+ throw createStructuredHttpError(resp.status, url, errBody, safeHeaders, apiKey);
962
+ }
963
+
964
+ if (!stream) {
965
+ const data = await resp.json();
966
+ const totalMs = Math.round(performance.now() - startedAt);
967
+ const parsed = parseJsonResponsePayload(data, protocol);
968
+ const upstreamChannel = classifyChannelSignature({
969
+ headers: safeHeaders,
970
+ responseId: parsed.responseId,
971
+ responseModel: parsed.responseModel,
972
+ systemFingerprint: parsed.systemFingerprint,
973
+ });
974
+
975
+ return {
976
+ ok: true,
977
+ text: parsed.text,
978
+ thinkingText: parsed.thinkingText,
979
+ thinkingChars: parsed.thinkingChars,
980
+ thinkingSignature: parsed.thinkingSignature,
981
+ thinkingSigPresent: parsed.thinkingSigPresent,
982
+ redactedThinking: parsed.redactedThinking,
983
+ totalMs,
984
+ ttftMs: totalMs,
985
+ chunkCount: 1,
986
+ fakeStreamSuspect: false,
987
+ responseModel: parsed.responseModel,
988
+ responseId: parsed.responseId,
989
+ systemFingerprint: parsed.systemFingerprint,
990
+ usage: parsed.usage,
991
+ echoInstructions: parsed.echoInstructions,
992
+ echoTools: parsed.echoTools,
993
+ responseHeaders: safeHeaders,
994
+ upstreamChannel,
995
+ compatRetried,
996
+ };
997
+ }
998
+
999
+ // Streaming SSE parser (with non-SSE JSON fallback)
1000
+ if (!resp.body || typeof resp.body.getReader !== 'function') {
1001
+ throw createStructuredHttpError(resp.status, url, 'Empty streaming response body', safeHeaders, apiKey);
1002
+ }
1003
+ const reader = resp.body.getReader();
1004
+ const decoder = new TextDecoder('utf-8');
1005
+ let buffer = '';
1006
+ let rawFallback = '';
1007
+ let sawSseData = false;
1008
+ let text = '';
1009
+ let thinkingText = '';
1010
+ let thinkingSignature = '';
1011
+ let redactedThinking = false;
1012
+ let firstTokenAt = null;
1013
+ let chunkCount = 0;
1014
+ let visibleChunkCount = 0;
1015
+ let maxChunkChars = 0;
1016
+ let responseModel = null;
1017
+ let responseId = null;
1018
+ let systemFingerprint = null;
1019
+ let rawUsage = null;
1020
+ let echoInstructions = null;
1021
+ let echoTools = null;
1022
+
1023
+ const processLine = (line) => {
1024
+ const trimmed = line.trim();
1025
+ if (!trimmed.startsWith('data:')) return;
1026
+ sawSseData = true;
1027
+ const dataStr = trimmed.slice(5).trim();
1028
+ if (!dataStr || dataStr === '[DONE]') return;
1029
+ let evt;
1030
+ try {
1031
+ evt = JSON.parse(dataStr);
1032
+ } catch {
1033
+ return;
1034
+ }
1035
+
1036
+ if (evt.model && !responseModel) responseModel = evt.model;
1037
+ if (evt.id && !responseId) responseId = evt.id;
1038
+ if (typeof evt.system_fingerprint === 'string' && !systemFingerprint) {
1039
+ systemFingerprint = evt.system_fingerprint;
1040
+ }
1041
+
1042
+ if (protocol === 'anthropic') {
1043
+ if (evt.type === 'message_start' && evt.message) {
1044
+ if (evt.message.model) responseModel = evt.message.model;
1045
+ if (evt.message.id) responseId = evt.message.id;
1046
+ if (evt.message.usage) rawUsage = { ...(rawUsage || {}), ...evt.message.usage };
1047
+ }
1048
+ if (evt.type === 'content_block_start') {
1049
+ if (evt.content_block?.type === 'redacted_thinking') {
1050
+ redactedThinking = true;
1051
+ if (firstTokenAt === null) firstTokenAt = performance.now();
1052
+ } else if (
1053
+ evt.content_block?.type === 'thinking' &&
1054
+ typeof evt.content_block.signature === 'string' &&
1055
+ evt.content_block.signature.length > 0
1056
+ ) {
1057
+ thinkingSignature += evt.content_block.signature;
1058
+ }
1059
+ }
1060
+ if (evt.type === 'content_block_delta') {
1061
+ if (evt.delta?.type === 'text_delta' && evt.delta.text) {
1062
+ const delta = evt.delta.text;
1063
+ if (firstTokenAt === null) firstTokenAt = performance.now();
1064
+ chunkCount += 1;
1065
+ visibleChunkCount += 1;
1066
+ if (delta.length > maxChunkChars) maxChunkChars = delta.length;
1067
+ text += delta;
1068
+ } else if (evt.delta?.type === 'thinking_delta' && evt.delta.thinking) {
1069
+ if (firstTokenAt === null) firstTokenAt = performance.now();
1070
+ chunkCount += 1;
1071
+ thinkingText += evt.delta.thinking;
1072
+ } else if (evt.delta?.type === 'signature_delta' && typeof evt.delta.signature === 'string') {
1073
+ thinkingSignature += evt.delta.signature;
1074
+ }
1075
+ }
1076
+ if (evt.type === 'message_delta' && evt.usage) {
1077
+ rawUsage = { ...(rawUsage || {}), ...evt.usage };
1078
+ }
1079
+ } else if (protocol === 'openai-responses') {
1080
+ if (evt.response) {
1081
+ if (evt.response.model) responseModel = evt.response.model;
1082
+ if (evt.response.id) responseId = evt.response.id;
1083
+ if (typeof evt.response.instructions === 'string') echoInstructions = evt.response.instructions;
1084
+ if (Array.isArray(evt.response.tools)) echoTools = evt.response.tools;
1085
+ if (evt.response.usage) rawUsage = evt.response.usage;
1086
+ if (evt.type === 'response.completed') {
1087
+ const completedParsed = parseJsonResponsePayload(evt.response, 'openai-responses');
1088
+ if (!text && completedParsed.text) text = completedParsed.text;
1089
+ if (!thinkingText && completedParsed.thinkingText) thinkingText = completedParsed.thinkingText;
1090
+ if (completedParsed.thinkingSignature && !thinkingSignature) {
1091
+ thinkingSignature = completedParsed.thinkingSignature;
1092
+ } else if (completedParsed.thinkingSigPresent && !thinkingSignature) {
1093
+ thinkingSignature = 'encrypted_reasoning_present';
1094
+ }
1095
+ }
1096
+ }
1097
+ if (evt.type === 'response.output_text.delta' && typeof evt.delta === 'string' && evt.delta) {
1098
+ if (firstTokenAt === null) firstTokenAt = performance.now();
1099
+ chunkCount += 1;
1100
+ visibleChunkCount += 1;
1101
+ if (evt.delta.length > maxChunkChars) maxChunkChars = evt.delta.length;
1102
+ text += evt.delta;
1103
+ } else if (
1104
+ (evt.type === 'response.reasoning_summary_text.delta' || evt.type === 'response.reasoning_text.delta') &&
1105
+ typeof evt.delta === 'string' &&
1106
+ evt.delta
1107
+ ) {
1108
+ if (firstTokenAt === null) firstTokenAt = performance.now();
1109
+ chunkCount += 1;
1110
+ thinkingText += evt.delta;
1111
+ }
1112
+ } else {
1113
+ const deltaObj = evt.choices?.[0]?.delta;
1114
+ if (deltaObj) {
1115
+ const content = deltaObj.content;
1116
+ if (typeof content === 'string' && content.length > 0) {
1117
+ if (firstTokenAt === null) firstTokenAt = performance.now();
1118
+ chunkCount += 1;
1119
+ visibleChunkCount += 1;
1120
+ if (content.length > maxChunkChars) maxChunkChars = content.length;
1121
+ text += content;
1122
+ } else if (Array.isArray(content)) {
1123
+ for (const part of content) {
1124
+ if (part && typeof part === 'object' && (part.type === 'thinking' || part.type === 'reasoning')) {
1125
+ const rTxt = String(part.thinking || part.text || '');
1126
+ if (rTxt.length > 0) {
1127
+ if (firstTokenAt === null) firstTokenAt = performance.now();
1128
+ chunkCount += 1;
1129
+ thinkingText += rTxt;
1130
+ }
1131
+ } else {
1132
+ const txt = typeof part === 'string' ? part : part?.text;
1133
+ if (typeof txt === 'string' && txt.length > 0) {
1134
+ if (firstTokenAt === null) firstTokenAt = performance.now();
1135
+ chunkCount += 1;
1136
+ visibleChunkCount += 1;
1137
+ if (txt.length > maxChunkChars) maxChunkChars = txt.length;
1138
+ text += txt;
1139
+ }
1140
+ }
1141
+ }
1142
+ }
1143
+ const deltaReason = deltaObj.reasoning_content || deltaObj.reasoning || deltaObj.thinking;
1144
+ if (typeof deltaReason === 'string' && deltaReason.length > 0) {
1145
+ if (firstTokenAt === null) firstTokenAt = performance.now();
1146
+ chunkCount += 1;
1147
+ thinkingText += deltaReason;
1148
+ }
1149
+ }
1150
+ if (evt.usage) rawUsage = evt.usage;
1151
+ }
1152
+ };
1153
+
1154
+ while (true) {
1155
+ const { value, done } = await reader.read();
1156
+ if (done) {
1157
+ const tail = decoder.decode();
1158
+ if (!sawSseData && rawFallback.length < 262144 && tail) rawFallback += tail;
1159
+ buffer += tail;
1160
+ if (buffer.trim()) processLine(buffer);
1161
+ break;
1162
+ }
1163
+ const decoded = decoder.decode(value, { stream: true });
1164
+ if (!sawSseData && rawFallback.length < 262144) rawFallback += decoded;
1165
+ buffer += decoded;
1166
+ const lines = buffer.split(/\r?\n/);
1167
+ buffer = lines.pop() || '';
1168
+ for (const line of lines) processLine(line);
1169
+ }
1170
+
1171
+ let usage = normalizeUsage(rawUsage, protocol);
1172
+ let thinkingSigPresent = thinkingSignature.length >= 16 || redactedThinking;
1173
+
1174
+ // Fallback when an upstream proxy ignores stream=true and returns a single JSON response body
1175
+ if (!sawSseData && !text && !thinkingText && rawFallback.trim().startsWith('{')) {
1176
+ try {
1177
+ const data = JSON.parse(rawFallback.trim());
1178
+ const parsed = parseJsonResponsePayload(data, protocol);
1179
+ text = parsed.text;
1180
+ thinkingText = parsed.thinkingText;
1181
+ thinkingSignature = parsed.thinkingSignature || thinkingSignature;
1182
+ thinkingSigPresent = parsed.thinkingSigPresent;
1183
+ redactedThinking = parsed.redactedThinking;
1184
+ responseModel = parsed.responseModel || responseModel;
1185
+ responseId = parsed.responseId || responseId;
1186
+ systemFingerprint = parsed.systemFingerprint || systemFingerprint;
1187
+ echoInstructions = parsed.echoInstructions ?? echoInstructions;
1188
+ echoTools = parsed.echoTools ?? echoTools;
1189
+ usage = parsed.usage;
1190
+ if (text || thinkingText) {
1191
+ chunkCount = 1;
1192
+ visibleChunkCount = text ? 1 : 0;
1193
+ maxChunkChars = text.length;
1194
+ }
1195
+ } catch {
1196
+ // Ignore unparseable fallback
1197
+ }
1198
+ }
1199
+
1200
+ const totalMs = Math.round(performance.now() - startedAt);
1201
+ const ttftMs = firstTokenAt !== null ? Math.round(firstTokenAt - startedAt) : totalMs;
1202
+ const decodeMs = Math.max(1, totalMs - ttftMs);
1203
+ const fakeStreamSuspect =
1204
+ text.length >= 160 &&
1205
+ (visibleChunkCount <= 2 || (maxChunkChars / text.length >= 0.85 && decodeMs < 120));
1206
+
1207
+ const upstreamChannel = classifyChannelSignature({
1208
+ headers: safeHeaders,
1209
+ responseId,
1210
+ responseModel,
1211
+ systemFingerprint,
1212
+ });
1213
+
1214
+ return {
1215
+ ok: true,
1216
+ text,
1217
+ thinkingText,
1218
+ thinkingChars: thinkingText.length,
1219
+ thinkingSignature: thinkingSignature || null,
1220
+ thinkingSigPresent,
1221
+ redactedThinking,
1222
+ totalMs,
1223
+ ttftMs,
1224
+ decodeMs,
1225
+ chunkCount,
1226
+ fakeStreamSuspect,
1227
+ responseModel,
1228
+ responseId,
1229
+ systemFingerprint,
1230
+ usage,
1231
+ echoInstructions,
1232
+ echoTools,
1233
+ responseHeaders: safeHeaders,
1234
+ upstreamChannel,
1235
+ compatRetried,
1236
+ };
1237
+ } finally {
1238
+ clearTimeout(timer);
1239
+ }
1240
+ }