-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmanager.go
More file actions
1542 lines (1461 loc) · 46.2 KB
/
manager.go
File metadata and controls
1542 lines (1461 loc) · 46.2 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"
"io/fs"
"net"
"net/http"
"os"
"os/exec"
pathpkg "path"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
)
func runManager() error {
root, _ := repoRoot()
distFS, distLabel, err := managerDistFS(root)
if err != nil {
return err
}
mux := http.NewServeMux()
manager := &server{root: root, dist: distLabel, distFS: distFS}
mux.HandleFunc("/api/commands/", manager.handleCommand)
mux.HandleFunc("/api/dialog/open", manager.handleOpenDialog)
mux.HandleFunc("/", manager.handleStatic)
listener, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return err
}
defer listener.Close()
url := "http://" + listener.Addr().String()
fmt.Printf("%s Go manager: %s\n", appName, url)
if defaultManagerDesktop() {
server := &http.Server{Handler: mux}
serverErr := make(chan error, 1)
go func() {
if err := server.Serve(listener); err != nil && err != http.ErrServerClosed {
serverErr <- err
}
close(serverErr)
}()
if err := runManagerDesktopWindow(managerName, url); err != nil {
return err
}
shutdownCtx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
_ = server.Shutdown(shutdownCtx)
if err, ok := <-serverErr; ok {
return err
}
return nil
}
_ = openURL(url)
return http.Serve(listener, mux)
}
func openManagerApp() error {
if runtime.GOOS == "darwin" {
app := entrypointPath(true)
if fileExists(app) {
cmd := exec.Command("open", "-a", app)
hideSubprocessWindow(cmd)
return cmd.Start()
}
}
cmd := exec.Command(companionBinaryPath(managerBinary))
hideSubprocessWindow(cmd)
return cmd.Start()
}
func (s *server) handleCommand(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "method not allowed", http.StatusMethodNotAllowed)
return
}
command := strings.TrimPrefix(r.URL.Path, "/api/commands/")
command, _ = urlPathUnescape(command)
var args map[string]any
if err := json.NewDecoder(r.Body).Decode(&args); err != nil && !errors.Is(err, io.EOF) {
writeJSON(w, failed("请求参数 JSON 解析失败:"+err.Error(), map[string]any{}))
return
}
if args == nil {
args = map[string]any{}
}
ctx, cancel := context.WithTimeout(r.Context(), commandTimeout(command))
defer cancel()
result := s.dispatch(ctx, command, args)
writeJSON(w, result)
}
func commandTimeout(command string) time.Duration {
if command == "install_update" {
return 5 * time.Minute
}
return 45 * time.Second
}
func (s *server) handleOpenDialog(w http.ResponseWriter, r *http.Request) {
var opts map[string]any
_ = json.NewDecoder(r.Body).Decode(&opts)
title := "选择路径"
if value, ok := opts["title"].(string); ok && strings.TrimSpace(value) != "" {
title = value
}
directory, _ := opts["directory"].(bool)
selected := os.Getenv("CODEX_PLUS_SELECTED_PATH")
if selected == "" {
selected = strings.TrimSpace(promptPath(title, directory))
}
if selected == "" {
writeJSON(w, nil)
return
}
writeJSON(w, selected)
}
func (s *server) handleStatic(w http.ResponseWriter, r *http.Request) {
assetPath := strings.TrimPrefix(pathpkg.Clean("/"+r.URL.Path), "/")
if assetPath == "" || assetPath == "." {
s.serveIndex(w)
return
}
info, err := fs.Stat(s.distFS, assetPath)
if err != nil || info.IsDir() {
s.serveIndex(w)
return
}
http.FileServer(http.FS(s.distFS)).ServeHTTP(w, r)
}
func (s *server) serveIndex(w http.ResponseWriter) {
index, err := fs.ReadFile(s.distFS, "index.html")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
injected := bytes.Replace(index, []byte("<head>"), []byte(`<head><script>window.__CODEX_PLUS_GO_MANAGER__={apiBase:""};</script>`), 1)
w.Header().Set("content-type", "text/html; charset=utf-8")
_, _ = w.Write(injected)
}
func (s *server) dispatch(ctx context.Context, command string, args map[string]any) commandResult {
switch command {
case "backend_version":
return ok("后端版本已读取。", map[string]any{"version": version})
case "load_overview":
return s.loadOverview()
case "check_update":
return s.checkUpdate(ctx)
case "install_update":
return s.installUpdate(ctx)
case "load_install_guide_status":
return s.loadInstallGuideStatus(ctx)
case "launch_codex_plus":
return s.launchCodex(args, false)
case "restart_codex_plus":
return s.launchCodex(args, true)
case "load_settings":
return settingsPayload("设置已加载。")
case "save_settings":
return s.saveSettings(args)
case "load_ccs_providers":
return s.loadCCSProviders()
case "import_ccs_providers":
return s.importCCSProviders()
case "sync_providers_now":
return s.syncProvidersNow()
case "repair_codex_plugins":
return s.repairCodexPlugins()
case "repair_codex_goals":
return s.repairCodexGoals()
case "refresh_script_market":
return s.refreshScriptMarket(ctx)
case "install_market_script":
return s.installMarketScript(ctx, stringArg(args, "id"))
case "set_user_script_enabled":
return s.setUserScriptEnabled(stringArg(args, "key"), boolArg(args, "enabled"))
case "delete_user_script":
return s.deleteUserScript(stringArg(args, "key"))
case "open_external_url":
return s.openExternalURL(stringArg(args, "url"))
case "install_entrypoints", "repair_shortcuts":
return s.installEntrypoints()
case "uninstall_entrypoints":
return s.uninstallEntrypoints(args)
case "repair_codex_app":
return s.repairCodexApp()
case "repair_backend":
return settingsPayload("后端已修复;Go 管理器当前复用设置文件,命令包装器仍由 Rust core 处理。")
case "load_watcher_state":
return ok("watcher 状态已加载。", watcherPayload())
case "install_watcher":
return s.installWatcher()
case "uninstall_watcher":
return s.uninstallWatcher()
case "enable_watcher":
return s.setWatcherDisabled(false)
case "disable_watcher":
return s.setWatcherDisabled(true)
case "read_latest_logs":
return s.readLatestLogs(args)
case "copy_diagnostics":
return ok("诊断报告已生成。", map[string]any{"report": s.diagnosticsReport()})
case "reset_settings":
if err := saveSettings(defaultSettings()); err != nil {
return failed("重置设置失败:"+err.Error(), settingsPayloadValue(defaultSettings()))
}
return settingsPayload("设置已重置为默认值。")
case "relay_status":
return s.relayStatus()
case "read_relay_files":
return s.readRelayFiles()
case "save_relay_file":
return s.saveRelayFile(args)
case "bind_official_auth":
return s.bindOfficialAuth(args)
case "unbind_official_auth":
return s.unbindOfficialAuth(args)
case "clear_current_official_auth":
return s.clearCurrentOfficialAuth()
case "test_relay_profile":
return s.testRelayProfile(ctx, args)
case "apply_relay_injection":
return s.applyRelayInjection(false)
case "apply_pure_api_injection":
return s.applyRelayInjection(true)
case "clear_relay_injection":
return s.clearRelayInjection()
default:
return failed("未知命令:"+command, map[string]any{})
}
}
func ok(message string, payload map[string]any) commandResult {
result := commandResult{"status": "ok", "message": message}
for key, value := range payload {
result[key] = value
}
return result
}
func failed(message string, payload map[string]any) commandResult {
result := commandResult{"status": "failed", "message": message}
for key, value := range payload {
result[key] = value
}
return result
}
func writeJSON(w http.ResponseWriter, value any) {
w.Header().Set("content-type", "application/json; charset=utf-8")
encoder := json.NewEncoder(w)
encoder.SetEscapeHTML(false)
_ = encoder.Encode(value)
}
func (s *server) loadOverview() commandResult {
settings := loadSettings()
codexApp := resolveCodexApp(settings.CodexAppPath)
var latest *launchStatus
_ = readJSON(latestStatusPath(), &latest)
payload := map[string]any{
"codex_app": codexPathState(codexApp),
"codex_version": codexAppVersion(codexApp),
"silent_shortcut": shortcutState(entrypointPath(false)),
"management_shortcut": shortcutState(entrypointPath(true)),
"latest_launch": latest,
"current_version": version,
"update_status": "not_checked",
"settings_path": settingsPath(),
"logs_path": diagnosticLogPath(),
}
return ok("概览已加载。", payload)
}
func (s *server) repairCodexApp() commandResult {
settings := loadSettings()
candidates := codexAppRepairCandidates(settings.CodexAppPath)
if len(candidates) == 0 {
return failed("未找到可启动的 Codex 程序。请确认 Microsoft Store 中的 Codex 已安装,或手动选择 Codex.exe / Codex 安装目录。", settingsPayloadValue(settings))
}
selected := candidates[0]
settings.CodexAppPath = selected
if err := saveSettings(settings); err != nil {
return failed("修复 Codex 程序失败:"+err.Error(), settingsPayloadValue(loadSettings()))
}
payload := settingsPayloadValue(loadSettings())
payload["codexApp"] = codexPathState(resolveCodexApp(selected))
payload["repairCandidates"] = candidates
return ok("已修复 Codex 程序路径:"+selected, payload)
}
func codexAppRepairCandidates(saved string) []string {
candidates := []string{}
add := func(path string) {
path = strings.TrimSpace(path)
if path == "" {
return
}
for _, existing := range candidates {
if strings.EqualFold(existing, path) {
return
}
}
candidates = append(candidates, path)
}
if normalized := normalizeCodexAppPath(saved); normalized != "" {
add(normalized)
}
if runtime.GOOS == "windows" {
if local := resolveWindowsCodexFromCommonPaths(); local != "" {
add(local)
}
if installed := resolveWindowsCodexFromInstalledApps(); installed != "" {
add(installed)
}
if latest := findLatestWindowsCodexAppDirFromRoots(windowsAppPackageRoots()); latest != "" {
add(latest)
}
if alias := windowsCodexExecutionAlias(); alias != "" && fileExists(alias) {
add(alias)
}
}
if installed := resolveCodexApp(""); installed != "" {
add(installed)
}
return candidates
}
func (s *server) loadInstallGuideStatus(ctx context.Context) commandResult {
settings := loadSettings()
codexApp := resolveCodexApp(settings.CodexAppPath)
ccsDBPath := defaultCCSDBPath()
ccsDBPathCandidates := ccsDBPathCandidates()
ccsProviders, ccsErr := listCCSProviders(ccsDBPath)
download := latestCodexDownload(ctx, runtime.GOOS, runtime.GOARCH)
relayStatus := relayStatusFromHome(codexHomeDir(), settings)
message := "新手引导状态已读取。"
var warnings []string
if ccsErr != nil {
warnings = append(warnings, "CCSwitch 数据库读取失败:"+ccsErr.Error())
}
if runtime.GOOS == "windows" && stringFromAny(download["status"]) == "failed" {
warnings = append(warnings, "Windows 安装包信息暂时获取失败,可稍后刷新")
}
if len(warnings) > 0 {
message = "系统和本地安装状态已读取;" + strings.Join(warnings, ";") + "。"
}
payload := map[string]any{
"platform": runtime.GOOS,
"arch": runtime.GOARCH,
"platformLabel": platformDisplayName(runtime.GOOS),
"archLabel": archDisplayName(runtime.GOARCH),
"desktopRuntime": desktopRuntimeName(),
"desktopRuntimeStatus": desktopRuntimeStatus(),
"codexApp": codexPathState(codexApp),
"codexVersion": codexAppVersion(codexApp),
"codexDetection": codexDetectionPayload(settings.CodexAppPath, codexApp),
"codexLaunch": codexLaunchPayload(codexApp),
"codexInstallUrl": codexInstallURL(download),
"codexInstallSource": codexInstallSource(download),
"codexMirrorProjectUrl": codexAppMirrorProjectURL,
"codexMirrorLatestReleaseUrl": codexMirrorLatestReleaseURL(download),
"codexLatestDownload": download,
"ccs": map[string]any{
"installed": fileExists(ccsDBPath),
"dbPath": ccsDBPath,
"dbPathCandidates": ccsDBPathCandidates,
"providerCount": len(ccsProviders),
"readError": optionalErrorString(ccsErr),
},
"settingsPath": settingsPath(),
"activeMode": activeRelayProfile(settings).RelayMode,
"relay": relayStatus,
"connection": installGuideConnectionPayload(settings, relayStatus),
}
return ok(message, payload)
}
func platformDisplayName(goos string) string {
switch goos {
case "darwin":
return "macOS"
case "windows":
return "Windows"
case "linux":
return "Linux"
default:
return goos
}
}
func archDisplayName(goarch string) string {
switch goarch {
case "amd64":
return "x64"
case "arm64":
return "ARM64"
case "386":
return "x86"
default:
return goarch
}
}
func desktopRuntimeName() string {
switch runtime.GOOS {
case "windows":
return "Windows WebView2 桌面窗口"
case "darwin":
return "macOS WebKit 桌面窗口"
default:
if defaultManagerDesktop() {
return "桌面窗口"
}
return "浏览器模式"
}
}
func desktopRuntimeStatus() string {
if defaultManagerDesktop() {
return "desktop"
}
return "browser"
}
func codexInstallURL(download map[string]any) string {
if url := stringFromAny(download["downloadUrl"]); url != "" {
return url
}
if runtime.GOOS == "darwin" {
return codexOfficialInstallURL
}
return codexAppMirrorReleaseURL
}
func codexInstallSource(download map[string]any) string {
if source := stringFromAny(download["source"]); source != "" {
return source
}
if runtime.GOOS == "darwin" {
return "official"
}
return "mirror"
}
func codexMirrorLatestReleaseURL(download map[string]any) string {
if url := stringFromAny(download["releaseUrl"]); url != "" {
return url
}
return codexAppMirrorReleaseURL
}
func latestCodexDownload(ctx context.Context, goos, goarch string) map[string]any {
payload := map[string]any{
"status": "not_checked",
"source": "mirror",
"projectUrl": codexAppMirrorProjectURL,
"releaseUrl": codexAppMirrorReleaseURL,
}
if goos == "darwin" {
payload["status"] = "available"
payload["source"] = "official"
payload["downloadUrl"] = codexOfficialInstallURL
payload["message"] = "macOS 默认打开 Codex 官方安装页面。"
}
release, err := getJSON[codexAppMirrorRelease](ctx, codexAppMirrorAPIURL)
if err != nil {
payload["status"] = "failed"
payload["message"] = "获取镜像最新版本失败:" + err.Error()
return payload
}
payload["releaseName"] = release.Name
payload["tagName"] = release.TagName
payload["publishedAt"] = release.PublishedAt
if release.HTMLURL != "" {
payload["releaseUrl"] = release.HTMLURL
}
if goos == "darwin" {
return payload
}
asset, ok := selectCodexMirrorAsset(release.Assets, goos, goarch)
if !ok {
payload["status"] = "missing"
payload["message"] = "最新镜像版本没有找到当前系统对应安装包。"
return payload
}
payload["status"] = "available"
payload["source"] = "mirror"
payload["assetName"] = asset.Name
payload["downloadUrl"] = asset.BrowserDownloadURL
payload["size"] = asset.Size
payload["contentType"] = asset.ContentType
payload["message"] = "已找到镜像项目最新对应系统安装包。"
return payload
}
func selectCodexMirrorAsset(assets []codexAppMirrorAsset, goos, goarch string) (codexAppMirrorAsset, bool) {
var candidates []codexAppMirrorAsset
for _, asset := range assets {
name := strings.ToLower(asset.Name)
url := strings.ToLower(asset.BrowserDownloadURL)
value := name + " " + url
if asset.BrowserDownloadURL == "" {
continue
}
switch goos {
case "windows":
if strings.HasSuffix(name, ".msix") || strings.HasSuffix(name, ".appx") || strings.Contains(value, "windows") || strings.Contains(value, "win") {
candidates = append(candidates, asset)
}
case "darwin":
if strings.HasSuffix(name, ".dmg") && (strings.Contains(value, "mac") || strings.Contains(value, "darwin")) {
candidates = append(candidates, asset)
}
}
}
if len(candidates) == 0 {
return codexAppMirrorAsset{}, false
}
sort.SliceStable(candidates, func(i, j int) bool {
return codexAssetScore(candidates[i].Name, goarch) > codexAssetScore(candidates[j].Name, goarch)
})
return candidates[0], true
}
func codexAssetScore(name, goarch string) int {
lower := strings.ToLower(name)
score := 0
switch goarch {
case "arm64":
if strings.Contains(lower, "arm64") || strings.Contains(lower, "aarch64") {
score += 20
}
case "amd64":
if strings.Contains(lower, "x64") || strings.Contains(lower, "amd64") || strings.Contains(lower, "x86_64") {
score += 20
}
}
if strings.HasSuffix(lower, ".msix") || strings.HasSuffix(lower, ".dmg") {
score += 10
}
if strings.Contains(lower, "sha256") || strings.Contains(lower, "manifest") || strings.HasSuffix(lower, ".png") || strings.HasSuffix(lower, ".txt") || strings.HasSuffix(lower, ".json") {
score -= 100
}
return score
}
func errorString(err error) string {
if err == nil {
return "unknown error"
}
return err.Error()
}
func optionalErrorString(err error) string {
if err == nil {
return ""
}
return err.Error()
}
func pathState(path string) map[string]any {
if path == "" {
return map[string]any{"status": "missing", "path": nil}
}
return map[string]any{"status": "found", "path": path}
}
func codexPathState(path string) map[string]any {
state := pathState(path)
if path != "" && runtime.GOOS == "windows" {
state["executable"] = buildCodexExecutable(path)
if appUserModelID := packagedWindowsAppUserModelID(path); appUserModelID != "" {
state["appUserModelId"] = appUserModelID
}
}
return state
}
func shortcutState(path string) map[string]any {
if path == "" {
return map[string]any{"status": "missing", "path": nil}
}
if !fileExists(path) {
return map[string]any{"status": "missing", "path": path}
}
return map[string]any{"status": "installed", "path": path}
}
func resolveCodexApp(saved string) string {
if normalized := normalizeCodexAppPath(saved); normalized != "" {
return normalized
}
if runtime.GOOS == "darwin" {
candidates := []string{"/Applications/Codex.app"}
if home, err := os.UserHomeDir(); err == nil {
candidates = append(candidates, filepath.Join(home, "Applications", "Codex.app"))
}
for _, candidate := range candidates {
if isDir(candidate) {
return candidate
}
}
}
if runtime.GOOS == "windows" {
if local := resolveWindowsCodexFromCommonPaths(); local != "" {
return local
}
if installed := resolveWindowsCodexFromInstalledApps(); installed != "" {
return installed
}
if latest := findLatestWindowsCodexAppDirFromRoots(windowsAppPackageRoots()); latest != "" {
return latest
}
}
return ""
}
func resolveWindowsCodexFromInstalledApps() string {
if runtime.GOOS != "windows" {
return ""
}
commands := [][]string{
{"powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `Get-AppxPackage -Name OpenAI.Codex -ErrorAction SilentlyContinue | Sort-Object Version | Select-Object -Last 1 -ExpandProperty InstallLocation`},
{"powershell", "-NoProfile", "-ExecutionPolicy", "Bypass", "-Command", `Get-AppxPackage -ErrorAction SilentlyContinue | Where-Object { $_.Name -eq 'OpenAI.Codex' -or $_.PackageFullName -like 'OpenAI.Codex_*' } | Sort-Object Version | Select-Object -Last 1 -ExpandProperty InstallLocation`},
}
for _, command := range commands {
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
cmd := exec.CommandContext(ctx, command[0], command[1:]...)
hideSubprocessWindow(cmd)
out, err := cmd.Output()
cancel()
if err != nil {
continue
}
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
if normalized := normalizeCodexAppPath(line); normalized != "" {
return normalized
}
}
}
return ""
}
func resolveWindowsCodexFromCommonPaths() string {
if runtime.GOOS != "windows" {
return ""
}
var candidates []string
addCandidate := func(path string) {
path = strings.TrimSpace(path)
if path != "" {
candidates = append(candidates, path)
}
}
for _, key := range []string{"CODEX_APP_PATH", "CODEX_PATH", "CODEX_DESKTOP_PATH"} {
addCandidate(os.Getenv(key))
}
for _, root := range []string{os.Getenv("LOCALAPPDATA"), os.Getenv("ProgramFiles"), os.Getenv("ProgramW6432")} {
if root == "" {
continue
}
addCandidate(filepath.Join(root, "Programs", "Codex"))
addCandidate(filepath.Join(root, "Codex"))
addCandidate(filepath.Join(root, "OpenAI", "Codex"))
addCandidate(filepath.Join(root, "OpenAI Codex"))
for _, alias := range []string{filepath.Join(root, "Microsoft", "WindowsApps", "Codex.exe"), filepath.Join(root, "Microsoft", "WindowsApps", "codex.exe")} {
if fileExists(alias) {
addCandidate(alias)
}
}
}
for _, candidate := range candidates {
if normalized := normalizeCodexAppPath(candidate); normalized != "" {
return normalized
}
}
return ""
}
func normalizeCodexAppPath(path string) string {
path = strings.TrimSpace(path)
if path == "" {
return ""
}
if runtime.GOOS == "windows" {
if normalized := normalizeWindowsPackageAppPath(path); normalized != "" {
return normalized
}
}
if runtime.GOOS == "windows" && isWindowsAppsExecutionAlias(path) {
if fileExists(path) {
return path
}
return ""
}
if strings.EqualFold(filepath.Base(path), "Codex.exe") || strings.EqualFold(filepath.Base(path), "codex.exe") {
return filepath.Dir(path)
}
if strings.EqualFold(filepath.Ext(path), ".app") {
return path
}
if fileExists(path) && !isDir(path) {
return filepath.Dir(path)
}
if fileExists(filepath.Join(path, "Codex.exe")) || fileExists(filepath.Join(path, "codex.exe")) {
return path
}
for _, subdir := range []string{"app", "VFS", filepath.Join("VFS", "ProgramFilesX64", "Codex"), filepath.Join("VFS", "ProgramFilesX64", "OpenAI", "Codex")} {
candidate := filepath.Join(path, subdir)
if fileExists(filepath.Join(candidate, "Codex.exe")) || fileExists(filepath.Join(candidate, "codex.exe")) {
return candidate
}
}
nested := filepath.Join(path, "app")
if isDir(nested) && (fileExists(filepath.Join(nested, "Codex.exe")) || fileExists(filepath.Join(nested, "codex.exe"))) {
return nested
}
if runtime.GOOS == "windows" {
return ""
}
if isDir(path) {
return path
}
return ""
}
func isWindowsAppsExecutionAlias(path string) bool {
if runtime.GOOS != "windows" {
return false
}
base := filepath.Base(path)
if !strings.EqualFold(base, "Codex.exe") && !strings.EqualFold(base, "codex.exe") {
return false
}
dir := strings.ToLower(filepath.ToSlash(filepath.Dir(path)))
return strings.Contains(dir, "/microsoft/windowsapps") || strings.HasSuffix(dir, "/windowsapps")
}
func isWindowsProtectedAppPackagePath(path string) bool {
if runtime.GOOS != "windows" {
return false
}
normalized := strings.ToLower(filepath.ToSlash(path))
return strings.Contains(normalized, "/program files/windowsapps/openai.codex_") ||
strings.HasPrefix(normalized, "c:/program files/windowsapps/openai.codex_")
}
func normalizeWindowsPackageAppPath(path string) string {
packageName := windowsPackageNameFromPath(path)
if !isWindowsCodexPackageName(packageName) {
return ""
}
parts := splitPathParts(path)
for i, part := range parts {
if strings.EqualFold(part, packageName) {
prefix := strings.Join(parts[:i+1], string(os.PathSeparator))
if strings.Contains(path, `\`) {
prefix = strings.Join(parts[:i+1], `\`)
}
if strings.HasSuffix(strings.ToLower(filepath.ToSlash(path)), "/app") || strings.EqualFold(filepath.Base(path), "Codex.exe") || strings.EqualFold(filepath.Base(path), "codex.exe") {
return filepath.Join(prefix, "app")
}
return filepath.Join(prefix, "app")
}
}
if strings.EqualFold(filepath.Base(path), "app") {
return path
}
return filepath.Join(path, "app")
}
func windowsCodexExecutionAlias() string {
if runtime.GOOS != "windows" {
return ""
}
if alias := strings.TrimSpace(os.Getenv("CODEX_APP_EXECUTION_ALIAS")); alias != "" {
return alias
}
for _, root := range []string{os.Getenv("LOCALAPPDATA"), filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local")} {
if strings.TrimSpace(root) == "" {
continue
}
return filepath.Join(root, "Microsoft", "WindowsApps", "Codex.exe")
}
return ""
}
func windowsAppPackageRoots() []string {
var roots []string
add := func(path string) {
path = strings.TrimSpace(path)
if path == "" {
return
}
for _, existing := range roots {
if strings.EqualFold(existing, path) {
return
}
}
roots = append(roots, path)
}
for _, root := range []string{os.Getenv("ProgramFiles"), os.Getenv("ProgramW6432")} {
if root != "" {
add(filepath.Join(root, "WindowsApps"))
}
}
add(`C:\Program Files\WindowsApps`)
return roots
}
func findLatestWindowsCodexAppDirFromRoots(roots []string) string {
var best string
for _, root := range roots {
if candidate := findLatestWindowsCodexAppDir(root); candidate != "" {
if best == "" || compareVersions(windowsPackageVersionFromPath(candidate), windowsPackageVersionFromPath(best)) > 0 {
best = candidate
}
}
}
return best
}
func findLatestWindowsCodexAppDir(root string) string {
entries, err := os.ReadDir(root)
if err != nil {
return ""
}
var best string
for _, entry := range entries {
if !entry.IsDir() {
continue
}
name := entry.Name()
if !isWindowsCodexPackageName(name) || windowsPackageVersionFromName(name) == "" {
continue
}
path := filepath.Join(root, name)
if app := filepath.Join(path, "app"); isDir(app) {
path = app
}
if best == "" || compareVersions(windowsPackageVersionFromPath(path), windowsPackageVersionFromPath(best)) > 0 {
best = path
}
}
return best
}
func packagedWindowsAppUserModelID(path string) string {
packageName := windowsPackageNameFromPath(path)
if !isWindowsCodexPackageName(packageName) {
return ""
}
_, publisherID, ok := strings.Cut(packageName, "__")
if !ok || publisherID == "" {
return ""
}
return "OpenAI.Codex_" + publisherID + "!App"
}
func isWindowsCodexPackageName(name string) bool {
lower := strings.ToLower(strings.TrimSpace(name))
return strings.HasPrefix(lower, "openai.codex_") && strings.Contains(name, "__")
}
func windowsPackageNameFromPath(path string) string {
parts := splitPathParts(path)
if len(parts) == 0 {
return ""
}
last := parts[len(parts)-1]
if strings.EqualFold(last, "Codex.exe") || strings.EqualFold(last, "codex.exe") {
if len(parts) >= 3 && strings.EqualFold(parts[len(parts)-2], "app") {
return parts[len(parts)-3]
}
if len(parts) < 2 {
return ""
}
return parts[len(parts)-2]
}
if strings.EqualFold(last, "app") {
if len(parts) < 2 {
return ""
}
return parts[len(parts)-2]
}
return last
}
func windowsPackageVersionFromPath(path string) string {
return windowsPackageVersionFromName(windowsPackageNameFromPath(path))
}
func windowsPackageVersionFromName(name string) string {
if !isWindowsCodexPackageName(name) {
return ""
}
rest := strings.TrimSpace(name)[len("OpenAI.Codex_"):]
version, _, ok := strings.Cut(rest, "_")
if !ok || version == "" {
return ""
}
for _, part := range strings.Split(version, ".") {
if part == "" {
return ""
}
if _, err := strconv.Atoi(part); err != nil {
return ""
}
}
return version
}
func splitPathParts(path string) []string {
return strings.FieldsFunc(filepath.ToSlash(strings.TrimSpace(path)), func(r rune) bool {
return r == '/' || r == '\\'
})
}
func codexDetectionPayload(saved, resolved string) map[string]any {
payload := map[string]any{
"savedPath": nullableString(saved),
"resolvedPath": nullableString(resolved),
"status": "missing",
"message": "未检测到 Codex 应用。",
"candidates": []string{},
}
if resolved != "" {
payload["status"] = "found"
payload["message"] = "已检测到 Codex 应用。"
payload["executable"] = buildCodexExecutable(resolved)
if appUserModelID := packagedWindowsAppUserModelID(resolved); appUserModelID != "" {
payload["appUserModelId"] = appUserModelID
}
return payload
}
if runtime.GOOS == "windows" {
payload["message"] = "Windows 自动探测没有找到 Codex。若 Codex 已安装,请手动选择 Codex.exe 或安装目录。"
payload["candidates"] = windowsCodexDetectionHints()
}
return payload
}
func codexLaunchPayload(appPath string) map[string]any {
payload := map[string]any{
"ready": false,
"method": "missing",
"methodLabel": "未检测到启动方式",
"path": nullableString(appPath),
"executable": "",
"appUserModelId": "",
"message": "未检测到 Codex 应用,无法启动。",
}
if appPath == "" {
return payload
}
if runtime.GOOS == "windows" {
if executable := buildCodexExecutable(appPath); strings.TrimSpace(executable) != "" && fileExists(executable) {
payload["ready"] = true
payload["method"] = "executable"
payload["methodLabel"] = "可执行文件启动"
payload["executable"] = executable
payload["message"] = "将按 1.1.12 的方式直接启动 Codex.exe。"
if appUserModelID := packagedWindowsAppUserModelID(appPath); appUserModelID != "" {
payload["appUserModelId"] = appUserModelID
}
return payload
}
if appUserModelID := packagedWindowsAppUserModelID(appPath); appUserModelID != "" {
payload["ready"] = true
payload["method"] = "packaged_activation"
payload["methodLabel"] = "MSIX 应用激活"
payload["appUserModelId"] = appUserModelID
payload["message"] = "未直接读取到 Codex.exe,将通过 AppUserModelID 激活 Windows Store/MSIX 版。"
return payload
}
}
executable := buildCodexExecutable(appPath)
if strings.TrimSpace(executable) == "" {
payload["message"] = "已识别到 Codex 目录,但没有找到可执行文件。"
return payload
}
if runtime.GOOS == "windows" && !isWindowsAppsExecutionAlias(executable) && !fileExists(executable) {
payload["method"] = "executable_missing"
payload["executable"] = executable
payload["message"] = "已推断 Codex.exe 位置,但文件不存在。"
return payload
}