File size: 42,639 Bytes
c7d34c1
b1cfe1b
 
4588c8c
b1cfe1b
 
 
 
4588c8c
 
 
 
 
c7d34c1
 
 
 
4588c8c
 
 
c7d34c1
 
e445b51
c7d34c1
4588c8c
c7d34c1
 
 
4588c8c
c7d34c1
 
 
 
 
 
6c12d18
 
c7d34c1
 
 
 
6c12d18
 
c7d34c1
3e8ea5d
 
 
 
 
 
b1cfe1b
4588c8c
 
 
b1cfe1b
 
 
 
3e8ea5d
 
e445b51
3e8ea5d
e445b51
 
 
 
3e8ea5d
b1cfe1b
c7d34c1
 
 
b1cfe1b
e445b51
c7d34c1
 
 
e445b51
 
 
 
 
 
 
f9a28cd
e445b51
 
 
 
 
 
 
 
 
f9a28cd
 
 
96bdf6c
f9a28cd
 
 
 
 
 
96bdf6c
f9a28cd
 
e445b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11486ce
 
 
 
 
4588c8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e445b51
 
 
 
 
 
 
 
 
 
b1cfe1b
 
 
 
e445b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9a28cd
 
 
 
 
 
 
 
e445b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9a28cd
 
 
 
 
 
96bdf6c
f9a28cd
96bdf6c
 
f9a28cd
 
 
96bdf6c
f9a28cd
96bdf6c
 
f9a28cd
 
 
 
 
 
 
 
 
 
 
96bdf6c
f9a28cd
96bdf6c
 
 
 
f9a28cd
96bdf6c
 
 
f9a28cd
 
 
 
 
 
 
4588c8c
f9a28cd
96bdf6c
 
 
4588c8c
 
96bdf6c
 
 
 
 
 
 
 
f9a28cd
 
 
 
4588c8c
 
f9a28cd
 
96bdf6c
 
f9a28cd
 
 
 
 
 
 
 
4588c8c
 
f9a28cd
 
96bdf6c
 
f9a28cd
 
 
 
e445b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c12d18
11486ce
6c12d18
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c12d18
 
 
 
 
11486ce
 
 
 
 
 
 
 
 
 
 
 
6c12d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
96bdf6c
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d34c1
 
f9a28cd
11486ce
c7d34c1
 
 
 
e445b51
 
c7d34c1
 
 
 
 
 
 
 
 
81587dd
c7d34c1
 
 
e445b51
 
 
c7d34c1
e445b51
f9a28cd
 
 
4588c8c
 
 
 
 
f9a28cd
4588c8c
 
 
 
 
 
 
 
 
 
 
 
 
f9a28cd
 
 
 
 
96bdf6c
 
f9a28cd
 
 
 
4588c8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9a28cd
 
 
c7d34c1
 
 
a2c232b
11486ce
 
 
c7d34c1
 
 
 
 
a2c232b
c7d34c1
 
e445b51
c7d34c1
 
 
 
 
 
 
 
 
 
 
f9a28cd
 
 
96bdf6c
f9a28cd
c7d34c1
 
 
11486ce
 
 
 
a2c232b
11486ce
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
 
 
3e8ea5d
c7d34c1
 
 
32151b6
c7d34c1
32151b6
c7d34c1
 
 
 
32151b6
c7d34c1
32151b6
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4588c8c
e445b51
 
3e8ea5d
e445b51
 
 
 
 
 
f9a28cd
 
3e8ea5d
4588c8c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8ea5d
 
 
 
e445b51
 
 
11486ce
f9a28cd
96bdf6c
11486ce
 
3e8ea5d
c7d34c1
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
 
e445b51
c7d34c1
11486ce
 
c7d34c1
 
 
 
a2c232b
c7d34c1
81587dd
c7d34c1
 
 
81587dd
3e8ea5d
96bdf6c
e445b51
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
e445b51
c7d34c1
11486ce
 
e445b51
c7d34c1
 
 
a2c232b
c7d34c1
81587dd
c7d34c1
 
 
81587dd
3e8ea5d
96bdf6c
e445b51
 
 
 
 
 
 
 
 
 
c7d34c1
 
11486ce
 
 
 
c7d34c1
 
 
 
 
 
 
 
 
 
e445b51
704e84f
e445b51
 
a2c232b
11486ce
e445b51
c7d34c1
 
 
 
 
 
 
 
a2c232b
c7d34c1
 
 
 
 
 
 
 
 
 
 
11486ce
c7d34c1
 
 
11486ce
 
 
 
c7d34c1
 
6c12d18
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
6c12d18
c7d34c1
 
6c12d18
c7d34c1
 
6c12d18
 
 
 
 
b1cfe1b
6c12d18
b1cfe1b
 
11486ce
 
 
 
c7d34c1
 
11486ce
 
f9a28cd
6c12d18
c7d34c1
 
6c12d18
 
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
6c12d18
 
 
 
