-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathhelper.go
More file actions
1264 lines (1187 loc) · 40.3 KB
/
Copy pathhelper.go
File metadata and controls
1264 lines (1187 loc) · 40.3 KB
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
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
"github.com/gorilla/websocket"
)
func (r relayProfile) needsLocalRelayProxy() bool {
return r.Protocol == "responses" && (disablesImageGeneration(r) || usesSeparateImageGenerationAPI(r))
}
func (r *launcherRuntime) runtimeSettingsSnapshot() backendSettings {
r.settingsMu.RLock()
defer r.settingsMu.RUnlock()
return r.settings
}
func (r *launcherRuntime) setRuntimeSettings(settings backendSettings) {
r.settingsMu.Lock()
r.settings = settings
r.settingsMu.Unlock()
}
func (r *launcherRuntime) relaySettingsForRequest() backendSettings {
settings := r.runtimeSettingsSnapshot()
return loadRuntimeRelaySettings(settings)
}
func (r *launcherRuntime) startHelper(helperPort uint16) error {
mux := http.NewServeMux()
mux.HandleFunc("/", r.handleHelperHTTP)
server := &http.Server{Addr: fmt.Sprintf("127.0.0.1:%d", helperPort), Handler: mux}
listener, err := net.Listen("tcp", server.Addr)
if err != nil {
return err
}
r.helper = server
r.helperURL = "http://" + server.Addr
appendDiagnosticLog("helper.listening", map[string]any{"helper_port": helperPort, "address": r.helperURL})
go func() {
if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
appendDiagnosticLog("helper.failed", map[string]any{"helper_port": helperPort, "error": err.Error()})
}
}()
return nil
}
func (r *launcherRuntime) shutdownHelper() {
if r.helper == nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = r.helper.Shutdown(ctx)
appendDiagnosticLog("helper.shutdown", map[string]any{"address": r.helperURL})
}
func (r *launcherRuntime) startRelayProxy(port uint16) error {
mux := http.NewServeMux()
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodOptions {
writeCORSHeaders(w)
w.WriteHeader(http.StatusNoContent)
return
}
body, _ := io.ReadAll(io.LimitReader(req.Body, 32*1024*1024))
_ = req.Body.Close()
r.forwardRelayProxy(w, req, body)
})
server := &http.Server{Addr: fmt.Sprintf("127.0.0.1:%d", port), Handler: mux}
listener, err := net.Listen("tcp", server.Addr)
if err != nil {
return err
}
r.relay = server
r.relayURL = "http://" + server.Addr
appendDiagnosticLog("relay_proxy.listening", map[string]any{"port": port, "address": r.relayURL})
go func() {
if err := server.Serve(listener); err != nil && !errors.Is(err, http.ErrServerClosed) {
appendDiagnosticLog("relay_proxy.failed", map[string]any{"port": port, "error": err.Error()})
}
}()
return nil
}
func (r *launcherRuntime) shutdownRelayProxy() {
if r.relay == nil {
return
}
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = r.relay.Shutdown(ctx)
appendDiagnosticLog("relay_proxy.shutdown", map[string]any{"address": r.relayURL})
}
func (r *launcherRuntime) handleHelperHTTP(w http.ResponseWriter, req *http.Request) {
if req.Method == http.MethodOptions {
writeCORSHeaders(w)
w.WriteHeader(http.StatusNoContent)
return
}
body, _ := io.ReadAll(io.LimitReader(req.Body, 32*1024*1024))
_ = req.Body.Close()
appendDiagnosticLog("helper.request", map[string]any{
"method": req.Method,
"path": req.URL.Path,
"body_bytes": len(body),
"remote": req.RemoteAddr,
})
if backendRouteKnown(req.URL.Path) {
payload := json.RawMessage(body)
if len(payload) == 0 {
payload = json.RawMessage(`{}`)
}
writeHelperJSON(w, http.StatusOK, r.handleHelperBackendRequest(req.URL.Path, payload))
return
}
switch req.URL.Path {
case "/overlay/image":
if req.Method != http.MethodGet {
writeHelperJSON(w, http.StatusMethodNotAllowed, map[string]any{"status": "failed", "message": "图片覆盖层只支持 GET"})
break
}
r.writeOverlayImage(w)
case "/mobile":
if req.Method != http.MethodGet {
writeHelperJSON(w, http.StatusMethodNotAllowed, map[string]any{"status": "failed", "message": "手机控制页面只支持 GET"})
break
}
r.writeMobilePage(w, req)
case "/app-server/status":
r.writeAppServerStatus(w, req)
case "/app-server/rpc", "/app-server/ws":
r.proxyAppServerWebSocket(w, req)
case "/v1/responses", "/responses", "/v1/responses/compact", "/responses/compact", "/v1/models", "/models":
r.forwardRelayProxy(w, req, body)
default:
writeHelperJSON(w, http.StatusNotFound, map[string]any{"status": "failed", "message": "未知后端路径"})
}
}
func backendRouteKnown(path string) bool {
switch path {
case "/backend/status", "/backend/repair",
"/settings/get", "/settings/set",
"/diagnostics/log",
"/user-scripts/list", "/user-scripts/set-enabled", "/user-scripts/set-script-enabled", "/user-scripts/reload", "/user-scripts/delete",
"/devtools/open", "/manager/open",
"/codex-model-catalog", "/codex-config-model",
"/zed-remote/status", "/zed-remote/resolve-host", "/zed-remote/fallback-request", "/zed-remote/open", "/zed-remote/projects", "/zed-remote/remember-project", "/zed-remote/forget-project",
"/upstream-worktree/status", "/upstream-worktree/defaults", "/upstream-worktree/prepare", "/upstream-worktree/create",
"/delete", "/undo", "/archived-thread", "/move-thread-workspace", "/move-thread-projectless", "/export-markdown", "/thread-sort-key", "/thread-sort-keys":
return true
default:
return false
}
}
func (r *launcherRuntime) handleHelperBackendRequest(path string, payload json.RawMessage) map[string]any {
result := r.handleBridgeRequest(path, payload)
if _, ok := result["transport"]; !ok {
result["transport"] = "http-helper"
}
return result
}
func (r *launcherRuntime) writeMobilePage(w http.ResponseWriter, req *http.Request) {
writeCORSHeaders(w)
w.Header().Set("content-type", "text/html; charset=utf-8")
w.Header().Set("cache-control", "no-store")
helperBase := "http://" + req.Host
wsBase := "ws://" + req.Host
page := `<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>ChatGPT Codex Mobile</title>
<style>
:root { color-scheme: light dark; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; }
body { margin: 0; min-height: 100vh; display: grid; place-items: center; background: #0f172a; color: #f8fafc; }
main { width: min(680px, calc(100vw - 32px)); }
h1 { margin: 0 0 12px; font-size: 28px; }
p { line-height: 1.6; color: #cbd5e1; }
code { background: rgba(148, 163, 184, .18); padding: 2px 6px; border-radius: 6px; }
button { border: 0; border-radius: 8px; padding: 10px 14px; font-weight: 700; background: #f8fafc; color: #0f172a; }
pre { white-space: pre-wrap; background: rgba(15, 23, 42, .7); border: 1px solid rgba(148, 163, 184, .3); padding: 12px; border-radius: 8px; min-height: 96px; }
</style>
</head>
<body>
<main>
<h1>ChatGPT Codex Mobile</h1>
<p>本地 helper 已启用内置 mobile 入口。手机控制客户端可以连接 <code id="ws"></code>,HTTP 状态可读取 <code id="status"></code>。</p>
<button id="check">检查连接</button>
<pre id="out">ready</pre>
</main>
<script>
const statusUrl = ` + strconv.Quote(helperBase+"/app-server/status") + `;
const wsUrl = ` + strconv.Quote(wsBase+"/app-server/ws") + `;
document.getElementById("status").textContent = statusUrl;
document.getElementById("ws").textContent = wsUrl;
document.getElementById("check").onclick = async () => {
const out = document.getElementById("out");
out.textContent = "checking...";
try {
const response = await fetch(statusUrl);
out.textContent = JSON.stringify(await response.json(), null, 2);
} catch (error) {
out.textContent = String(error && error.message || error);
}
};
</script>
</body>
</html>`
_, _ = w.Write([]byte(page))
}
func (r *launcherRuntime) writeAppServerStatus(w http.ResponseWriter, req *http.Request) {
if req.Method != http.MethodGet && req.Method != http.MethodPost {
writeHelperJSON(w, http.StatusMethodNotAllowed, map[string]any{"status": "failed", "message": "app-server status 只支持 GET/POST"})
return
}
ctx, cancel := context.WithTimeout(req.Context(), 12*time.Second)
defer cancel()
runtime, err := ensureMobileAppServerRuntime(ctx)
if err != nil {
writeHelperJSON(w, http.StatusBadGateway, map[string]any{"status": "failed", "message": err.Error(), "ready": false})
return
}
writeHelperJSON(w, http.StatusOK, map[string]any{
"status": "ok",
"ready": true,
"source": runtime.source,
"port": runtime.port,
"url": fmt.Sprintf("ws://127.0.0.1:%d/rpc", runtime.port),
})
}
func (r *launcherRuntime) proxyAppServerWebSocket(w http.ResponseWriter, req *http.Request) {
ctx, cancel := context.WithTimeout(req.Context(), 12*time.Second)
defer cancel()
upstream, err := connectMobileAppServer(ctx)
if err != nil {
writeHelperJSON(w, http.StatusBadGateway, map[string]any{"status": "failed", "message": err.Error()})
return
}
defer upstream.Close()
upgrader := websocket.Upgrader{CheckOrigin: func(*http.Request) bool { return true }}
client, err := upgrader.Upgrade(w, req, nil)
if err != nil {
return
}
defer client.Close()
done := make(chan struct{}, 2)
pipe := func(dst, src *websocket.Conn) {
defer func() { done <- struct{}{} }()
for {
messageType, data, err := src.ReadMessage()
if err != nil {
return
}
if err := dst.WriteMessage(messageType, data); err != nil {
return
}
}
}
go pipe(upstream, client)
go pipe(client, upstream)
<-done
}
func (r *launcherRuntime) writeOverlayImage(w http.ResponseWriter) {
settings := normalizeSettings(loadSettings())
imagePath := strings.TrimSpace(settings.CodexAppImageOverlayPath)
contentType := overlayImageContentType(imagePath)
if !settings.CodexAppImageOverlayEnabled || imagePath == "" || contentType == "" {
writeHelperJSON(w, http.StatusNotFound, map[string]any{"status": "failed", "message": "图片覆盖层未启用或图片不可用"})
appendDiagnosticLog("helper.overlay_image_not_found", map[string]any{"reason": "disabled_or_invalid_path"})
return
}
bytes, err := os.ReadFile(imagePath)
if err != nil {
writeHelperJSON(w, http.StatusNotFound, map[string]any{"status": "failed", "message": "图片覆盖层未启用或图片不可用"})
appendDiagnosticLog("helper.overlay_image_not_found", map[string]any{"path": imagePath, "error": err.Error()})
return
}
writeCORSHeaders(w)
w.Header().Set("content-type", contentType)
w.Header().Set("cache-control", "no-store")
w.WriteHeader(http.StatusOK)
_, _ = w.Write(bytes)
appendDiagnosticLog("helper.overlay_image_ok", map[string]any{"path": imagePath, "bytes": len(bytes), "content_type": contentType})
}
func (r *launcherRuntime) forwardRelayProxy(w http.ResponseWriter, req *http.Request, body []byte) {
settings := r.relaySettingsForRequest()
requestJSON := map[string]any{}
_ = json.Unmarshal(body, &requestJSON)
profile, selectErr := selectRelayForRequest(settings, rotationContext{ConversationID: conversationIDFromRelayRequest(requestJSON)})
if selectErr != nil {
writeHelperJSON(w, http.StatusBadGateway, map[string]any{"error": map[string]any{"message": selectErr.Error()}})
return
}
profiles := []relayProfile{profile}
if fallbacks, err := fallbackRelaysAfter(settings, profile.ID); err == nil {
profiles = append(profiles, fallbacks...)
}
var lastErr error
for attempt, candidate := range profiles {
if attempt > 0 {
appendDiagnosticLog("relay_proxy.upstream_failover", map[string]any{
"from_relay_id": profile.ID,
"to_relay_id": candidate.ID,
"attempt": attempt + 1,
"candidateCount": len(profiles),
})
}
if forwardRelayProxyAttempt(settings, w, req, body, candidate, attempt+1, len(profiles)) {
return
}
lastErr = errors.New("upstream returned failure")
profile = candidate
}
message := "ChatGPT Codex relay proxy request failed"
if lastErr != nil {
message += ": " + lastErr.Error()
}
writeHelperJSON(w, http.StatusBadGateway, map[string]any{"error": map[string]any{"message": message}})
}
func forwardRelayProxyAttempt(settings backendSettings, w http.ResponseWriter, req *http.Request, body []byte, profile relayProfile, attempt, candidateCount int) bool {
baseURL := relayProxyBaseURL(effectiveUpstreamBaseURL(profile), profile.Protocol)
apiKey := strings.TrimSpace(profile.APIKey)
decision := relayRouteDecision{body: body, route: "text", reason: "default_text"}
if profile.Protocol == "responses" && profile.needsLocalRelayProxy() {
decision = decideRelayRouteForPath(req.URL.Path, body, profile)
body = decision.body
if decision.useImageAPI && usesSeparateImageGenerationAPI(profile) {
baseURL = relayProxyBaseURL(profile.ImageGenerationBaseURL, profile.Protocol)
apiKey = strings.TrimSpace(profile.ImageGenerationAPIKey)
decision.keySource = "image"
} else {
decision.keySource = "default"
}
}
if baseURL == "" || apiKey == "" {
writeHelperJSON(w, http.StatusBadGateway, map[string]any{"error": map[string]any{"message": "ChatGPT Codex relay proxy missing base URL or API key"}})
recordRelayRequestFailure(settings)
return true
}
target := relayTargetURL(baseURL, req.URL.Path)
if decision.useImageAPI {
target = relayImageTargetURL(baseURL, req.URL.Path)
}
startedAt := time.Now()
method := req.Method
if method == "" {
method = http.MethodPost
}
upstreamReq, err := http.NewRequestWithContext(req.Context(), method, target, bytes.NewReader(body))
if err != nil {
writeHelperJSON(w, http.StatusBadGateway, map[string]any{"error": map[string]any{"message": err.Error()}})
recordRelayRequestFailure(settings)
return true
}
upstreamReq.Header.Set("authorization", "Bearer "+apiKey)
copyProxyHeaders(req.Header, upstreamReq.Header)
setRelayProxyUserAgent(profile.UserAgent, req.Header, upstreamReq.Header)
upstreamReq.Header.Set("accept-encoding", "identity")
client, err := relayHTTPClient(profile)
if err != nil {
appendDiagnosticLog("relay_proxy.proxy_config_invalid", map[string]any{
"relay_id": profile.ID,
"relay_name": profile.Name,
"target": target,
"attempt": attempt,
"candidateCount": candidateCount,
"willFailover": attempt < candidateCount,
"error": err.Error(),
})
recordRelayRequestFailure(settings)
if attempt < candidateCount {
return false
}
writeHelperJSON(w, http.StatusBadGateway, map[string]any{"error": map[string]any{"message": relayProxyRequestFailureMessage(err, candidateCount)}})
return true
}
resp, err := client.Do(upstreamReq)
if err != nil {
appendDiagnosticLog("relay_proxy.request_failed", map[string]any{
"relay_id": profile.ID,
"relay_name": profile.Name,
"target": target,
"attempt": attempt,
"candidateCount": candidateCount,
"willFailover": attempt < candidateCount,
"error": err.Error(),
})
recordRelayRequestFailure(settings)
if attempt < candidateCount {
return false
}
writeHelperJSON(w, http.StatusBadGateway, map[string]any{"error": map[string]any{"message": relayProxyRequestFailureMessage(err, candidateCount)}})
return true
}
defer resp.Body.Close()
recordRelayRequestEvent(settings, relayRotationEventForStatus(resp.StatusCode))
if resp.StatusCode >= 400 && attempt < candidateCount {
appendDiagnosticLog("relay_proxy.upstream_status_failed", map[string]any{
"relay_id": profile.ID,
"relay_name": profile.Name,
"target": target,
"status": resp.StatusCode,
"attempt": attempt,
"candidateCount": candidateCount,
"willFailover": true,
})
return false
}
writeCORSHeaders(w)
for _, name := range []string{"content-type", "cache-control", "openai-request-id", "x-request-id"} {
if value := resp.Header.Get(name); value != "" {
w.Header().Set(name, value)
}
}
if w.Header().Get("content-type") == "" {
w.Header().Set("content-type", "application/json")
}
w.WriteHeader(resp.StatusCode)
flushRelayResponseHeaders(w)
responseBytes, copyErr := copyRelayResponseBody(w, resp.Body)
logDetail := map[string]any{
"path": req.URL.Path,
"status": resp.StatusCode,
"target": target,
"route": decision.route,
"reason": decision.reason,
"key_source": decision.keySource,
"stripped_image_tool": decision.strippedImageTool,
"relay_id": profile.ID,
"relay_name": profile.Name,
"attempt": attempt,
"candidateCount": candidateCount,
"body_bytes": responseBytes,
"duration_ms": time.Since(startedAt).Milliseconds(),
}
if copyErr != nil {
logDetail["copy_error"] = copyErr.Error()
}
appendDiagnosticLog("relay_proxy.response", logDetail)
return true
}
func relayProxyRequestFailureMessage(err error, candidateCount int) string {
detail := err.Error()
if errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) {
detail = "upstream disconnected before returning an HTTP response (EOF)"
}
message := "ChatGPT Codex relay proxy request failed: " + detail
if candidateCount <= 1 {
return message + "; no failover candidate is configured"
}
return message + "; all configured failover candidates failed"
}
func relayRotationEventForStatus(statusCode int) rotationEvent {
if statusCode >= 200 && statusCode < 300 {
return rotationEventSuccess
}
return rotationEventFailure
}
func conversationIDFromRelayRequest(body map[string]any) string {
for _, key := range []string{"conversation", "conversation_id", "previous_response_id"} {
if value := strings.TrimSpace(stringFromAny(body[key])); value != "" {
return value
}
}
return ""
}
func effectiveUpstreamBaseURL(profile relayProfile) string {
return strings.TrimSpace(firstNonEmpty(profile.UpstreamBaseURL, profile.BaseURL))
}
func relayProxyBaseURL(baseURL, protocol string) string {
trimmed := strings.TrimRight(strings.TrimSpace(baseURL), "/")
if protocol == "responses" {
return normalizeResponsesBaseURL(trimmed)
}
return trimmed
}
func relayTargetURL(baseURL, path string) string {
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
path = relayUpstreamPath(path)
if path == "" {
return baseURL
}
if strings.HasSuffix(baseURL, path) {
return baseURL
}
return baseURL + path
}
func relayImageTargetURL(baseURL, path string) string {
baseURL = strings.TrimRight(strings.TrimSpace(baseURL), "/")
if relayURLHasCompleteImageEndpoint(baseURL) {
return baseURL
}
return relayTargetURL(baseURL, path)
}
func relayUpstreamPath(path string) string {
path = "/" + strings.TrimLeft(strings.TrimSpace(path), "/")
if path == "/" || path == "/v1" {
return ""
}
if strings.HasPrefix(path, "/v1/") {
return strings.TrimPrefix(path, "/v1")
}
return path
}
func relayURLHasCompleteImageEndpoint(rawURL string) bool {
parsed, err := url.Parse(strings.TrimSpace(rawURL))
if err != nil {
return false
}
path := strings.TrimRight(parsed.Path, "/")
return path == "/responses" || strings.HasSuffix(path, "/responses") ||
path == "/images/generations" || strings.HasSuffix(path, "/images/generations") ||
path == "/images/edits" || strings.HasSuffix(path, "/images/edits") ||
path == "/images/variations" || strings.HasSuffix(path, "/images/variations")
}
func copyProxyHeaders(source http.Header, target http.Header) {
for name, values := range source {
lower := strings.ToLower(name)
if lower == "authorization" || lower == "host" || lower == "connection" || lower == "content-length" || lower == "user-agent" || lower == "accept-encoding" {
continue
}
target.Del(name)
for _, value := range values {
target.Add(name, value)
}
}
}
func setRelayProxyUserAgent(configured string, source http.Header, target http.Header) {
userAgent := strings.TrimSpace(configured)
if userAgent == "" {
userAgent = strings.TrimSpace(source.Get("user-agent"))
}
if userAgent == "" {
userAgent = "Codex"
}
target.Set("user-agent", userAgent)
}
func flushRelayResponseHeaders(w http.ResponseWriter) {
flusher, ok := w.(http.Flusher)
if !ok {
return
}
flusher.Flush()
}
func copyRelayResponseBody(w http.ResponseWriter, body io.Reader) (int64, error) {
flusher, ok := w.(http.Flusher)
if !ok {
return io.Copy(w, body)
}
buffer := make([]byte, 32*1024)
var written int64
for {
read, readErr := body.Read(buffer)
if read > 0 {
copied, writeErr := w.Write(buffer[:read])
if copied > 0 {
written += int64(copied)
flusher.Flush()
}
if writeErr != nil {
return written, writeErr
}
if copied != read {
return written, io.ErrShortWrite
}
}
if readErr != nil {
if errors.Is(readErr, io.EOF) {
return written, nil
}
return written, readErr
}
}
}
func decideRelayRoute(body []byte, profile relayProfile) relayRouteDecision {
return decideRelayRouteForPath("", body, profile)
}
func decideRelayRouteForPath(path string, body []byte, profile relayProfile) relayRouteDecision {
decision := relayRouteDecision{body: body, route: "text", reason: "default_text", keySource: "default"}
var value map[string]any
if json.Unmarshal(body, &value) != nil {
decision.reason = "invalid_json"
if usesSeparateImageGenerationAPI(profile) && relayPathRequestsImageGeneration(path) {
decision.useImageAPI = true
decision.route = "image"
decision.reason = "image_endpoint"
decision.keySource = "image"
}
return decision
}
if !profile.ImageGenerationEnabled {
decision.reason = "image_disabled"
decision.body, decision.strippedImageTool = stripImageGenerationTools(value, body)
return decision
}
if usesSeparateImageGenerationAPI(profile) {
if relayPathRequestsImageGeneration(path) {
decision.useImageAPI = true
decision.route = "image"
decision.reason = "image_endpoint"
decision.keySource = "image"
return decision
}
if relayToolChoiceRequestsImage(value["tool_choice"]) {
decision.useImageAPI = true
decision.route = "image"
decision.reason = "tool_choice_image"
decision.keySource = "image"
return decision
}
latestUserTexts := relayLatestUserTextFragments(value["input"])
if len(latestUserTexts) == 0 && relayBodyContainsImageGenerationCall(value) {
decision.useImageAPI = true
decision.route = "image"
decision.reason = "image_generation_call"
decision.keySource = "image"
return decision
}
if relayBodyDeclaresImageGenerationTool(value) && (relayTextFragmentsRequestImage(latestUserTexts, value["input"]) ||
relayLatestUserInputContainsImage(value["input"]) && relayTextFragmentsRequestImageEdit(latestUserTexts, value["input"])) {
decision.useImageAPI = true
decision.route = "image"
decision.reason = "latest_user_image_intent"
decision.keySource = "image"
return decision
}
}
decision.body, decision.strippedImageTool = stripImageGenerationTools(value, body)
if decision.strippedImageTool {
decision.reason = "text_with_image_tool_stripped"
}
return decision
}
func relayPathRequestsImageGeneration(path string) bool {
path = strings.ToLower(strings.TrimRight("/"+strings.TrimLeft(strings.TrimSpace(path), "/"), "/"))
return strings.HasSuffix(path, "/images/generations") || strings.HasSuffix(path, "/images/edits") || strings.HasSuffix(path, "/images/variations")
}
func relayBodyDeclaresImageGenerationTool(value map[string]any) bool {
tools, ok := value["tools"].([]any)
if !ok {
return false
}
for _, tool := range tools {
if relayToolIsImageGeneration(tool) {
return true
}
}
return false
}
func stripImageGenerationTools(value map[string]any, fallback []byte) ([]byte, bool) {
stripped := false
if tools, ok := value["tools"].([]any); ok && len(tools) > 0 {
filtered := make([]any, 0, len(tools))
for _, tool := range tools {
if relayToolIsImageGeneration(tool) {
stripped = true
continue
}
filtered = append(filtered, tool)
}
if stripped {
value["tools"] = filtered
}
}
if relayToolChoiceRequestsImage(value["tool_choice"]) {
delete(value, "tool_choice")
stripped = true
}
if !stripped {
return fallback, false
}
updated, err := json.Marshal(value)
if err != nil {
return fallback, false
}
return updated, true
}
func relayToolIsImageGeneration(tool any) bool {
object, ok := tool.(map[string]any)
if !ok {
return false
}
return relayImageKind(stringFromAny(firstNonNil(object["type"], object["name"])))
}
func relayToolChoiceRequestsImage(choice any) bool {
switch value := choice.(type) {
case string:
return relayImageKind(value)
case map[string]any:
return relayImageKind(stringFromAny(firstNonNil(value["type"], value["name"])))
default:
return false
}
}
func relayBodyContainsImageGenerationCall(value map[string]any) bool {
for key, item := range value {
if key == "tools" || key == "tool_choice" {
continue
}
if relayNodeContainsImageGenerationCall(item) {
return true
}
}
return false
}
func relayNodeContainsImageGenerationCall(node any) bool {
switch value := node.(type) {
case map[string]any:
kind := strings.ToLower(stringFromAny(firstNonNil(value["type"], value["name"])))
if strings.Contains(kind, "image_generation_call") {
return true
}
for key, item := range value {
if key == "tools" || key == "tool_choice" {
continue
}
if relayNodeContainsImageGenerationCall(item) {
return true
}
}
case []any:
for _, item := range value {
if relayNodeContainsImageGenerationCall(item) {
return true
}
}
}
return false
}
func relayLatestUserInputRequestsImage(input any) bool {
texts := relayLatestUserTextFragments(input)
return relayTextFragmentsRequestImage(texts, input)
}
func relayTextFragmentsRequestImage(texts []string, fallback any) bool {
if len(texts) == 0 {
texts = relayTextFragments(fallback)
}
for _, text := range texts {
if relayTextRequestsImage(text) {
return true
}
}
return false
}
func relayTextFragmentsRequestImageEdit(texts []string, fallback any) bool {
if len(texts) == 0 {
texts = relayTextFragments(fallback)
}
for _, text := range texts {
if relayTextRequestsImageEdit(text) {
return true
}
}
return false
}
func relayLatestUserTextFragments(input any) []string {
messages, ok := input.([]any)
if !ok {
return nil
}
for index := len(messages) - 1; index >= 0; index-- {
message, ok := messages[index].(map[string]any)
if !ok {
continue
}
if strings.ToLower(stringFromAny(message["role"])) != "user" {
continue
}
texts := relayTextFragments(firstNonNil(message["content"], message["text"], message["input"], message["prompt"]))
if len(texts) > 0 {
return texts
}
}
return nil
}
func relayLatestUserInputContainsImage(input any) bool {
messages, ok := input.([]any)
if !ok {
return relayNodeContainsImageInput(input)
}
for index := len(messages) - 1; index >= 0; index-- {
message, ok := messages[index].(map[string]any)
if !ok || strings.ToLower(stringFromAny(message["role"])) != "user" {
continue
}
return relayNodeContainsImageInput(firstNonNil(message["content"], message["input"]))
}
return relayNodeContainsImageInput(input)
}
func relayNodeContainsImageInput(node any) bool {
switch value := node.(type) {
case []any:
for _, child := range value {
if relayNodeContainsImageInput(child) {
return true
}
}
case map[string]any:
kind := strings.ToLower(stringFromAny(value["type"]))
if kind == "input_image" || kind == "image_url" {
return true
}
if stringFromAny(value["image_url"]) != "" && !strings.Contains(kind, "output") {
return true
}
for _, key := range []string{"content", "input"} {
if relayNodeContainsImageInput(value[key]) {
return true
}
}
}
return false
}
func relayTextFragments(node any) []string {
var fragments []string
var walk func(any)
walk = func(item any) {
switch value := item.(type) {
case string:
fragments = append(fragments, value)
case []any:
for _, child := range value {
walk(child)
}
case map[string]any:
if kind := strings.ToLower(stringFromAny(value["type"])); kind != "" && strings.Contains(kind, "image") && !strings.Contains(kind, "text") {
return
}
for key, child := range value {
switch key {
case "text", "content", "input", "prompt":
walk(child)
}
}
}
}
walk(node)
return fragments
}
func relayTextRequestsImage(text string) bool {
normalized := strings.ToLower(strings.TrimSpace(text))
if normalized == "" {
return false
}
for _, negative := range []string{
"不要生成图片", "不生成图片", "无需生成图片", "不用生成图片", "不要画图", "无需画图", "不用画图",
"do not generate an image", "do not generate images", "don't generate an image", "don't generate images",
"without generating an image", "without generating images", "no image generation",
} {
if strings.Contains(normalized, negative) {
return false
}
}
return relayChineseTextRequestsImage(normalized) || relayEnglishTextRequestsImage(normalized)
}
func relayTextRequestsImageEdit(text string) bool {
normalized := strings.ToLower(strings.TrimSpace(text))
if normalized == "" {
return false
}
for _, negative := range []string{
"不要编辑图片", "不修改图片", "无需修改图片", "不用修改图片",
"do not edit the image", "don't edit the image", "do not modify the image", "without editing the image",
} {
if strings.Contains(normalized, negative) {
return false
}
}
return relayChineseTextRequestsImageEdit(normalized) || relayEnglishTextRequestsImageEdit(normalized)
}
func relayChineseTextRequestsImage(text string) bool {
actions := []string{"生成", "画", "绘制", "创建", "设计", "做", "制作"}
targets := []string{"架构图", "示意图", "缩略图", "图片", "图像", "图标", "插画", "海报", "照片", "头像", "封面", "logo", "图"}
for _, action := range actions {
for search := 0; search < len(text); {
actionIndex := strings.Index(text[search:], action)
if actionIndex < 0 {
break
}
actionIndex += search
if relayChineseImageActionPrefixAllowed(text[:actionIndex]) {
targetIndex, target := relayFirstTextTarget(text, actionIndex+len(action), targets, false)
if targetIndex >= 0 && relayChineseImageObjectGapAllowed(text[actionIndex+len(action):targetIndex]) && relayChineseImageTargetSuffixAllowed(text[targetIndex+len(target):]) {
return true
}
if targetIndex < 0 && (action == "画" || action == "绘制") && relayChineseDrawObjectAllowed(text[:actionIndex], text[actionIndex+len(action):]) {
return true
}
}
search = actionIndex + len(action)
}
}
return false
}
func relayChineseTextRequestsImageEdit(text string) bool {
actions := []string{"编辑", "修改", "修复"}
targets := []string{"架构图", "示意图", "缩略图", "图片", "图像", "图标", "插画", "海报", "照片", "头像", "封面", "logo", "图"}
for _, action := range actions {
for search := 0; search < len(text); {
actionIndex := strings.Index(text[search:], action)
if actionIndex < 0 {
break
}
actionIndex += search
if relayChineseImageActionPrefixAllowed(text[:actionIndex]) {
targetIndex, target := relayFirstTextTarget(text, actionIndex+len(action), targets, false)
if targetIndex >= 0 && relayChineseImageObjectGapAllowed(text[actionIndex+len(action):targetIndex]) && relayChineseImageTargetSuffixAllowed(text[targetIndex+len(target):]) {
return true
}
}
search = actionIndex + len(action)
}
}
return false
}
func relayEnglishTextRequestsImage(text string) bool {
actions := []string{"generate", "create", "draw", "make", "design"}
targets := []string{
"illustrations", "illustration", "thumbnails", "thumbnail", "pictures", "picture", "diagrams", "diagram",
"graphics", "graphic", "artworks", "artwork", "posters", "poster", "avatars", "avatar",
"images", "image", "icons", "icon", "logos", "logo", "photo", "photos",
}
for _, action := range actions {
for search := 0; search < len(text); {
actionIndex := relayASCIIWordIndex(text, action, search)
if actionIndex < 0 {
break
}
if relayEnglishImageActionPrefixAllowed(text[:actionIndex]) {
targetIndex, target := relayFirstTextTarget(text, actionIndex+len(action), targets, true)
if targetIndex >= 0 && relayEnglishImageObjectGapAllowed(text[actionIndex+len(action):targetIndex]) && relayEnglishImageTargetSuffixAllowed(text[targetIndex+len(target):]) {
return true
}
if targetIndex < 0 && action == "draw" && relayEnglishDrawObjectAllowed(text[:actionIndex], text[actionIndex+len(action):]) {
return true
}
}
search = actionIndex + len(action)