File size: 54,295 Bytes
3e8ea5d
 
11486ce
f9a28cd
 
 
 
 
 
b1cfe1b
c7d34c1
 
 
 
 
 
 
 
11486ce
 
 
 
 
 
 
 
 
 
 
b1cfe1b
 
 
 
 
 
 
 
 
a2c232b
b1cfe1b
3e8ea5d
32151b6
 
 
 
 
 
11486ce
 
32151b6
c7d34c1
 
e445b51
c7d34c1
 
 
 
11486ce
 
c7d34c1
 
 
11486ce
 
c7d34c1
 
 
 
 
32151b6
3e8ea5d
 
 
 
 
 
 
 
 
 
e445b51
3e8ea5d
e445b51
3e8ea5d
 
 
 
 
e445b51
 
 
 
 
 
b1cfe1b
09ad34c
01f44cd
11486ce
c7d34c1
 
32151b6
3e8ea5d
c7d34c1
 
 
 
32151b6
3e8ea5d
6dd78ad
 
3e8ea5d
 
 
 
 
 
c7d34c1
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
 
 
 
 
 
3e8ea5d
e445b51
3e8ea5d
11486ce
01f44cd
 
 
 
96bdf6c
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
f9a28cd
 
 
11486ce
 
 
 
 
c7d34c1
 
 
 
 
 
 
11486ce
 
c7d34c1
 
32151b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
32151b6
c7d34c1
 
11486ce
 
 
 
a2c232b
11486ce
 
 
 
 
 
a2c232b
f9a28cd
96bdf6c
11486ce
 
 
f9a28cd
 
 
 
96bdf6c
 
 
 
f9a28cd
 
 
 
 
c7d34c1
 
 
 
3e8ea5d
e445b51
3e8ea5d
11486ce
c7d34c1
 
 
 
11486ce
 
 
c7d34c1
11486ce
c7d34c1
11486ce
 
 
c7d34c1
96bdf6c
 
 
 
 
 
 
 
32151b6
 
 
 
 
 
 
11486ce
 
32151b6
3e8ea5d
32151b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8ea5d
 
 
 
e445b51
 
 
 
 
3e8ea5d
 
 
e445b51
3e8ea5d
 
 
32151b6
 
 
 
 
3e8ea5d
 
 
 
 
 
 
 
 
 
 
09ad34c
3e8ea5d
 
6dd78ad
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8ea5d
 
 
 
 
01f44cd
3e8ea5d
 
 
32151b6
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
 
 
3e8ea5d
 
 
f9a28cd
3e8ea5d
e445b51
c7d34c1
 
 
 
 
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
704e84f
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
 
3e8ea5d
 
e445b51
3e8ea5d
 
 
e445b51
3e8ea5d
 
 
e445b51
 
01f44cd
e445b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8ea5d
 
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11486ce
 
 
 
 
96bdf6c
 
11486ce
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
96bdf6c
c7d34c1
11486ce
96bdf6c
11486ce
 
c7d34c1
 
96bdf6c
c7d34c1
 
 
 
 
 
11486ce
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8ea5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e445b51
3e8ea5d
e445b51
 
3e8ea5d
 
 
 
e445b51
3e8ea5d
 
 
e445b51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8ea5d
 
 
 
e445b51
3e8ea5d
 
 
e445b51
3e8ea5d
 
 
e445b51
3e8ea5d
 
 
 
 
 
 
 
11486ce
 
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
 
 
 
96bdf6c
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
01f44cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
b1cfe1b
 
 
 
 
01f44cd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
11486ce
 
 
c7d34c1
 
 
 
3e8ea5d
 
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
11486ce
c7d34c1
 
 
96bdf6c
 
 
 
c7d34c1
 
 
96bdf6c
c7d34c1
 
3e8ea5d
e445b51
3e8ea5d
11486ce
01f44cd
 
 
 
e445b51
c7d34c1
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8ea5d
 
e445b51
3e8ea5d
01f44cd
 
 
 
96bdf6c
 
c7d34c1
 
 
 
 
 
 
 
 
 
 
32151b6
c7d34c1
 
 
32151b6
c7d34c1
 
 
32151b6
c7d34c1
 
 
 
 
 
 
32151b6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
32151b6
 
 
 
 
 
 
 
 
 
3e8ea5d
 
 
 
 
 
 
 
 
 
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8ea5d
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32151b6
3e8ea5d
 
 
 
 
 
 
 
 
 
 
 
 
32151b6
 
 
c7d34c1
3e8ea5d
 
11486ce
 
 
c7d34c1
 
 
32151b6
3e8ea5d
11486ce
 
 
f9a28cd
c7d34c1
 
 
3e8ea5d
 
e445b51
 
11486ce
c7d34c1
 
 
11486ce
 
 
 
 
 
 
 
 
 
 
 
c7d34c1
96bdf6c
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
32151b6
 
 
 
 
 
 
11486ce
 
32151b6
 
 
 
 
3e8ea5d
 
 
32151b6
 
 
 
 
 
 
3e8ea5d
32151b6
 
 
 
3e8ea5d
 
 
 
 
 
e445b51
 
 
 
 
3e8ea5d
 
 
e445b51
3e8ea5d
 
32151b6
 
 
 
 
3e8ea5d
 
 
 
 
 
 
 
09ad34c
3e8ea5d
 
6dd78ad
 
 
 
 
 
 
 
 
 
 
 
 
 
 
3e8ea5d
 
 
e445b51
 
 
 
3e8ea5d
 
e445b51
 
 
 
 
 
 
 
 
 
77bcff5
3e8ea5d
 
 
e445b51
 
 
 
 
3e8ea5d
 
 
e445b51
 
 
 
 
 
 
 
3e8ea5d
 
 
 
e445b51
 
 
 
 
3e8ea5d
 
 
e445b51
 
 
 
 
 
 
 
3e8ea5d
 
 
 
e445b51
 
 
 
 
3e8ea5d
 
6dd78ad
e445b51
 
 
6dd78ad
e445b51
 
 
6dd78ad
3e8ea5d
01f44cd
 
e445b51
 
01f44cd
e445b51
 
3e8ea5d
 
6dd78ad
e445b51
 
 
6dd78ad
01f44cd
e445b51
 
 
 
01f44cd
3e8ea5d
 
 
 
 
32151b6
 
 
 
 
3e8ea5d
 
 
 
 
 
32151b6
 
6dd78ad
32151b6
c7d34c1
 
 
 
 
 
 
3e8ea5d
 
 
 
f9a28cd
e445b51
 
c7d34c1
 
 
 
 
11486ce
 
704e84f
 
 
 
 
 
 
c7d34c1
 
 
 
 
 
 
11486ce
f9a28cd
 
 
 
 
96bdf6c
 
 
 