c7d34c1
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
import { appLogger } from '@/lib/app-logger';
import type { ChannelCapacityLease } from '@/lib/channel-capacity-queue';
import {
    getEffectiveChannelRequestModes,
    isStreamingChannelRequestMode,
    resolveChannelRequestMode,
    type ChannelRequestMode
} from '@/lib/channel-request-mode';
import {
    isChannelCredentialRequestModeHealthy,
    type ChannelCredential,
    resolveEffectiveCredential
} from '@/lib/channel-router';
import {
    RequestValidationError,
    assertSafeApiOverride,
    readCount,
    readBackground,
    readImageFiles,
    readMaskFile,
    readMode,
    readModel,
    readPlainHttpApiBaseUrlAllowlist,
    readRequiredText,
    readSize,
    readStorageMode,
    validateApiBaseUrl
} from '@/lib/image-request-utils';
import type { ImageMode } from '@/lib/image-request-utils';
import { handleEditImageMode, handleGenerateImageMode } from '@/lib/image-route-mode-handlers';
import {
    assertResponsesImageBackendAllowed,
    attachAccessCookie,
    describeInvalidImagesResponse,
    ensureOutputDirExists,
    inspectInvalidImagesResponse,
    inspectUpstreamError,
    readClientRequestId,
    reportServerCredentialFailure,
    resolveRequestActualCostSafely,
    type AccessCookie,
    type RequestLogContext,
    type UpstreamResponseDiagnostics
} from '@/lib/image-route-support';
import {
    InvalidOpenAiImagesResponseError,
    MissingOpenAiImageDataError,
    persistedImageToLegacyResponse,
    persistOpenAiImages
} from '@/lib/image-service';
import {
    clampIntegerToRange,
    getImageBackendCompatibility,
    isIntegerWithinRange,
    mergeUpstreamHeadersWithFixed,
    readImageUpstreamProfile,
    type PartialImagesCount
} from '@/lib/image-upstream-profile';
import {
    readImageGenerationBackend,
    readImageStreamMode,
    readImageStreamingStrategy,
    resolveImageStreamEnabled,
    type ImageGenerationBackend,
    type ImageStreamMode,
    type ImageStreamingStrategy
} from '@/lib/image-upstream-strategy';
import { createOpenAIImageClientOptions } from '@/lib/openai-image-transport';
import { PAGE_PASSWORD_AUTH_ERROR_CODES } from '@/lib/page-password-auth';
import { getServerChannelState } from '@/lib/server-channel-router';
import { buildAccessCookie, readAffinityKey, verifyPasswordHash } from '@/lib/server-runtime';
import type { StreamingAvailabilityKey, StreamingOperation } from '@/lib/streaming-availability';
import crypto from 'crypto';
import { NextRequest, NextResponse } from 'next/server';
import OpenAI from 'openai';

type StreamResolutionInput = {
    streamMode: ImageStreamMode;
    imageBackend: ImageGenerationBackend;
    streamingStrategy: ImageStreamingStrategy;
    operation: StreamingOperation;
    selectedCredential?: ChannelCredential;
    sourceId?: string;
    forceNonStream?: boolean;
};

type StreamResolution = {
    availabilityKey: StreamingAvailabilityKey;
    streamEnabled: boolean;
    streamFallbackEnabled: boolean;
    streamingMarkedUnavailable: boolean;
};

type ChannelRequestModePlan = {
    preferred: ChannelRequestMode;
    fallback?: ChannelRequestMode;
    candidates: readonly ChannelRequestMode[];
};

type PageChannelSelection = {
    selectedCredential?: ChannelCredential;
    requestMode: ChannelRequestMode;
    forcedNonStream: boolean;
    fallbackApplied: boolean;
};

function readErrorStatus(error: unknown): number | undefined {
    if (typeof error !== 'object' || error === null) return undefined;
    if ('status' in error && typeof error.status === 'number') return error.status;
    if ('statusCode' in error && typeof error.statusCode === 'number') return error.statusCode;
    return undefined;
}

function readErrorCode(error: unknown): string | undefined {
    if (typeof error !== 'object' || error === null) return undefined;
    if ('code' in error && typeof error.code === 'string') return error.code;
    if ('error' in error && typeof error.error === 'object' && error.error !== null) {
        const nested = error.error as Record<string, unknown>;
        return typeof nested.code === 'string' ? nested.code : undefined;
    }
    return undefined;
}

function toPartialImagesCount(value: number): PartialImagesCount {
    if (value === 0 || value === 1 || value === 2 || value === 3 || value === 4) return value;
    throw new RequestValidationError('partial_images 必须在 0 到 4 之间。');
}

function readOptionalPositiveCount(formData: FormData, field: string): number | undefined {
    const value = formData.get(field);
    if (value === null) return undefined;
    if (typeof value !== 'string' || !/^\d+$/.test(value)) {
        throw new RequestValidationError(`${field} 必须是整数。`);
    }
    const count = Number(value);
    if (!Number.isSafeInteger(count) || count < 1) {
        throw new RequestValidationError(`${field} 必须是正整数。`);
    }
    return count;
}

function readOptionalInteger(formData: FormData, field: string): number | undefined {
    const value = formData.get(field);
    if (value === null) return undefined;
    if (typeof value !== 'string' || !/^\d+$/.test(value)) {
        throw new RequestValidationError(`${field} 必须是整数。`);
    }
    const count = Number(value);
    if (!Number.isSafeInteger(count)) {
        throw new RequestValidationError(`${field} 必须是整数。`);
    }
    return count;
}

function readOptionalPartialImages(formData: FormData): number | undefined {
    const value = readOptionalInteger(formData, 'partial_images');
    return value === undefined ? undefined : toPartialImagesCount(value);
}