f9a28cd
 
 
 
 
 
 
b1cfe1b
 
 
11486ce
 
 
 
 
a2c232b
f9a28cd
96bdf6c
11486ce
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
import { AGENT_ENDPOINTS, AGENT_JOB_ENDPOINTS } from './agent-api-paths.mjs';
import type { AgentErrorDiagnostics } from './api-error-response';
import { readAppLogRetentionMetadata, type AppLogRetentionMetadata } from './app-log-retention';
import {
    CHANNEL_REQUEST_MODES,
    CHANNEL_REQUEST_MODE_ADMIN_CONTROL,
    type ChannelRequestMode,
    type ChannelRequestModeDecision
} from './channel-request-mode';
import { getChannelPoolSummary, parseChannelPoolConfig } from './channel-router';
import {
    MAX_IMAGE_COUNT,
    MAX_PROMPT_LENGTH,
    RequestValidationError,
    validateApiBaseUrl,
    type GptImageModel,
    type ValidOutputFormat
} from './image-request-utils';
import {
    summarizeImageUpstreamProfile,
    summarizeUpstreamRequestHeaders,
    clampIntegerToRange,
    getPartialImagesRangeForBackend,
    type ImageUpstreamProfile,
    type ImageUpstreamProfileId,
    type ImageUpstreamProfileSummary,
    type PartialImagesCount,
    type UpstreamRequestHeaderSummary
} from './image-upstream-profile';
import {
    parseImageGenerationBackendValue,
    parseImageStreamModeValue,
    parseImageStreamingStrategyValue,
    resolveImageStreamEnabled,
    type ImageGenerationBackend,
    type ImageStreamMode,
    type ImageStreamingStrategy
} from './image-upstream-strategy';
import { summarizeOpenAIImageTransport, type UpstreamProxySummary } from './openai-image-transport';
import { CHINESE_POSITIVE_INTEGER_MESSAGES, readPositiveIntegerFromEnv } from './positive-integer-config.mjs';
import { readBooleanEnv } from './server-runtime';
import {
    GPT_IMAGE_2_EDGE_MULTIPLE,
    GPT_IMAGE_2_MAX_ASPECT,
    GPT_IMAGE_2_MAX_EDGE,
    GPT_IMAGE_2_MAX_PIXELS,
    GPT_IMAGE_2_MIN_PIXELS,
    validateGptImage2Size,
    validatePositiveIntegerImageSize
} from './size-utils';

export const AGENT_API_VERSION = '1.0.0';
export const AGENT_SCHEMA_VERSION = '2026-05-28';
export const AGENT_DEFAULT_SQLITE_PATH = 'generated-images/.agent-state/agent.sqlite';
export const AGENT_DEFAULT_LEASE_MS = 10 * 60 * 1000;
export const AGENT_DEFAULT_REQUEST_TTL_SECONDS = 24 * 60 * 60;
export const AGENT_DEFAULT_RECOVERY_INTERVAL_MS = 30 * 1000;
export const AGENT_PAGE_REQUEST_DIAGNOSTICS_NO_MATCH_HINT =
    'matched_log_count=0 表示当前保留窗口内没有匹配日志;可能已被保留条数淘汰、被 APP_LOG_LEVEL 过滤,或本地日志文件被清理。';

export const AGENT_MODELS = ['gpt-image-1', 'gpt-image-1-mini', 'gpt-image-1.5', 'gpt-image-2'] as const;
export const AGENT_OUTPUT_FORMATS = ['png', 'jpeg', 'webp'] as const;
const AGENT_DEFAULT_OUTPUT_FORMAT = 'webp';
const AGENT_DEFAULT_LOSSY_OUTPUT_COMPRESSION = 100;
export const AGENT_RESPONSE_MODES = ['path', 'base64', 'both'] as const;
export const AGENT_QUALITIES = ['low', 'medium', 'high', 'auto'] as const;
export const AGENT_BACKGROUNDS = ['transparent', 'opaque', 'auto'] as const;
export const AGENT_MODERATIONS = ['low', 'auto'] as const;
export const AGENT_LEGACY_SIZES = ['auto', '1024x1024', '1536x1024', '1024x1536'] as const;
export const AGENT_JOB_STATES = ['queued', 'running', 'succeeded', 'failed', 'expired'] as const;
export const AGENT_IMAGE_BACKENDS = ['images-api', 'responses-image-generation'] as const;
export const PAGE_SSE_CLIENT_REQUEST_ID_MAX_LENGTH = 128;
export const AGENT_STREAMING_STRATEGIES = [
    'off',
    'auto',
    'openai-sse',
    'newapi-keepalive-sse',
    'responses-sse',
    'force-sse'
] as const;
export const AGENT_STREAM_MODES = ['auto', 'stream', 'non_stream'] as const;
export const AGENT_UPSTREAM_SSE_ACTIVATION_STRATEGIES = [
    'auto',
    'openai-sse',
    'newapi-keepalive-sse',
    'responses-sse',
    'force-sse'
] as const;
export const AGENT_UPSTREAM_SSE_GENERATE_REQUEST_FIELDS = [
    'image_backend',
    'stream_mode',
    'streaming_strategy',
    'partial_images'
] as const;
export const AGENT_UPSTREAM_SSE_EDIT_REQUEST_FIELDS = ['stream_mode', 'streaming_strategy', 'partial_images'] as const;
export const AGENT_PAGE_SSE_AGENT_USAGE =
    'explicit_diagnostics_for_generate_recommended_for_default_webp_edit_high_resolution_edit_long_image_recovery_and_complex_batch' as const;
const AGENT_DEFAULT_PARTIAL_IMAGES = 2;

export type AgentStateBackend = 'memory' | 'sqlite' | 'postgres';
export type AgentAuthScheme = 'bearer' | 'x-app-password-hash';
export type PageSseAuthScheme = 'form-password-hash';
export type AgentResponseMode = (typeof AGENT_RESPONSE_MODES)[number];
export type AgentQuality = (typeof AGENT_QUALITIES)[number];
export type AgentBackground = (typeof AGENT_BACKGROUNDS)[number];
export type AgentModeration = (typeof AGENT_MODERATIONS)[number];
export type AgentJobState = (typeof AGENT_JOB_STATES)[number];
export type AgentRoutingTransport = 'agent_json' | 'agent_job_polling' | 'page_sse';
export type AgentRoutingStrength = 'default' | 'recommended' | 'explicit';
export type AgentOrchestrationPolicy = 'server_orchestrated_generate_v1';
export type ImageBackendRuntimeRequirement = {
    supported: true;
    enabled: boolean;
    required_env: string[];
    missing_env: string[];
};

export type AgentPageRequestDiagnosticsRetention = AppLogRetentionMetadata & {
    bounded: true;
    not_agent_state_backend: true;
};

export type AgentRequestDiagnosticsRetention = {
    storage: 'agent_state';
    ttl_seconds: number;
    bounded: true;
    loss_modes: ['request_expired_by_ttl', 'artifact_deleted_or_purged', 'state_backend_reset'];
};

export type AgentPageRequestDiagnosticsNote = {
    code: 'no_matching_logs_in_retention_window';
    message: string;
    retention: AgentPageRequestDiagnosticsRetention;
};

export type AgentGenerateRequest = {
    model: GptImageModel;
    prompt: string;
    n: number;
    size: string;
    quality: AgentQuality;
    output_format: ValidOutputFormat;
    output_compression?: number;
    background: AgentBackground;
    moderation: AgentModeration;
    response_mode: AgentResponseMode;
    image_backend: ImageGenerationBackend;
    stream_mode: ImageStreamMode;
    streaming_strategy: ImageStreamingStrategy;
    partial_images: 0 | 1 | 2 | 3 | 4;
    responsesModel?: string;
    thinking?: 'minimal' | 'none' | 'low' | 'medium' | 'high' | 'xhigh';
    promptOptimization?: boolean;
    force_web?: boolean;
    force_request?: boolean;
};

export type AgentImageResponseItem = {
    id: string;
    filename: string;
    content_url: string;
    metadata_url: string;
    output_format: string;
    mime_type: string;
    size_bytes: number;
    width: number | null;
    height: number | null;
    b64_json?: string;
};

export type AgentImageResponseTiming = {
    started_at: string;
    completed_at: string;
    elapsed_ms: number;
    server_elapsed_ms: number;
};

export type AgentImageResponseExecution = {
    transport: AgentRoutingTransport;
    endpoint: string;
    route_mode: 'agent' | 'job' | 'page_sse';
    operation: 'generate' | 'edit';
    image_backend: ImageGenerationBackend;
    stream_mode: ImageStreamMode;
    streaming_strategy: ImageStreamingStrategy;
    channel_request_mode?: ChannelRequestMode;
    channel_request_mode_fallback_applied?: boolean;
    route_decision?: ChannelRequestModeDecision;
    selected_channel_id?: string;
    upstream_host?: string;
    request_headers: UpstreamRequestHeaderSummary;
};

export type AgentImageResponse = {
    request_id: string;
    idempotency_key: string;
    cached: boolean;
    images: AgentImageResponseItem[];
    usage?: unknown;
    created_at: string;
    timing?: AgentImageResponseTiming;
    execution?: AgentImageResponseExecution;
};

export type AgentJobStatusResponse = {
    job: {
        id: string;
        request_id: string;
        idempotency_key: string;
        mode: 'generate' | 'edit';
        state: AgentJobState;
        created_at: string;
        updated_at: string;
        expires_at: string;
        result_url?: string;
        retry_after_seconds?: number;
        error?: {
            code: string;
            message: string;
            retryable: boolean;
            details?: Record<string, unknown>;
            upstream_status?: number;
            diagnostics?: AgentErrorDiagnostics;
        };
    };
};

export type AgentCapabilities = {
    api_version: string;
    schema_version: string;
    auth: {
        required: boolean;
        schemes: AgentAuthScheme[];
    };
    endpoints: Record<string, string>;
    image_transport: {
        upstream_timeout_ms: number;
        stream_data_interval_timeout_ms: number;
        upstream_max_retries: number;
        upstream_proxy: UpstreamProxySummary;
    };
    upstream_profile: ImageUpstreamProfileSummary;
    upstream_request_headers: {
        default: UpstreamRequestHeaderSummary;
        channels: Array<{
            id: string;
            upstream_proxy: UpstreamProxySummary;
            request_modes: readonly ChannelRequestMode[];
            request_mode_priority: readonly ChannelRequestMode[];
            request_headers: UpstreamRequestHeaderSummary;
        }>;
    };
    request_mode_controls: {
        source: 'admin_env_whitelist';
        global_env: string;
        channel_env_pattern: string;
        global_priority_env: string;
        channel_priority_env_pattern: string;
        default_priority: readonly ChannelRequestMode[];
        default_priority_policy: 'lowest_cost_first';
        mutable_at_runtime: false;
        agent_client_policy: 'diagnostics_only';
        final_gate_command: string;
        smoke_gate_commands: Record<ChannelRequestMode, readonly string[]>;
    };
    defaults: {
        model: GptImageModel;
        response_mode: AgentResponseMode;
        state_backend: AgentStateBackend;
        image_backend: ImageGenerationBackend;
        stream_mode: ImageStreamMode;
        streaming_strategy: ImageStreamingStrategy;
        partial_images: PartialImagesCount;
    };
    limits: {
        max_prompt_length: number;
        max_images: number;
        generate_images: { min: number; max: number };
        edit_images: { min: number; max: number };
        upload_images: { max: number };
        max_upload_mb: number;
        max_total_upload_mb?: number;
        partial_images: { min: number; max: number };
        partial_images_by_backend: Record<ImageGenerationBackend, { min: number; max: number }>;
        upstream_profile: ImageUpstreamProfileId;
        upstream_profile_mixed: boolean;
    };
    force_request_controls: {
        field: 'force_request';
        cli_flag: '--force-request';
        default: false;
        effect: 'skip_local_upstream_profile_size_and_background_validation';
        still_enforced: readonly string[];
        intended_for: readonly string[];
    };
    model_limits: {
        'gpt-image-2': {
            max_edge: number;
            max_pixels: number;
            edge_multiple: number;
            max_aspect: number;
            min_pixels: number;
            size_policy: ImageUpstreamProfile['gptImage2']['sizePolicy'];
            allow_transparent_background: boolean;
            recommended_presets: Array<{ name: string; size: string; purpose: string }>;
            large_image_risk: {
                applies_to: string[];
                guidance: string;
            };
        };
    };
    agent_streaming: {
        generate: {
            supported: false;
            mode: 'non_streaming_only';
            endpoint: string;
        };
        edit: {
            supported: false;
            mode: 'non_streaming_only';
            endpoint: string;
        };
        upstream_sse: {
            supported: true;
            mode: 'internal_upstream_sse';
            endpoint: string;
            request_fields: typeof AGENT_UPSTREAM_SSE_GENERATE_REQUEST_FIELDS;
            request_fields_by_mode: {
                generate: typeof AGENT_UPSTREAM_SSE_GENERATE_REQUEST_FIELDS;
                edit: typeof AGENT_UPSTREAM_SSE_EDIT_REQUEST_FIELDS;
            };
            image_backends: readonly ImageGenerationBackend[];
            enabled_image_backends: readonly ImageGenerationBackend[];
            streaming_strategies: readonly ImageStreamingStrategy[];
            stream_modes: readonly ImageStreamMode[];
            activation_strategies: readonly ImageStreamingStrategy[];
            final_response_contract: 'AgentImageResponse';
        };
        page_sse: {
            supported: true;
            mode: 'form_data_sse';
            endpoint: string;
            contract: 'page_ui_only';
            transport_contract: 'page_form_data_sse';
            auth: {
                required: boolean;
                schemes: PageSseAuthScheme[];
                form_field: 'passwordHash';
            };
            client_request_id: {
                form_field: 'clientRequestId';
                source_header: 'Idempotency-Key';
                max_length: number;
            };
            agent_usage: typeof AGENT_PAGE_SSE_AGENT_USAGE;
        };
    };
    orchestration: {
        supported: true;
        policy: AgentOrchestrationPolicy;
        endpoint: string;
        client_contract: 'intent_only';
        transport_selection: 'server_owned';
        result_mode: 'job_polling';
        hidden_controls: readonly string[];
        diagnostics: {
            job_result: string;
            request_lookup: string;
        };
        current_guidance: string;
    };
    routing_rules: {
        high_resolution_edit: AgentRoutingRule;
        complex_ui_batch: AgentRoutingRule;
        long_image_recovery: AgentRoutingRule;
        agent_generate_small_smoke: AgentRoutingRule;
        page_sse_generate_diagnostics: AgentRoutingRule;
        retry_recovery: {
            reuse_failed_idempotency_key: false;
            new_attempt_guidance: string;
        };
    };
    agent_jobs: {
        supported: true;
        mode: 'job_polling';
        intended_for: string[];
        endpoints: {
            create_generate_job: string;
            get_job: string;
            get_job_result: string;
        };
        states: readonly string[];
        current_guidance: string;
    };
    supported: {
        models: readonly string[];
        output_formats: readonly string[];
        response_modes: readonly string[];
        qualities: readonly string[];
        backgrounds: readonly string[];
        moderations: readonly string[];
        legacy_sizes: readonly string[];
        image_backends: readonly ImageGenerationBackend[];
        enabled_image_backends: readonly ImageGenerationBackend[];
        image_backend_requirements: Record<ImageGenerationBackend, ImageBackendRuntimeRequirement>;
        request_modes: readonly ChannelRequestMode[];
        streaming_strategies: readonly ImageStreamingStrategy[];
        stream_modes: readonly ImageStreamMode[];
    };
    storage: {
        image_storage_mode: string;
        postgres_configured: boolean;
    };
    page_request_diagnostics: {
        supported: true;
        source: 'app_log';
        endpoints: {
            single: string;
            batch: string;
        };
        retention: AgentPageRequestDiagnosticsRetention;
        no_match_hint: string;
    };
    agent_request_diagnostics: {
        supported: true;
        source: 'agent_state';
        endpoints: {
            lookup: string;
            single: string;
        };
        lookup: {
            by_request_id: true;
            by_idempotency_key: true;
        };
        retention: AgentRequestDiagnosticsRetention;
    };
    channel_health_diagnostics: {
        supported: true;
        endpoint: string;
        source: 'in_process_channel_router';
        state_scope: 'process_local';
        billable: false;
    };
    idempotency: {
        required: boolean;
        header: string;
        ttl_seconds: number;
    };
};