function isPageCredentialEligible(input: {
    credential: ChannelCredential;
    requestMode?: ChannelRequestMode;
    mode: ImageMode;
    imageBackend: ImageGenerationBackend;
    formData: FormData;
    model: ReturnType<typeof readModel>;
    forceRequest: boolean;
    streamMode: ImageStreamMode;
    streamingStrategy: ImageStreamingStrategy;
    requestedImageCount?: number;
    requestedPartialImages?: number;
}): boolean {
    if (!input.requestMode) return true;
    if (
        input.streamMode === 'auto' &&
        isStreamingChannelRequestMode(input.requestMode) &&
        getServerChannelState().streamingAvailability.isUnavailable({
            channelId: input.credential.channelId,
            imageBackend: input.imageBackend,
            streamingStrategy: input.streamingStrategy,
            operation: input.mode
        })
    ) {
        return false;
    }
    const upstreamProfile =
        input.credential.providerProfile ||
        readImageUpstreamProfile({
            explicitProfile: input.credential.upstreamProfile,
            channelId: input.credential.channelId,
            baseUrl: input.credential.baseUrl
        });
    const validatePartialImages = isStreamingChannelRequestMode(input.requestMode);
    const compatibility = getImageBackendCompatibility(upstreamProfile, input.mode, input.imageBackend, undefined, {
        validatePartialImages
    });
    const imageCountRange = compatibility.imageCountRange;
    if (!compatibility.compatible || !imageCountRange) return false;
    if (input.requestedImageCount !== undefined && !isIntegerWithinRange(input.requestedImageCount, imageCountRange)) {
        return false;
    }
    if (validatePartialImages) {
        const partialImagesRange = compatibility.partialImagesRange;
        if (
            !partialImagesRange ||
            (input.requestedPartialImages !== undefined &&
                !isIntegerWithinRange(input.requestedPartialImages, partialImagesRange))
        ) {
            return false;
        }
    }
    try {
        if (input.mode === 'generate') {
            readBackground(input.formData, input.model, upstreamProfile, { forceRequest: input.forceRequest });
            readSize(input.formData, 'size', '1024x1024', input.model, upstreamProfile, {
                forceRequest: input.forceRequest
            });
        } else {
            readSize(input.formData, 'size', 'auto', input.model, upstreamProfile, {
                forceRequest: input.forceRequest
            });
            readImageFiles(input.formData, upstreamProfile);
            readMaskFile(input.formData, upstreamProfile);
        }
        return true;
    } catch (error) {
        if (error instanceof RequestValidationError) return false;
        throw error;
    }
}

function validatePageInputAgainstConfiguredProfiles(input: {
    credentials: readonly ChannelCredential[];
    formData: FormData;
    mode: ImageMode;
    imageBackend: ImageGenerationBackend;
    model: ReturnType<typeof readModel>;
    forceRequest: boolean;
    requestedImageCount?: number;
    requestedPartialImages?: number;
    requestModes: readonly ChannelRequestMode[];
}): void {
    let firstValidationError: RequestValidationError | undefined;
    let hasHealthyRequestMode = false;
    const router = getServerChannelState().router;
    for (const credential of input.credentials) {
        const profile =
            credential.providerProfile ||
            readImageUpstreamProfile({
                explicitProfile: credential.upstreamProfile,
                channelId: credential.channelId,
                baseUrl: credential.baseUrl
            });
        const requestModes = input.requestModes.filter((requestMode) =>
            getEffectiveChannelRequestModes(credential).includes(requestMode)
        );
        if (requestModes.length === 0) continue;
        for (const requestMode of requestModes) {
            if (!isChannelCredentialRequestModeHealthy(router, credential, requestMode)) continue;
            hasHealthyRequestMode = true;
            try {
                const validatePartialImages = isStreamingChannelRequestMode(requestMode);
                const compatibility = getImageBackendCompatibility(profile, input.mode, input.imageBackend, undefined, {
                    validatePartialImages
                });
                const imageCountRange = compatibility.imageCountRange;
                if (!compatibility.compatible || !imageCountRange) {
                    throw new RequestValidationError(
                        compatibility.errors.map((error) => error.message).join(' ') ||
                            '当前图片后端没有可用的图片数量约束。',
                        422
                    );
                }
                if (
                    input.requestedImageCount !== undefined &&
                    !isIntegerWithinRange(input.requestedImageCount, imageCountRange)
                ) {
                    throw new RequestValidationError(
                        imageCountRange.allowedValues
                            ? `n 必须是以下值之一:${imageCountRange.allowedValues.join(', ')}。`
                            : `n 必须在 ${imageCountRange.min}${imageCountRange.max} 之间。`,
                        422
                    );
                }
                if (validatePartialImages) {
                    const partialImagesRange = compatibility.partialImagesRange;
                    if (
                        !partialImagesRange ||
                        (input.requestedPartialImages !== undefined &&
                            !isIntegerWithinRange(input.requestedPartialImages, partialImagesRange))
                    ) {
                        throw new RequestValidationError(
                            partialImagesRange
                                ? partialImagesRange.allowedValues
                                    ? `partial_images 必须是以下值之一:${partialImagesRange.allowedValues.join(', ')}。`
                                    : `partial_images 必须在 ${partialImagesRange.min}${partialImagesRange.max} 之间。`
                                : '当前图片后端没有可用的 partial_images 约束。',
                            422
                        );
                    }
                }
                if (input.mode === 'generate') {
                    readBackground(input.formData, input.model, profile, { forceRequest: input.forceRequest });
                    readSize(input.formData, 'size', '1024x1024', input.model, profile, {
                        forceRequest: input.forceRequest
                    });
                } else {
                    readSize(input.formData, 'size', 'auto', input.model, profile, {
                        forceRequest: input.forceRequest
                    });
                    readImageFiles(input.formData, profile);
                    readMaskFile(input.formData, profile);
                }
                return;
            } catch (error) {
                if (!(error instanceof RequestValidationError)) throw error;
                firstValidationError ??= error;
            }
        }
    }
    if (hasHealthyRequestMode && firstValidationError) throw firstValidationError;
}