export type AgentRoutingRule = {
    when: string[];
    conditions: AgentRoutingCondition;
    endpoint: string;
    transport: AgentRoutingTransport;
    strength: AgentRoutingStrength;
    action: AgentRoutingAction;
    reason: string;
};

export type AgentRoutingCondition = {
    operation: 'generate' | 'edit' | 'generate_or_edit';
    explicit_page_sse?: boolean;
    max_edge?: {
        operator: 'gt' | 'lte';
        value: number;
    };
    batch?: boolean;
    single_request?: boolean;
    complex_ui?: boolean;
    long_image?: boolean;
    resume_or_recover?: boolean;
};

export type AgentRoutingAction = {
    endpoint: string;
    transport: AgentRoutingTransport;
    strength: AgentRoutingStrength;
    fallback_endpoint?: string;
    fallback_mode?: 'manual_after_diagnosis' | 'fix_request_before_retry';
    requires_new_idempotency_key_on_retry: boolean;
    no_automatic_fallback: boolean;
};

type FieldErrors = Record<string, string>;

function isOneOf<T extends readonly string[]>(value: string, allowed: T): value is T[number] {
    return (allowed as readonly string[]).includes(value);
}

function readStringField(body: Record<string, unknown>, field: string, fallback?: string): string | undefined {
    const value = body[field];
    if (value === undefined || value === null) return fallback;
    return typeof value === 'string' ? value : undefined;
}

function readIntegerField(
    body: Record<string, unknown>,
    field: string,
    fallback: number,
    min: number,
    max: number,
    fields: FieldErrors
): number {
    const value = body[field];
    if (value === undefined || value === null || value === '') return fallback;
    const parsed =
        typeof value === 'number' ? value : typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : NaN;
    if (!Number.isInteger(parsed) || parsed < min || parsed > max) {
        fields[field] = `必须是 ${min}${max} 之间的整数`;
        return fallback;
    }
    return parsed;
}

function validatePrompt(value: unknown, fields: FieldErrors): string {
    if (typeof value !== 'string' || value.trim().length === 0) {
        fields.prompt = '必填';
        return '';
    }
    if (value.length > MAX_PROMPT_LENGTH) {
        fields.prompt = `长度不能超过 ${MAX_PROMPT_LENGTH} 个字符`;
    }
    return value;
}

function readModel(body: Record<string, unknown>, fields: FieldErrors): GptImageModel {
    const value = readStringField(body, 'model', 'gpt-image-2');
    if (!value || !isOneOf(value, AGENT_MODELS)) {
        fields.model = `必须是以下值之一:${AGENT_MODELS.join(', ')}`;
        return 'gpt-image-2';
    }
    return value;
}

function readSize(
    body: Record<string, unknown>,
    model: GptImageModel,
    fields: FieldErrors,
    fallback: string,
    upstreamProfile: Pick<ImageUpstreamProfile, 'gptImage2'>,
    options: { forceRequest?: boolean } = {}
): string {
    const value = readStringField(body, 'size', fallback);
    if (!value) {
        fields.size = '必须是字符串';
        return fallback;
    }
    if (model !== 'gpt-image-2' && !isOneOf(value, AGENT_LEGACY_SIZES)) {
        fields.size = `${model} 的 size 必须是以下值之一:${AGENT_LEGACY_SIZES.join(', ')}`;
        return fallback;
    }
    if (model === 'gpt-image-2' && value !== 'auto') {
        const match = /^(\d+)x(\d+)$/.exec(value);
        if (!match) {
            fields.size = '必须是 auto 或 WxH 格式的尺寸值';
            return fallback;
        }
        const validation =
            options.forceRequest || upstreamProfile.gptImage2.sizePolicy === 'positive-integer'
                ? validatePositiveIntegerImageSize(Number(match[1]), Number(match[2]))
                : validateGptImage2Size(Number(match[1]), Number(match[2]));
        if (!validation.valid) {
            fields.size = validation.reason;
            return fallback;
        }
    }
    return value;
}

function readOutputFormat(body: Record<string, unknown>, fields: FieldErrors): ValidOutputFormat {
    const rawValue = readStringField(body, 'output_format', AGENT_DEFAULT_OUTPUT_FORMAT);
    const normalized = rawValue?.toLowerCase() === 'jpg' ? 'jpeg' : rawValue?.toLowerCase();
    if (!normalized || !isOneOf(normalized, AGENT_OUTPUT_FORMATS)) {
        fields.output_format = `必须是以下值之一:${AGENT_OUTPUT_FORMATS.join(', ')}`;
        return 'png';
    }
    return normalized;
}

function readResponseMode(body: Record<string, unknown>, fields: FieldErrors): AgentResponseMode {
    const value = readStringField(body, 'response_mode', 'path');
    if (!value || !isOneOf(value, AGENT_RESPONSE_MODES)) {
        fields.response_mode = `必须是以下值之一:${AGENT_RESPONSE_MODES.join(', ')}`;
        return 'path';
    }
    return value;
}

function readAgentImageBackend(body: Record<string, unknown>, fields: FieldErrors): ImageGenerationBackend {
    const rawValue = body.image_backend;
    if (rawValue !== undefined && rawValue !== null && typeof rawValue !== 'string') {
        fields.image_backend = '必须是字符串';
        return 'images-api';
    }
    const value = readStringField(body, 'image_backend', 'images-api');
    if (!value) return 'images-api';
    try {
        return parseImageGenerationBackendValue(value);
    } catch (error) {
        fields.image_backend = error instanceof Error ? error.message : 'image_backend 无效';
        return 'images-api';
    }
}

function readAgentStreamingStrategy(body: Record<string, unknown>, fields: FieldErrors): ImageStreamingStrategy {
    const rawValue = body.streaming_strategy;
    if (rawValue !== undefined && rawValue !== null && typeof rawValue !== 'string') {
        fields.streaming_strategy = '必须是字符串';
        return 'auto';
    }
    const value = readStringField(body, 'streaming_strategy', 'auto');
    if (!value) return 'auto';
    try {
        return parseImageStreamingStrategyValue(value);
    } catch (error) {
        fields.streaming_strategy = error instanceof Error ? error.message : 'streaming_strategy 无效';
        return 'auto';
    }
}

function readAgentStreamMode(body: Record<string, unknown>, fields: FieldErrors): ImageStreamMode {
    const rawValue = body.stream_mode;
    if (rawValue !== undefined && rawValue !== null && typeof rawValue !== 'string') {
        fields.stream_mode = '必须是字符串';
        return 'auto';
    }
    if ((rawValue === undefined || rawValue === null || rawValue === '') && body.streaming_strategy === 'off') {
        return 'non_stream';
    }
    const value = readStringField(body, 'stream_mode', 'auto');
    if (!value) return 'auto';
    try {
        return parseImageStreamModeValue(value);
    } catch (error) {
        fields.stream_mode = error instanceof Error ? error.message : 'stream_mode 无效';
        return 'auto';
    }
}

function validateAgentImageUpstreamStrategy(input: {
    imageBackend: ImageGenerationBackend;
    streamMode: ImageStreamMode;
    streamingStrategy: ImageStreamingStrategy;
    fields: FieldErrors;
}) {
    if (input.streamMode === 'non_stream') return;
    try {
        resolveImageStreamEnabled({
            imageBackend: input.imageBackend,
            requestedStream: true,
            streamingStrategy: input.streamingStrategy
        });
    } catch (error) {
        input.fields.streaming_strategy =
            error instanceof Error ? error.message : 'streaming_strategy 与 image_backend 不兼容';
    }
}

function readPartialImagesForBackend(
    body: Record<string, unknown>,
    imageBackend: ImageGenerationBackend,
    fields: FieldErrors,
    profile: ImageUpstreamProfile
): PartialImagesCount {
    const limits = getPartialImagesRangeForBackend(profile, imageBackend);
    const fallback = clampDefaultPartialImages(limits);
    return readIntegerField(body, 'partial_images', fallback, limits.min, limits.max, fields) as PartialImagesCount;
}

function readQuality(body: Record<string, unknown>, fields: FieldErrors): AgentQuality {
    const value = readStringField(body, 'quality', 'high');
    if (!value || !isOneOf(value, AGENT_QUALITIES)) {
        fields.quality = `必须是以下值之一:${AGENT_QUALITIES.join(', ')}`;
        return 'high';
    }
    return value;
}

function readBackground(body: Record<string, unknown>, fields: FieldErrors): AgentBackground {
    const value = readStringField(body, 'background', 'auto');
    if (!value || !isOneOf(value, AGENT_BACKGROUNDS)) {
        fields.background = `必须是以下值之一:${AGENT_BACKGROUNDS.join(', ')}`;
        return 'auto';
    }
    return value;
}

function readModeration(body: Record<string, unknown>, fields: FieldErrors): AgentModeration {
    const value = readStringField(body, 'moderation', 'auto');
    if (!value || !isOneOf(value, AGENT_MODERATIONS)) {
        fields.moderation = `必须是以下值之一:${AGENT_MODERATIONS.join(', ')}`;
        return 'auto';
    }
    return value;
}

function readOptionalStringField(
    body: Record<string, unknown>,
    field: string,
    fields: FieldErrors,
    options: { maxLength?: number } = {}
): string | undefined {
    const value = body[field];
    if (value === undefined || value === null || value === '') return undefined;
    if (typeof value !== 'string') {
        fields[field] = '必须是字符串';
        return undefined;
    }
    const trimmed = value.trim();
    if (!trimmed) {
        fields[field] = '必须是非空字符串';
        return undefined;
    }
    if (options.maxLength !== undefined && trimmed.length > options.maxLength) {
        fields[field] = `长度不能超过 ${options.maxLength} 个字符`;
        return undefined;
    }
    return trimmed;
}

function readOptionalBooleanField(
    body: Record<string, unknown>,
    field: string,
    fields: FieldErrors
): boolean | undefined {
    const value = body[field];
    if (value === undefined || value === null || value === '') return undefined;
    if (typeof value === 'boolean') return value;
    fields[field] = '必须是布尔值';
    return undefined;
}

function readAgentResponsesModel(
    body: Record<string, unknown>,
    imageBackend: ImageGenerationBackend,
    fields: FieldErrors
): string | undefined {
    const value = readOptionalStringField(body, 'responsesModel', fields, { maxLength: 128 });
    if (value && imageBackend !== 'responses-image-generation') {
        fields.responsesModel = '仅适用于 image_backend=responses-image-generation';
    }
    return value;
}

function readAgentThinking(body: Record<string, unknown>, fields: FieldErrors): AgentGenerateRequest['thinking'] {
    const value = readOptionalStringField(body, 'thinking', fields);
    if (value === undefined) return undefined;
    if (['minimal', 'none', 'low', 'medium', 'high', 'xhigh'].includes(value)) {
        return value as AgentGenerateRequest['thinking'];
    }
    fields.thinking = '必须是 minimal、none、low、medium、high 或 xhigh';
    return undefined;
}

function readOutputCompression(
    body: Record<string, unknown>,
    outputFormat: ValidOutputFormat,
    fields: FieldErrors
): number | undefined {
    const value = body.output_compression;
    if (value === undefined || value === null || value === '') {
        return outputFormat === 'png' ? undefined : AGENT_DEFAULT_LOSSY_OUTPUT_COMPRESSION;
    }
    if (outputFormat === 'png') {
        fields.output_compression = '仅适用于 jpeg 或 webp 输出';
        return undefined;
    }
    const parsed =
        typeof value === 'number' ? value : typeof value === 'string' && /^\d+$/.test(value) ? Number(value) : NaN;
    if (!Number.isInteger(parsed) || parsed < 0 || parsed > 100) {
        fields.output_compression = '必须是 0 到 100 之间的整数';
        return undefined;
    }
    return parsed;
}

export function validateAgentGenerateRequest(body: unknown): AgentGenerateRequest {
    if (typeof body !== 'object' || body === null || Array.isArray(body)) {
        throw new RequestValidationError('请求正文必须是 JSON 对象。');
    }
    const objectBody = body as Record<string, unknown>;
    const fields: FieldErrors = {};
    const upstreamLimits = buildAgentUpstreamLimits(process.env);
    const model = readModel(objectBody, fields);
    const prompt = validatePrompt(objectBody.prompt, fields);
    const n = readIntegerField(objectBody, 'n', 1, 1, MAX_IMAGE_COUNT, fields);
    const forceRequest = readOptionalBooleanField(objectBody, 'force_request', fields);
    const size = readSize(objectBody, model, fields, '1024x1024', upstreamLimits.profile, {
        forceRequest: forceRequest === true
    });
    const quality = readQuality(objectBody, fields);
    const outputFormat = readOutputFormat(objectBody, fields);
    const outputCompression = readOutputCompression(objectBody, outputFormat, fields);
    const background = readBackground(objectBody, fields);
    const moderation = readModeration(objectBody, fields);
    const responseMode = readResponseMode(objectBody, fields);
    const imageBackend = readAgentImageBackend(objectBody, fields);
    const streamMode = readAgentStreamMode(objectBody, fields);
    const streamingStrategy = readAgentStreamingStrategy(objectBody, fields);
    const partialImages = readPartialImagesForBackend(objectBody, imageBackend, fields, upstreamLimits.profile);
    const responsesModel = readAgentResponsesModel(objectBody, imageBackend, fields);
    const thinking = readAgentThinking(objectBody, fields);
    const promptOptimization = readOptionalBooleanField(objectBody, 'promptOptimization', fields);
    const forceWeb = readOptionalBooleanField(objectBody, 'force_web', fields);
    validateAgentImageUpstreamStrategy({ imageBackend, streamMode, streamingStrategy, fields });

    if (Object.keys(fields).length > 0) {
        throw new RequestValidationError(JSON.stringify({ fields }), 422);
    }

    return {
        model,
        prompt,
        n,
        size,
        quality,
        output_format: outputFormat,
        ...(outputCompression !== undefined ? { output_compression: outputCompression } : {}),
        background,
        moderation,
        response_mode: responseMode,
        image_backend: imageBackend,
        stream_mode: streamMode,
        streaming_strategy: streamingStrategy,
        partial_images: partialImages,
        ...(responsesModel ? { responsesModel } : {}),
        ...(thinking ? { thinking } : {}),
        ...(promptOptimization !== undefined ? { promptOptimization } : {}),
        ...(forceWeb !== undefined ? { force_web: forceWeb } : {}),
        ...(forceRequest !== undefined ? { force_request: forceRequest } : {})
    };
}

export function readAgentStateBackend(env: Record<string, string | undefined>): AgentStateBackend {
    const backend = env.AGENT_STATE_BACKEND?.trim().toLowerCase();
    if (!backend) return 'sqlite';
    if (backend === 'memory' || backend === 'sqlite' || backend === 'postgres') return backend;
    throw new RequestValidationError('AGENT_STATE_BACKEND 必须是 memory、sqlite 或 postgres。', 500);
}