function createAvailabilityKey(input: StreamResolutionInput): StreamingAvailabilityKey {
    return {
        channelId: input.selectedCredential?.channelId,
        sourceId: input.selectedCredential ? undefined : input.sourceId,
        imageBackend: input.imageBackend,
        streamingStrategy: input.streamingStrategy,
        operation: input.operation
    };
}

function createAvailabilitySourceId(input: {
    selectedCredential?: ChannelCredential;
    baseUrl?: string;
}): string | undefined {
    if (input.selectedCredential) return undefined;
    const normalized = normalizeAvailabilityBaseUrl(input.baseUrl);
    const digest = crypto.createHash('sha256').update(normalized).digest('hex').slice(0, 16);
    return `upstream:${digest}`;
}

function normalizeAvailabilityBaseUrl(baseUrl: string | undefined): string {
    const rawValue = baseUrl && baseUrl.trim() ? baseUrl.trim() : 'https://api.openai.com/v1';
    try {
        const parsed = new URL(rawValue);
        const pathname = parsed.pathname.replace(/\/+$/, '') || '/';
        return `${parsed.protocol}//${parsed.host}${pathname}`.toLowerCase();
    } catch {
        return 'invalid-upstream';
    }
}

function resolvePageStream(input: StreamResolutionInput): StreamResolution {
    const availabilityKey = createAvailabilityKey(input);
    const streamingAvailability = getServerChannelState().streamingAvailability;
    if (input.forceNonStream) {
        return {
            availabilityKey,
            streamEnabled: false,
            streamFallbackEnabled: false,
            streamingMarkedUnavailable: streamingAvailability.isUnavailable(availabilityKey)
        };
    }
    if (input.streamMode === 'non_stream') {
        return {
            availabilityKey,
            streamEnabled: false,
            streamFallbackEnabled: false,
            streamingMarkedUnavailable: streamingAvailability.isUnavailable(availabilityKey)
        };
    }

    if (input.streamMode === 'auto' && input.streamingStrategy === 'off') {
        return {
            availabilityKey,
            streamEnabled: false,
            streamFallbackEnabled: false,
            streamingMarkedUnavailable: streamingAvailability.isUnavailable(availabilityKey)
        };
    }

    if (input.streamMode === 'auto' && streamingAvailability.isUnavailable(availabilityKey)) {
        return {
            availabilityKey,
            streamEnabled: false,
            streamFallbackEnabled: false,
            streamingMarkedUnavailable: true
        };
    }

    return {
        availabilityKey,
        streamEnabled: resolveImageStreamEnabled({
            imageBackend: input.imageBackend,
            requestedStream: true,
            streamingStrategy: input.streamingStrategy
        }),
        streamFallbackEnabled: input.streamMode === 'auto',
        streamingMarkedUnavailable: false
    };
}

function resolvePageChannelRequestModePlan(input: {
    streamMode: ImageStreamMode;
    imageBackend: ImageGenerationBackend;
    streamingStrategy: ImageStreamingStrategy;
}): ChannelRequestModePlan {
    if (input.streamMode === 'non_stream') {
        const preferred = resolveChannelRequestMode({ imageBackend: input.imageBackend, streamEnabled: false });
        return {
            preferred,
            candidates: [preferred]
        };
    }
    if (input.streamMode === 'auto' && input.streamingStrategy === 'off') {
        const preferred = resolveChannelRequestMode({ imageBackend: input.imageBackend, streamEnabled: false });
        return {
            preferred,
            candidates: [preferred]
        };
    }
    const preferred = resolveChannelRequestMode({
        imageBackend: input.imageBackend,
        streamEnabled: resolveImageStreamEnabled({
            imageBackend: input.imageBackend,
            requestedStream: true,
            streamingStrategy: input.streamingStrategy
        })
    });
    if (input.streamMode !== 'auto' || !isStreamingChannelRequestMode(preferred)) {
        return { preferred, candidates: [preferred] };
    }
    if (input.streamingStrategy !== 'auto') {
        return { preferred, candidates: [preferred] };
    }
    const fallback = resolveChannelRequestMode({ imageBackend: input.imageBackend, streamEnabled: false });
    return {
        preferred: fallback,
        fallback: preferred,
        candidates: [fallback, preferred]
    };
}