export function readAgentRequestTtlSeconds(env: Record<string, string | undefined>): number {
    return readPositiveIntegerEnv(env, 'AGENT_REQUEST_TTL_SECONDS', AGENT_DEFAULT_REQUEST_TTL_SECONDS);
}

export function readAgentLeaseMs(env: Record<string, string | undefined>): number {
    return readPositiveIntegerEnv(env, 'AGENT_REQUEST_LEASE_MS', AGENT_DEFAULT_LEASE_MS);
}

export function readAgentRecoveryIntervalMs(env: Record<string, string | undefined>): number {
    return readPositiveIntegerEnv(env, 'AGENT_RECOVERY_INTERVAL_MS', AGENT_DEFAULT_RECOVERY_INTERVAL_MS);
}

export function readAgentSqlitePath(env: Record<string, string | undefined>): string {
    return env.AGENT_SQLITE_PATH?.trim() || AGENT_DEFAULT_SQLITE_PATH;
}

export function readAgentPublicBaseUrl(env: Record<string, string | undefined>): string {
    const value = env.AGENT_PUBLIC_BASE_URL?.trim();
    if (!value) return '/';
    let parsed: URL;
    try {
        parsed = new URL(value);
    } catch {
        throw new RequestValidationError('AGENT_PUBLIC_BASE_URL 格式无效。', 500);
    }
    if (parsed.protocol !== 'http:' && parsed.protocol !== 'https:') {
        throw new RequestValidationError('AGENT_PUBLIC_BASE_URL 必须是 http 或 https URL。', 500);
    }
    if (parsed.username || parsed.password || parsed.search || parsed.hash) {
        throw new RequestValidationError('AGENT_PUBLIC_BASE_URL 不能包含凭据、查询参数或片段。', 500);
    }
    return parsed.toString().replace(/\/$/, '');
}

export function validateOptionalAgentApiBaseUrl(baseUrl: string | undefined): void {
    if (baseUrl) validateApiBaseUrl(baseUrl);
}

export function buildAgentAuthCapabilities(env: Record<string, string | undefined>): AgentCapabilities['auth'] {
    if (env.AGENT_API_TOKEN?.trim()) {
        return { required: true, schemes: ['bearer'] };
    }
    if (env.APP_PASSWORD?.trim()) {
        return { required: true, schemes: ['x-app-password-hash'] };
    }
    return { required: false, schemes: [] };
}

export function buildPageSseAuthCapabilities(
    env: Record<string, string | undefined>
): AgentCapabilities['agent_streaming']['page_sse']['auth'] {
    return {
        required: Boolean(env.APP_PASSWORD?.trim()),
        schemes: env.APP_PASSWORD?.trim() ? ['form-password-hash'] : [],
        form_field: 'passwordHash'
    };
}

export function buildPageRequestDiagnosticsCapabilities(
    env: Record<string, string | undefined>
): AgentCapabilities['page_request_diagnostics'] {
    const retention = buildPageRequestDiagnosticsRetention(env);
    return {
        supported: true,
        source: 'app_log',
        endpoints: {
            single: AGENT_ENDPOINTS.page_request_diagnostics,
            batch: AGENT_ENDPOINTS.page_request_diagnostics_batch
        },
        retention,
        no_match_hint: AGENT_PAGE_REQUEST_DIAGNOSTICS_NO_MATCH_HINT
    };
}

export function buildPageRequestDiagnosticsRetention(
    env: Record<string, string | undefined>
): AgentPageRequestDiagnosticsRetention {
    return {
        ...readAppLogRetentionMetadata(env),
        bounded: true,
        not_agent_state_backend: true
    };
}

export function buildAgentRequestDiagnosticsCapabilities(
    env: Record<string, string | undefined>
): AgentCapabilities['agent_request_diagnostics'] {
    return {
        supported: true,
        source: 'agent_state',
        endpoints: {
            lookup: AGENT_ENDPOINTS.agent_request_diagnostics_lookup,
            single: AGENT_ENDPOINTS.agent_request_diagnostics
        },
        lookup: {
            by_request_id: true,
            by_idempotency_key: true
        },
        retention: buildAgentRequestDiagnosticsRetention(env)
    };
}

export function buildAgentRequestDiagnosticsRetention(
    env: Record<string, string | undefined>
): AgentRequestDiagnosticsRetention {
    return {
        storage: 'agent_state',
        ttl_seconds: readAgentRequestTtlSeconds(env),
        bounded: true,
        loss_modes: ['request_expired_by_ttl', 'artifact_deleted_or_purged', 'state_backend_reset']
    };
}

export function buildPageRequestDiagnosticsNoMatchNote(input: {
    matchedLogCount: number;
    retention: AgentPageRequestDiagnosticsRetention;
}): AgentPageRequestDiagnosticsNote | undefined {
    if (input.matchedLogCount !== 0) return undefined;
    return {
        code: 'no_matching_logs_in_retention_window',
        message: AGENT_PAGE_REQUEST_DIAGNOSTICS_NO_MATCH_HINT,
        retention: input.retention
    };
}

function readEnabledImageBackends(
    requirements: Record<ImageGenerationBackend, ImageBackendRuntimeRequirement>
): ImageGenerationBackend[] {
    return requirements['responses-image-generation'].enabled
        ? ['images-api', 'responses-image-generation']
        : ['images-api'];
}

function buildImageBackendRequirements(
    env: Record<string, string | undefined>
): Record<ImageGenerationBackend, ImageBackendRuntimeRequirement> {
    const responsesMissingEnv = readResponsesImageBackendMissingEnv(env);
    return {
        'images-api': {
            supported: true,
            enabled: true,
            required_env: [],
            missing_env: []
        },
        'responses-image-generation': {
            supported: true,
            enabled: responsesMissingEnv.length === 0,
            required_env: ['ENABLE_RESPONSES_IMAGE_BACKEND', 'OPENAI_RESPONSES_API_MODEL'],
            missing_env: responsesMissingEnv
        }
    };
}

function readResponsesImageBackendMissingEnv(env: Record<string, string | undefined>): string[] {
    const missing: string[] = [];
    if (!readBooleanEnv(env, 'ENABLE_RESPONSES_IMAGE_BACKEND')) {
        missing.push('ENABLE_RESPONSES_IMAGE_BACKEND');
    }
    if (!env.OPENAI_RESPONSES_API_MODEL?.trim()) {
        missing.push('OPENAI_RESPONSES_API_MODEL');
    }
    return missing;
}

function readPositiveIntegerEnv(env: Record<string, string | undefined>, fieldName: string, fallback: number): number {
    try {
        return readPositiveIntegerFromEnv(env, fieldName, fallback, {
            messages: CHINESE_POSITIVE_INTEGER_MESSAGES
        });
    } catch (error) {
        throw new RequestValidationError(error instanceof Error ? error.message : `${fieldName} 必须是正整数。`, 500);
    }
}

export function buildAgentCapabilities(env: Record<string, string | undefined>): AgentCapabilities {
    const imageBackendRequirements = buildImageBackendRequirements(env);
    const enabledImageBackends = readEnabledImageBackends(imageBackendRequirements);
    const upstreamLimits = buildAgentUpstreamLimits(env);
    const partialImagesByBackend = buildAgentPartialImagesByBackend(upstreamLimits.profile);
    const defaultPartialImages = clampDefaultPartialImages(partialImagesByBackend['images-api']);
    return {
        api_version: AGENT_API_VERSION,
        schema_version: AGENT_SCHEMA_VERSION,
        auth: buildAgentAuthCapabilities(env),
        endpoints: { ...AGENT_ENDPOINTS },
        image_transport: summarizeOpenAIImageTransport(env),
        upstream_profile: upstreamLimits.summary,
        upstream_request_headers: buildAgentUpstreamRequestHeadersCapabilities(env),
        request_mode_controls: buildAgentRequestModeControlsCapabilities(),
        defaults: {
            model: 'gpt-image-2',
            response_mode: 'path',
            state_backend: readAgentStateBackend(env),
            image_backend: 'images-api',
            stream_mode: 'auto',
            streaming_strategy: 'auto',
            partial_images: defaultPartialImages
        },
        limits: {
            max_prompt_length: MAX_PROMPT_LENGTH,
            max_images: Math.min(upstreamLimits.profile.generateCount.max, upstreamLimits.profile.editCount.max),
            generate_images: upstreamLimits.profile.generateCount,
            edit_images: upstreamLimits.profile.editCount,
            upload_images: { max: upstreamLimits.profile.upload.maxImages },
            max_upload_mb: upstreamLimits.profile.upload.maxSingleBytes / 1024 / 1024,
            ...(upstreamLimits.profile.upload.maxTotalBytes !== undefined
                ? { max_total_upload_mb: upstreamLimits.profile.upload.maxTotalBytes / 1024 / 1024 }
                : {}),
            partial_images: upstreamLimits.profile.partialImages,
            partial_images_by_backend: partialImagesByBackend,
            upstream_profile: upstreamLimits.profile.id,
            upstream_profile_mixed: upstreamLimits.summary.serverProfileMixed
        },
        force_request_controls: {
            field: 'force_request',
            cli_flag: '--force-request',
            default: false,
            effect: 'skip_local_upstream_profile_size_and_background_validation',
            still_enforced: [
                'authentication',
                'idempotency_key',
                'billable_confirmation',
                'api_base_url_safety',
                'channel_request_mode_whitelist',
                'image_count_limits',
                'partial_image_limits',
                'non_gpt_image2_size_allowlist',
                'positive_integer_size_syntax',
                'upload_file_size_and_type',
                'mask_integrity_checks'
            ],
            intended_for: [
                'upstream_compatibility_probe',
                'administrator_confirmed_provider_contract',
                'requests_where_real_upstream_should_decide'
            ]
        },
        model_limits: {
            'gpt-image-2': {
                max_edge: GPT_IMAGE_2_MAX_EDGE,
                max_pixels: GPT_IMAGE_2_MAX_PIXELS,
                edge_multiple: GPT_IMAGE_2_EDGE_MULTIPLE,
                max_aspect: GPT_IMAGE_2_MAX_ASPECT,
                min_pixels: GPT_IMAGE_2_MIN_PIXELS,
                size_policy: upstreamLimits.profile.gptImage2.sizePolicy,
                allow_transparent_background: upstreamLimits.profile.gptImage2.allowTransparentBackground,
                recommended_presets: [
                    { name: 'square', size: '2048x2048', purpose: '通用正方形构图' },
                    { name: 'landscape', size: '3072x2048', purpose: '横向宽幅构图' },
                    { name: 'portrait', size: '2048x3072', purpose: '纵向主体构图' }
                ],
                large_image_risk: {
                    applies_to: ['max_edge>2048', 'long_running_upstream'],
                    guidance: '大尺寸请求可能耗时数分钟;失败应归类为上游长耗时风险,不代表低负载路径不可用。'
                }
            }
        },
        agent_streaming: {
            generate: {
                supported: false,
                mode: 'non_streaming_only',
                endpoint: AGENT_ENDPOINTS.generate
            },
            edit: {
                supported: false,
                mode: 'non_streaming_only',
                endpoint: AGENT_ENDPOINTS.edit
            },
            upstream_sse: {
                supported: true,
                mode: 'internal_upstream_sse',
                endpoint: AGENT_ENDPOINTS.generate,
                request_fields: AGENT_UPSTREAM_SSE_GENERATE_REQUEST_FIELDS,
                request_fields_by_mode: {
                    generate: AGENT_UPSTREAM_SSE_GENERATE_REQUEST_FIELDS,
                    edit: AGENT_UPSTREAM_SSE_EDIT_REQUEST_FIELDS
                },
                image_backends: AGENT_IMAGE_BACKENDS,
                enabled_image_backends: enabledImageBackends,
                streaming_strategies: AGENT_STREAMING_STRATEGIES,
                stream_modes: AGENT_STREAM_MODES,
                activation_strategies: AGENT_UPSTREAM_SSE_ACTIVATION_STRATEGIES,
                final_response_contract: 'AgentImageResponse'
            },
            page_sse: {
                supported: true,
                mode: 'form_data_sse',
                endpoint: '/api/images',
                contract: 'page_ui_only',
                transport_contract: 'page_form_data_sse',
                auth: buildPageSseAuthCapabilities(env),
                client_request_id: {
                    form_field: 'clientRequestId',
                    source_header: 'Idempotency-Key',
                    max_length: PAGE_SSE_CLIENT_REQUEST_ID_MAX_LENGTH
                },
                agent_usage: AGENT_PAGE_SSE_AGENT_USAGE
            }
        },
        orchestration: {
            supported: true,
            policy: 'server_orchestrated_generate_v1',
            endpoint: AGENT_ENDPOINTS.create_image_request,
            client_contract: 'intent_only',
            transport_selection: 'server_owned',
            result_mode: 'job_polling',
            hidden_controls: ['transport', 'route_mode', 'client_endpoint_selection'],
            diagnostics: {
                job_result: AGENT_ENDPOINTS.job_result,
                request_lookup: AGENT_ENDPOINTS.agent_request_diagnostics_lookup
            },
            current_guidance:
                'Agent 客户端默认只提交生成意图到 /api/agent/image-requests;服务端负责选择内部执行路径、上游策略和轮询结果。显式 /api/images、Agent JSON 或 job endpoint 仅作为诊断/兼容入口。'
        },
        routing_rules: {
            high_resolution_edit: {
                when: ['operation=edit', 'max_edge>2048'],
                conditions: {
                    operation: 'edit',
                    max_edge: { operator: 'gt', value: 2048 }
                },
                endpoint: '/api/images',
                transport: 'page_sse',
                strength: 'default',
                action: {
                    endpoint: '/api/images',
                    transport: 'page_sse',
                    strength: 'default',
                    fallback_endpoint: AGENT_ENDPOINTS.edit,
                    fallback_mode: 'manual_after_diagnosis',
                    requires_new_idempotency_key_on_retry: true,
                    no_automatic_fallback: true
                },
                reason: 'High-resolution edit uses the page form-data SSE endpoint because Agent edit has a fixed output contract; if streaming has issues, diagnose first and explicitly fall back to Agent edit.'
            },
            complex_ui_batch: {
                when: ['operation=generate_or_edit', 'complex_ui=true', 'batch=true'],
                conditions: {
                    operation: 'generate_or_edit',
                    complex_ui: true,
                    batch: true
                },
                endpoint: '/api/images',
                transport: 'page_sse',
                strength: 'recommended',
                action: {
                    endpoint: '/api/images',
                    transport: 'page_sse',
                    strength: 'recommended',
                    fallback_mode: 'manual_after_diagnosis',
                    requires_new_idempotency_key_on_retry: true,
                    no_automatic_fallback: true
                },
                reason: 'Page form-data SSE keeps long-running image production observable and recoverable for complex UI batches.'
            },
            long_image_recovery: {
                when: ['operation=generate_or_edit', 'long_image=true', 'resume_or_recover=true'],
                conditions: {
                    operation: 'generate_or_edit',
                    long_image: true,
                    resume_or_recover: true
                },
                endpoint: '/api/images',
                transport: 'page_sse',
                strength: 'recommended',
                action: {
                    endpoint: '/api/images',
                    transport: 'page_sse',
                    strength: 'recommended',
                    fallback_mode: 'manual_after_diagnosis',
                    requires_new_idempotency_key_on_retry: true,
                    no_automatic_fallback: true
                },
                reason: 'Page form-data SSE exposes partial progress and final-image diagnostics needed for long-image recovery runs.'
            },
            agent_generate_small_smoke: {
                when: ['operation=generate', 'max_edge<=2048', 'single_request=true'],
                conditions: {
                    operation: 'generate',
                    max_edge: { operator: 'lte', value: 2048 },
                    single_request: true
                },
                endpoint: AGENT_ENDPOINTS.generate,
                transport: 'agent_json',
                strength: 'explicit',
                action: {
                    endpoint: AGENT_ENDPOINTS.generate,
                    transport: 'agent_json',
                    strength: 'explicit',
                    requires_new_idempotency_key_on_retry: true,
                    no_automatic_fallback: true
                },
                reason: 'Agent JSON generate remains available for compatibility and explicit diagnostics; ordinary generate clients should use orchestration.endpoint.'
            },
            page_sse_generate_diagnostics: {
                when: ['operation=generate', 'explicit_page_sse=true'],
                conditions: {
                    operation: 'generate',
                    explicit_page_sse: true,
                    single_request: true
                },
                endpoint: '/api/images',
                transport: 'page_sse',
                strength: 'explicit',
                action: {
                    endpoint: '/api/images',
                    transport: 'page_sse',
                    strength: 'explicit',
                    fallback_endpoint: AGENT_ENDPOINTS.create_image_request,
                    fallback_mode: 'manual_after_diagnosis',
                    requires_new_idempotency_key_on_retry: true,
                    no_automatic_fallback: true
                },
                reason: 'Page form-data SSE is available for explicit page-workbench or diagnostic generate runs; ordinary generate clients should use orchestration.endpoint.'
            },
            retry_recovery: {
                reuse_failed_idempotency_key: false,
                new_attempt_guidance:
                    'A failed terminal Agent request only replays the stored failure. Diagnose the failure, then create a new business operation with a new Idempotency-Key.'
            }
        },
        agent_jobs: {
            supported: true,
            mode: 'job_polling',
            intended_for: [
                'explicit_job_route',
                'manual_after_diagnosis',
                'long_running_upstream_when_page_sse_not_selected'
            ],
            endpoints: { ...AGENT_JOB_ENDPOINTS },
            states: AGENT_JOB_STATES,
            current_guidance:
                'Agent 客户端默认使用 orchestration.endpoint;直接创建 job 是兼容和诊断入口。当前执行模型为同实例后台任务,不是跨实例持久队列。'
        },
        supported: {
            models: AGENT_MODELS,
            output_formats: AGENT_OUTPUT_FORMATS,
            response_modes: AGENT_RESPONSE_MODES,
            qualities: AGENT_QUALITIES,
            backgrounds: AGENT_BACKGROUNDS,
            moderations: AGENT_MODERATIONS,
            legacy_sizes: AGENT_LEGACY_SIZES,
            image_backends: AGENT_IMAGE_BACKENDS,
            enabled_image_backends: enabledImageBackends,
            image_backend_requirements: imageBackendRequirements,
            request_modes: CHANNEL_REQUEST_MODES,
            streaming_strategies: AGENT_STREAMING_STRATEGIES,
            stream_modes: AGENT_STREAM_MODES
        },
        storage: {
            image_storage_mode: env.NEXT_PUBLIC_IMAGE_STORAGE_MODE || (env.VERCEL === '1' ? 'indexeddb' : 'fs'),
            postgres_configured: Boolean(env.AGENT_DATABASE_URL || env.AGENT_DB_PASSWORD || env.AGENT_DB_PASSWORD_FILE)
        },
        page_request_diagnostics: buildPageRequestDiagnosticsCapabilities(env),
        agent_request_diagnostics: buildAgentRequestDiagnosticsCapabilities(env),
        channel_health_diagnostics: {
            supported: true,
            endpoint: AGENT_ENDPOINTS.channel_health_diagnostics,
            source: 'in_process_channel_router',
            state_scope: 'process_local',
            billable: false
        },
        idempotency: {
            required: true,
            header: 'Idempotency-Key',
            ttl_seconds: readAgentRequestTtlSeconds(env)
        }
    };
}