function selectPageServerCredential(input: {
    router: NonNullable<ReturnType<typeof getServerChannelState>['router']>;
    affinityKey: string;
    plan: ChannelRequestModePlan;
    isEligible?: (credential: ChannelCredential, requestMode?: ChannelRequestMode) => boolean;
}): PageChannelSelection {
    if (input.plan.candidates.length > 1) {
        const selection = input.router.selectWithRequestModes({
            affinityKey: input.affinityKey,
            requestModes: input.plan.candidates,
            isEligible: input.isEligible
        });
        return {
            selectedCredential: selection.credential,
            requestMode: selection.requestMode,
            forcedNonStream: !isStreamingChannelRequestMode(selection.requestMode),
            fallbackApplied: selection.requestMode !== selection.preferredRequestMode
        };
    }
    try {
        return {
            selectedCredential: input.router.select({
                affinityKey: input.affinityKey,
                requestMode: input.plan.preferred,
                isEligible: input.isEligible
            }),
            requestMode: input.plan.preferred,
            forcedNonStream: !isStreamingChannelRequestMode(input.plan.preferred),
            fallbackApplied: false
        };
    } catch (error) {
        if (!input.plan.fallback || !(error instanceof RequestValidationError)) {
            throw error;
        }
        return {
            selectedCredential: input.router.select({
                affinityKey: input.affinityKey,
                requestMode: input.plan.fallback,
                isEligible: input.isEligible
            }),
            requestMode: input.plan.fallback,
            forcedNonStream: true,
            fallbackApplied: true
        };
    }
}

function markStreamingUnavailable(input: {
    key: StreamingAvailabilityKey;
    error?: unknown;
    reason: string;
    status?: number;
}) {
    const status = input.status ?? readErrorStatus(input.error);
    getServerChannelState().streamingAvailability.markUnavailable({
        ...input.key,
        reason: input.reason,
        ...(status !== undefined ? { status } : {}),
        ...(readErrorCode(input.error) ? { code: readErrorCode(input.error) } : {})
    });
}

function appendChannelQueueHeaders(response: Response, lease: ChannelCapacityLease | undefined): Response {
    if (!lease) return response;
    const headers = new Headers(response.headers);
    headers.set('X-Channel-Queue-Wait-Ms', String(lease.waitMs));
    headers.set('X-Channel-Queue-Queued', lease.queued ? 'true' : 'false');
    headers.set('X-Channel-Queue-Capacity', String(lease.capacity));
    return new Response(response.body, {
        status: response.status,
        statusText: response.statusText,
        headers
    });
}

function releaseChannelLeaseAfterResponse(response: Response, lease: ChannelCapacityLease): Response {
    if (!response.body) {
        const responseWithHeaders = appendChannelQueueHeaders(response, lease);
        lease.release();
        return responseWithHeaders;
    }

    const reader = response.body.getReader();
    const body = new ReadableStream<Uint8Array>({
        async pull(controller) {
            try {
                const result = await reader.read();
                if (result.done) {
                    lease.release();
                    controller.close();
                    return;
                }
                controller.enqueue(result.value);
            } catch (error) {
                lease.release();
                controller.error(error);
            }
        },
        async cancel(reason) {
            try {
                await reader.cancel(reason);
            } finally {
                lease.release();
            }
        }
    });
    return appendChannelQueueHeaders(
        new Response(body, {
            status: response.status,
            statusText: response.statusText,
            headers: response.headers
        }),
        lease
    );
}

function reportPersistDiagnosticsFailure(input: {
    credential?: ChannelCredential;
    diagnostics: UpstreamResponseDiagnostics;
    requestMode?: ChannelRequestMode;
}) {
    if (input.diagnostics.category !== 'responses_disabled') return;
    reportServerCredentialFailure(
        input.credential,
        {
            status: 403,
            error: { message: 'Image generation is not enabled for this group' }
        },
        input.requestMode
    );
}

function readBooleanAlias(formData: FormData, ...fields: string[]): boolean | undefined {
    for (const field of fields) {
        const value = formData.get(field);
        if (value === null || value === '') continue;
        if (typeof value !== 'string') {
            throw new RequestValidationError(`${field} 必须是 true 或 false。`);
        }
        if (value === 'true') return true;
        if (value === 'false') return false;
        throw new RequestValidationError(`${field} 必须是 true 或 false。`);
    }
    return undefined;
}