function buildAgentRequestModeControlsCapabilities(): AgentCapabilities['request_mode_controls'] {
    return {
        source: CHANNEL_REQUEST_MODE_ADMIN_CONTROL.source,
        global_env: CHANNEL_REQUEST_MODE_ADMIN_CONTROL.globalEnv,
        channel_env_pattern: CHANNEL_REQUEST_MODE_ADMIN_CONTROL.channelEnvPattern,
        global_priority_env: CHANNEL_REQUEST_MODE_ADMIN_CONTROL.globalPriorityEnv,
        channel_priority_env_pattern: CHANNEL_REQUEST_MODE_ADMIN_CONTROL.channelPriorityEnvPattern,
        default_priority: CHANNEL_REQUEST_MODE_ADMIN_CONTROL.defaultPriority,
        default_priority_policy: CHANNEL_REQUEST_MODE_ADMIN_CONTROL.defaultPriorityPolicy,
        mutable_at_runtime: CHANNEL_REQUEST_MODE_ADMIN_CONTROL.mutableAtRuntime,
        agent_client_policy: 'diagnostics_only',
        final_gate_command: CHANNEL_REQUEST_MODE_ADMIN_CONTROL.finalGateCommand,
        smoke_gate_commands: CHANNEL_REQUEST_MODE_ADMIN_CONTROL.smokeGateCommands
    };
}

function buildAgentUpstreamRequestHeadersCapabilities(
    env: Record<string, string | undefined>
): AgentCapabilities['upstream_request_headers'] {
    const channelSummary = getChannelPoolSummary(parseChannelPoolConfig(env));
    return {
        default: summarizeUpstreamRequestHeaders(undefined, env),
        channels: channelSummary.channels.map((channel) => ({
            id: channel.id,
            upstream_proxy: channel.upstreamProxy,
            request_modes: channel.requestModes,
            request_mode_priority: channel.requestModePriority,
            request_headers: channel.requestHeaders
        }))
    };
}

function buildAgentUpstreamLimits(env: Record<string, string | undefined>): {
    profile: ImageUpstreamProfile;
    summary: ImageUpstreamProfileSummary;
} {
    const serverProfiles = readServerProfiles(env);
    const summary = summarizeImageUpstreamProfile({ serverProfiles });
    return {
        profile: summary.activeConstraints,
        summary
    };
}

function readServerProfiles(env: Record<string, string | undefined>): ImageUpstreamProfile[] {
    return getChannelPoolSummary(parseChannelPoolConfig(env)).channels.map((channel) => channel.effectiveProfile);
}

function clampDefaultPartialImages(limits: ImageUpstreamProfile['partialImages']): PartialImagesCount {
    return clampIntegerToRange(AGENT_DEFAULT_PARTIAL_IMAGES, limits) as PartialImagesCount;
}

function buildAgentPartialImagesByBackend(
    profile: ImageUpstreamProfile
): Record<ImageGenerationBackend, { min: number; max: number }> {
    return {
        'images-api': getPartialImagesRangeForBackend(profile, 'images-api'),
        'responses-image-generation': getPartialImagesRangeForBackend(profile, 'responses-image-generation')
    };
}