export async function POST(request: NextRequest) {
    let selectedServerCredential: ChannelCredential | undefined;
    let selectedServerRequestMode: ChannelRequestMode | undefined;
    let channelLease: ChannelCapacityLease | undefined;
    let clientRequestId: string | undefined;
    let requestLogContext: RequestLogContext | undefined;
    let accessCookie: AccessCookie | undefined;
    try {
        const serverChannelState = getServerChannelState();
        const serverChannelRouter = serverChannelState.router;
        const contentType = request.headers.get('content-type') || '';
        if (
            !contentType.includes('multipart/form-data') &&
            !contentType.includes('application/x-www-form-urlencoded')
        ) {
            return NextResponse.json({ error: '请求正文无效:必须是 multipart/form-data。' }, { status: 400 });
        }
        const formData = await request.formData();
        clientRequestId = readClientRequestId(formData);
        const upstreamIdempotencyKey = clientRequestId || crypto.randomUUID();
        requestLogContext = clientRequestId ? { clientRequestId } : undefined;
        const requestApiKey = String(formData.get('apiKey') || '').trim();
        const requestApiBaseUrl = String(formData.get('apiBaseUrl') || '').trim();
        const allowedPlainHttpBaseUrls = readPlainHttpApiBaseUrlAllowlist(
            process.env.OPENAI_ALLOWED_PLAIN_HTTP_API_BASE_URLS
        );
        assertSafeApiOverride(requestApiKey, requestApiBaseUrl);
        validateApiBaseUrl(requestApiBaseUrl, { allowedPlainHttpBaseUrls });
        const streamMode = readImageStreamMode(formData, process.env);
        const imageBackend = readImageGenerationBackend(formData, process.env);
        const streamingStrategy = readImageStreamingStrategy(formData, process.env);
        const mode = readMode(formData);
        const model = readModel(formData);
        const forceRequest = readBooleanAlias(formData, 'force_request', 'forceRequest') === true;
        const requestedImageCount = readOptionalPositiveCount(formData, 'n');
        const requestedPartialImages = readOptionalPartialImages(formData);
        const requestModePlan = resolvePageChannelRequestModePlan({ streamMode, imageBackend, streamingStrategy });
        if (!requestApiKey && serverChannelRouter) {
            validatePageInputAgainstConfiguredProfiles({
                credentials: serverChannelState.config.credentials,
                formData,
                mode,
                imageBackend,
                model,
                forceRequest,
                requestedImageCount,
                requestedPartialImages,
                requestModes: requestModePlan.candidates
            });
        }
        const channelSelection =
            requestApiKey || !serverChannelRouter
                ? {
                      selectedCredential: undefined,
                      requestMode: requestModePlan.preferred,
                      forcedNonStream: !isStreamingChannelRequestMode(requestModePlan.preferred),
                      fallbackApplied: false
                  }
                : selectPageServerCredential({
                      router: serverChannelRouter,
                      affinityKey: readAffinityKey(request.headers),
                      plan: requestModePlan,
                      isEligible: (credential, requestMode) =>
                          isPageCredentialEligible({
                              credential,
                              requestMode,
                              mode,
                              imageBackend,
                              formData,
                              model,
                              forceRequest,
                              streamMode,
                              streamingStrategy,
                              requestedImageCount,
                              requestedPartialImages
                          })
                  });
        selectedServerCredential = channelSelection.selectedCredential;
        selectedServerRequestMode = channelSelection.requestMode;
        const {
            apiKey: effectiveApiKey,
            baseUrl: effectiveApiBaseUrl,
            upstreamProxyUrl: effectiveUpstreamProxyUrl,
            upstreamProfile: effectiveUpstreamProfileId,
            providerProfile,
            upstreamHeaders,
            selectedCredential
        } = resolveEffectiveCredential({
            requestApiKey,
            requestApiBaseUrl,
            legacyBaseUrl: process.env.OPENAI_API_BASE_URL,
            legacyUpstreamProxyUrl: process.env.OPENAI_UPSTREAM_PROXY_URL,
            selectedCredential: selectedServerCredential
        });
        validateApiBaseUrl(effectiveApiBaseUrl || '', { allowedPlainHttpBaseUrls });

        if (!effectiveApiKey) {
            appLogger.error('未设置 OPENAI_API_KEY,且请求未提供 API Key。', requestLogContext);
            return NextResponse.json(
                { error: '请在 API 设置中填写 API Key,或配置 OPENAI_API_KEY 环境变量。' },
                { status: 400 }
            );
        }
        if (selectedCredential) {
            appLogger.info(
                `已选择 API 渠道:${selectedCredential.channelId},凭证:${selectedCredential.id},策略:server`,
                {
                    ...requestLogContext,
                    channelRequestMode: channelSelection.requestMode,
                    channelRequestModeFallbackApplied: channelSelection.fallbackApplied
                }
            );
        }

        const openai = new OpenAI(
            createOpenAIImageClientOptions({
                apiKey: effectiveApiKey,
                baseURL: effectiveApiBaseUrl || undefined,
                upstreamProxyUrl: effectiveUpstreamProxyUrl,
                defaultHeaders: mergeUpstreamHeadersWithFixed(upstreamHeaders, {})
            })
        );
        const upstreamProfile =
            providerProfile ||
            readImageUpstreamProfile({
                explicitProfile: effectiveUpstreamProfileId,
                channelId: selectedCredential?.channelId,
                baseUrl: effectiveApiBaseUrl
            });

        const effectiveStorageMode = readStorageMode(process.env);
        appLogger.info(`实际图片存储模式:${effectiveStorageMode}`, requestLogContext);

        if (effectiveStorageMode === 'fs') {
            await ensureOutputDirExists();
        }

        const appPassword = process.env.APP_PASSWORD?.trim();
        if (appPassword) {
            const clientPasswordHash = formData.get('passwordHash');
            if (typeof clientPasswordHash !== 'string' || !clientPasswordHash) {
                appLogger.error('缺少访问码哈希。', requestLogContext);
                return NextResponse.json(
                    { error: '未授权:缺少访问码哈希。', code: PAGE_PASSWORD_AUTH_ERROR_CODES.missing },
                    { status: 401 }
                );
            }
            if (!verifyPasswordHash(clientPasswordHash, appPassword)) {
                appLogger.error('访问码哈希无效。', requestLogContext);
                return NextResponse.json(
                    { error: '未授权:访问码无效。', code: PAGE_PASSWORD_AUTH_ERROR_CODES.invalid },
                    { status: 401 }
                );
            }
            accessCookie = buildAccessCookie(appPassword, request.headers);
        }

        const prompt = readRequiredText(formData, 'prompt');
        const upstreamStartedAtMs = Date.now();

        appLogger.info(`开始处理图片请求。模式:${mode},模型:${model}`, requestLogContext);
        appLogger.debug(
            `模式:${mode},模型:${model},提示词:${prompt ? prompt.substring(0, 50) + '...' : 'N/A'}`,
            requestLogContext
        );

        assertResponsesImageBackendAllowed({ imageBackend, mode });
        const streamResolution = resolvePageStream({
            streamMode,
            imageBackend,
            streamingStrategy,
            operation: mode,
            selectedCredential,
            sourceId: createAvailabilitySourceId({
                selectedCredential,
                baseUrl: effectiveApiBaseUrl
            }),
            forceNonStream: channelSelection.forcedNonStream
        });
        const backendCompatibility = getImageBackendCompatibility(upstreamProfile, mode, imageBackend, undefined, {
            validatePartialImages: streamResolution.streamEnabled
        });
        if (!backendCompatibility.compatible) {
            throw new RequestValidationError(backendCompatibility.errors.map((error) => error.message).join(' '), 422);
        }
        const partialImagesCount = streamResolution.streamEnabled
            ? (() => {
                  const partialImagesRange = backendCompatibility.partialImagesRange;
                  if (!partialImagesRange) {
                      throw new RequestValidationError('当前图片后端没有可用的 partial_images 约束。', 422);
                  }
                  return toPartialImagesCount(
                      readCount(
                          formData,
                          'partial_images',
                          clampIntegerToRange(2, partialImagesRange),
                          partialImagesRange.min,
                          partialImagesRange.max,
                          partialImagesRange
                      )
                  );
              })()
            : toPartialImagesCount(requestedPartialImages ?? 2);
        appLogger.info('图片上游兼容策略。', {
            ...requestLogContext,
            imageBackend,
            streamingStrategy,
            streamMode,
            streamEnabled: streamResolution.streamEnabled,
            streamFallbackEnabled: streamResolution.streamFallbackEnabled,
            streamingMarkedUnavailable: streamResolution.streamingMarkedUnavailable,
            channelRequestMode: channelSelection.requestMode,
            channelRequestModeFallbackApplied: channelSelection.fallbackApplied,
            upstreamProfile: upstreamProfile.id,
            upstreamExtraHeaders: Boolean(upstreamHeaders)
        });

        if (selectedCredential) {
            channelLease = await serverChannelState.channelCapacityQueue.acquire(selectedCredential.id, {
                signal: request.signal
            });
            appLogger.info('渠道凭证并发容量已获取。', {
                ...requestLogContext,
                channelId: selectedCredential.channelId,
                credentialId: selectedCredential.id,
                queued: channelLease.queued,
                waitMs: channelLease.waitMs,
                queueCapacity: channelLease.capacity,
                queuedCount: channelLease.queuedCount
            });
        }

        const modeResult =
            mode === 'generate'
                ? await handleGenerateImageMode({
                      formData,
                      openai,
                      model,
                      prompt,
                      streamEnabled: streamResolution.streamEnabled,
                      partialImagesCount,
                      upstreamProfile,
                      upstreamHeaders,
                      imageBackend,
                      storageMode: effectiveStorageMode,
                      apiBaseUrl: effectiveApiBaseUrl,
                      apiKey: effectiveApiKey,
                      upstreamProxyUrl: effectiveUpstreamProxyUrl,
                      startedAtMs: upstreamStartedAtMs,
                      upstreamIdempotencyKey,
                      clientRequestId,
                      requestLogContext,
                      selectedCredential,
                      channelRequestMode: channelSelection.requestMode,
                      accessCookie,
                      forceRequest,
                      abortSignal: request.signal,
                      streamFallbackEnabled: streamResolution.streamFallbackEnabled,
                      onStreamUnavailable: (error, reason) =>
                          markStreamingUnavailable({ key: streamResolution.availabilityKey, error, reason }),
                      onStreamingDegraded: (reason) =>
                          markStreamingUnavailable({
                              key: streamResolution.availabilityKey,
                              reason,
                              status: 200
                          })
                  })
                : await handleEditImageMode({
                      formData,
                      openai,
                      model,
                      prompt,
                      streamEnabled: streamResolution.streamEnabled,
                      partialImagesCount,
                      upstreamProfile,
                      upstreamHeaders,
                      imageBackend,
                      storageMode: effectiveStorageMode,
                      apiBaseUrl: effectiveApiBaseUrl,
                      apiKey: effectiveApiKey,
                      upstreamProxyUrl: effectiveUpstreamProxyUrl,
                      startedAtMs: upstreamStartedAtMs,
                      upstreamIdempotencyKey,
                      clientRequestId,
                      requestLogContext,
                      selectedCredential,
                      channelRequestMode: channelSelection.requestMode,
                      accessCookie,
                      forceRequest,
                      abortSignal: request.signal,
                      streamFallbackEnabled: streamResolution.streamFallbackEnabled,
                      onStreamUnavailable: (error, reason) =>
                          markStreamingUnavailable({ key: streamResolution.availabilityKey, error, reason }),
                      onStreamingDegraded: (reason) =>
                          markStreamingUnavailable({
                              key: streamResolution.availabilityKey,
                              reason,
                              status: 200
                          })
                  });
        if (modeResult instanceof Response) {
            if (!channelLease) return modeResult;
            const response = releaseChannelLeaseAfterResponse(modeResult, channelLease);
            channelLease = undefined;
            return response;
        }
        const { result, outputFormat: responseOutputFormat } = modeResult;

        appLogger.info('OpenAI API 调用成功。', requestLogContext);

        try {
            const savedImages = await persistOpenAiImages({
                result,
                outputFormat: responseOutputFormat,
                storageMode: effectiveStorageMode,
                includeBase64: true,
                normalizeOutputFormat: true,
                apiBaseUrl: effectiveApiBaseUrl,
                apiKey: effectiveApiKey,
                upstreamProxyUrl: effectiveUpstreamProxyUrl,
                upstreamHeaders,
                abortSignal: request.signal
            });
            const savedImagesData = savedImages.map((image) => ({
                ...persistedImageToLegacyResponse(image),
                ...(clientRequestId ? { clientRequestId } : {})
            }));
            const actualCost = await resolveRequestActualCostSafely({
                apiBaseUrl: effectiveApiBaseUrl,
                apiKey: effectiveApiKey,
                upstreamProxyUrl: effectiveUpstreamProxyUrl,
                model,
                startedAtMs: upstreamStartedAtMs,
                expectedImageCount: savedImagesData.length,
                requestLogContext
            });

            appLogger.info(`所有图片已处理。模式:${effectiveStorageMode}`, {
                ...requestLogContext,
                filenames: savedImagesData.map((image) => image.filename)
            });

            const response = attachAccessCookie(
                NextResponse.json({ images: savedImagesData, usage: result.usage, actualCost, clientRequestId }),
                accessCookie
            );
            const responseWithHeaders = appendChannelQueueHeaders(response, channelLease);
            channelLease?.release();
            channelLease = undefined;
            return responseWithHeaders;
        } catch (persistError) {
            if (persistError instanceof MissingOpenAiImageDataError) {
                const invalidResult = persistError.result;
                const diagnostics = inspectInvalidImagesResponse(invalidResult);
                appLogger.error(`第 ${persistError.index} 个图片数据缺少 b64_json。`, {
                    upstreamDiagnostics: diagnostics,
                    ...requestLogContext
                });
                reportPersistDiagnosticsFailure({
                    credential: selectedCredential,
                    diagnostics,
                    requestMode: selectedServerRequestMode
                });
                const response = NextResponse.json(
                    { error: describeInvalidImagesResponse(invalidResult), diagnostics },
                    { status: 502 }
                );
                const responseWithHeaders = appendChannelQueueHeaders(response, channelLease);
                channelLease?.release();
                channelLease = undefined;
                return responseWithHeaders;
            }
            if (!(persistError instanceof InvalidOpenAiImagesResponseError)) {
                throw persistError;
            }
            const invalidResult: unknown = persistError.result;
            const diagnostics = inspectInvalidImagesResponse(invalidResult);
            appLogger.error('OpenAI API 返回的数据无效或为空:', {
                type: typeof invalidResult,
                upstreamDiagnostics: diagnostics,
                ...requestLogContext
            });
            reportPersistDiagnosticsFailure({
                credential: selectedCredential,
                diagnostics,
                requestMode: selectedServerRequestMode
            });
            const response = NextResponse.json(
                { error: describeInvalidImagesResponse(invalidResult), diagnostics },
                { status: 502 }
            );
            const responseWithHeaders = appendChannelQueueHeaders(response, channelLease);
            channelLease?.release();
            channelLease = undefined;
            return responseWithHeaders;
        }
    } catch (error: unknown) {
        channelLease?.release();
        channelLease = undefined;
        reportServerCredentialFailure(selectedServerCredential, error, selectedServerRequestMode);
        const upstreamDiagnostics = inspectUpstreamError(error);
        appLogger.error('/api/images 处理失败:', {
            ...requestLogContext,
            error: error instanceof Error ? error.message : String(error),
            ...(upstreamDiagnostics ? { upstreamDiagnostics } : {})
        });

        let errorMessage = '发生未知错误。';
        let status = 500;

        if (error instanceof RequestValidationError) {
            errorMessage = error.message;
            status = error.status;
        } else if (error instanceof Error) {
            errorMessage = error.message;
            if (errorMessage.includes('<!DOCTYPE html') || errorMessage.includes('<html')) {
                errorMessage = describeInvalidImagesResponse(errorMessage);
            }
            if (typeof error === 'object' && error !== null && 'status' in error && typeof error.status === 'number') {
                status = error.status;
            }
        } else if (typeof error === 'object' && error !== null) {
            if ('message' in error && typeof error.message === 'string') {
                errorMessage = error.message;
            }
            if ('status' in error && typeof error.status === 'number') {
                status = error.status;
            }
        }

        return NextResponse.json(
            { error: errorMessage, ...(upstreamDiagnostics ? { diagnostics: upstreamDiagnostics } : {}) },
            { status }
        );
    }
}