-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy pathrepair.go
More file actions
2183 lines (2080 loc) · 66.7 KB
/
Copy pathrepair.go
File metadata and controls
2183 lines (2080 loc) · 66.7 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"
"crypto/sha256"
"database/sql"
"encoding/hex"
"encoding/json"
"errors"
"fmt"
"io"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
_ "modernc.org/sqlite"
)
type codexCommandOutput struct {
Command string
Output string
Err error
}
var runCodexPluginCommand = defaultRunCodexPluginCommand
var currentRuntimeGOOS = func() string { return runtime.GOOS }
var detectProviderSyncActiveProcesses = defaultConversationHistoryDirectProcesses
var applyProviderSyncGlobalStateUpdate = applyGlobalStateUpdate
var acquireProviderSyncLauncherGuard = defaultConversationHistoryLauncherGuard
const (
providerSyncLockTTL = 30 * time.Minute
providerSyncUnknownOwnerLockTTL = 2 * time.Minute
)
func (s *server) syncProvidersNow() commandResult {
result := runProviderSync(codexHomeDir())
status := "ok"
if result.Status == "skipped" {
status = "not_checked"
} else if result.Status == "failed" {
status = "failed"
}
message := "模式对话历史已检查,无需更新。"
if result.Status == "skipped" {
message = "模式对话历史同步暂未执行且未修改聊天记录,可重试。"
if detail := providerSyncExtraMessage(result.Message); detail != "" {
message += " " + detail
}
} else if result.Status == "failed" {
switch {
case result.Partial:
message = "模式对话历史同步失败且回滚失败,可能处于部分同步状态。 " + result.Message
case result.RollbackStatus == "rolled_back":
message = "模式对话历史同步失败,已回滚本次聊天记录改动。 " + result.Message
default:
message = "模式对话历史同步失败,未完成同步。 " + result.Message
}
} else if result.ChangedSessionFiles > 0 || result.SQLiteRowsUpdated > 0 {
message = fmt.Sprintf("模式对话历史已同步:%d 个会话文件,%d 行索引。", result.ChangedSessionFiles, result.SQLiteRowsUpdated)
}
return commandResult{
"status": status,
"message": strings.TrimSpace(message),
"syncStatus": result.Status,
"targetProvider": result.TargetProvider,
"changedSessionFiles": result.ChangedSessionFiles,
"sqliteRowsUpdated": result.SQLiteRowsUpdated,
"backupDir": result.BackupDir,
"syncMessage": result.Message,
"partial": result.Partial,
"rollbackStatus": result.RollbackStatus,
}
}
func (s *server) repairCodexPlugins() commandResult {
result := repairCodexConfig(codexHomeDir(), codexConfigRepairOptions{Plugins: true, RefreshMarketplaces: true})
status := "ok"
if result.Status == "failed" {
status = "failed"
}
return commandResult{
"status": status,
"message": result.Message,
"backupPath": result.BackupPath,
"pluginCount": result.PluginCount,
"marketplaceCount": result.MarketplaceCount,
"mcpServerCount": result.MCPServerCount,
"marketplaceRefreshStatus": result.MarketplaceRefreshStatus,
"marketplaceRefreshSummary": result.MarketplaceRefreshSummary,
"marketplaceRefreshError": result.MarketplaceRefreshError,
"configChanged": result.PluginConfigChanged,
"goalsEnabled": result.GoalsEnabled,
"configPath": filepath.Join(codexHomeDir(), "config.toml"),
"codexHome": codexHomeDir(),
}
}
func (s *server) repairCodexGoals() commandResult {
result := repairCodexConfig(codexHomeDir(), codexConfigRepairOptions{Goals: true})
status := "ok"
if result.Status == "failed" {
status = "failed"
}
return commandResult{
"status": status,
"message": result.Message,
"backupPath": result.BackupPath,
"goalsEnabled": result.GoalsEnabled,
"configChanged": result.GoalsConfigChanged,
"configPath": filepath.Join(codexHomeDir(), "config.toml"),
"codexHome": codexHomeDir(),
}
}
func providerSyncExtraMessage(message string) string {
message = strings.TrimSpace(message)
if message == "" || message == "Provider sync complete" || message == "Provider sync already up to date" {
return ""
}
return message
}
func repairCodexConfig(home string, options codexConfigRepairOptions) codexConfigRepairResult {
if !isDir(home) {
return codexConfigRepairResult{Status: "failed", Message: "Codex home 不存在:" + home}
}
configPath := filepath.Join(home, "config.toml")
data, err := os.ReadFile(configPath)
if err != nil {
return codexConfigRepairResult{Status: "failed", Message: "读取 config.toml 失败:" + err.Error()}
}
original := string(data)
updated := original
result := codexConfigRepairResult{Status: "ok"}
if options.Plugins {
var pluginCount, marketplaceCount, mcpCount int
updated, pluginCount, marketplaceCount, mcpCount = repairCodexPluginConfig(home, updated)
result.PluginCount = pluginCount
result.MarketplaceCount = marketplaceCount
result.MCPServerCount = mcpCount
result.PluginConfigChanged = updated != original
}
beforeGoals := updated
if options.Goals {
updated = repairCodexGoalsConfig(updated)
result.GoalsEnabled = true
result.GoalsConfigChanged = updated != beforeGoals
}
changed := updated != original
if updated != original {
backupPath, err := writeCodexConfigWithBackup(configPath, updated, "config-repair")
if err != nil {
return codexConfigRepairResult{Status: "failed", Message: "写入 config.toml 失败:" + err.Error(), BackupPath: backupPath}
}
result.BackupPath = backupPath
}
if options.Plugins && options.RefreshMarketplaces {
refresh := refreshCodexMarketplaces(home)
result.MarketplaceRefreshStatus = refresh.Status
result.MarketplaceRefreshSummary = refresh.Summary
result.MarketplaceRefreshError = refresh.Error
if refresh.Status == "failed" {
result.Status = "failed"
}
data, err := os.ReadFile(configPath)
if err != nil {
result.Status = "failed"
result.MarketplaceRefreshError = strings.TrimSpace(result.MarketplaceRefreshError + ";刷新后读取 config.toml 失败:" + err.Error())
} else {
refreshedOriginal := string(data)
refreshedUpdated, pluginCount, marketplaceCount, mcpCount := repairCodexPluginConfig(home, refreshedOriginal)
result.PluginCount = pluginCount
result.MarketplaceCount = marketplaceCount
result.MCPServerCount = mcpCount
if refreshedUpdated != refreshedOriginal {
backupPath, err := writeCodexConfigWithBackup(configPath, refreshedUpdated, "config-repair")
if err != nil {
return codexConfigRepairResult{Status: "failed", Message: "写入刷新后的 config.toml 失败:" + err.Error(), BackupPath: backupPath}
}
if result.BackupPath == nil {
result.BackupPath = backupPath
}
result.PluginConfigChanged = true
changed = true
}
}
}
result.Message = codexConfigRepairMessage(result, options, changed)
return result
}
func repairCodexPluginConfig(home, contents string) (string, int, int, int) {
updated := contents
marketplaces := discoverCodexMarketplaces(home)
for _, marketplace := range marketplaces {
if strings.TrimSpace(marketplace.Source) == "" {
continue
}
updated = repairCodexMarketplaceTable(updated, marketplace)
}
plugins := discoverCachedPluginEnables(home)
for _, plugin := range plugins {
table := fmt.Sprintf("plugins.%s", quoteToml(plugin.Name+"@"+plugin.Marketplace))
if !hasTable(updated, table) {
updated = appendTomlBlock(updated, []string{
"[" + table + "]",
"enabled = true",
})
}
}
updated, mcpCount := repairNodeReplMCPConfig(home, updated)
return updated, len(plugins), len(marketplaces), mcpCount
}
func repairCodexMarketplaceTable(contents string, marketplace marketplaceSpec) string {
table := "marketplaces." + marketplace.Name
lastUpdated := quoteToml(time.Now().UTC().Format(time.RFC3339))
if !hasTable(contents, table) {
return appendTomlBlock(contents, []string{
"[" + table + "]",
"last_updated = " + lastUpdated,
`source_type = "local"`,
"source = " + quoteToml(marketplace.Source),
})
}
values := tableValues(contents, table)
sourceType := strings.TrimSpace(unquoteToml(values["source_type"]))
source := strings.TrimSpace(unquoteToml(values["source"]))
if sourceType == "local" && samePath(source, marketplace.Source) {
return contents
}
updated := upsertTableKey(contents, table, "last_updated", lastUpdated)
updated = upsertTableKey(updated, table, "source_type", quoteToml("local"))
updated = upsertTableKey(updated, table, "source", quoteToml(marketplace.Source))
return updated
}
type marketplaceRefreshResult struct {
Status string
Summary string
Error string
}
func refreshCodexMarketplaces(home string) marketplaceRefreshResult {
if !isDir(home) {
return marketplaceRefreshResult{Status: "skipped", Summary: "Codex home 不存在,已跳过 marketplace 刷新。"}
}
if !hasRefreshableCodexMarketplaces(home) {
return marketplaceRefreshResult{Status: "skipped", Summary: "未发现已配置或本地可用的 Codex marketplace。"}
}
commands := [][]string{
{"plugin", "marketplace", "upgrade"},
{"plugin", "marketplace", "list"},
{"plugin", "list"},
}
var summaries []string
var failures []string
for _, args := range commands {
output := runCodexPluginCommand(home, args...)
label := "codex " + strings.Join(args, " ")
if strings.TrimSpace(output.Command) != "" {
label = output.Command
}
if output.Err != nil {
failures = append(failures, label+": "+output.Err.Error()+outputPreview(output.Output))
continue
}
summaries = append(summaries, label+outputPreview(output.Output))
}
if len(failures) > 0 {
return marketplaceRefreshResult{
Status: "failed",
Summary: strings.Join(summaries, ";"),
Error: strings.Join(failures, ";"),
}
}
return marketplaceRefreshResult{Status: "ok", Summary: strings.Join(summaries, ";")}
}
func hasRefreshableCodexMarketplaces(home string) bool {
if len(discoverCodexMarketplaces(home)) > 0 {
return true
}
contents := readFile(filepath.Join(home, "config.toml"))
for _, line := range splitLines(contents) {
if strings.HasPrefix(strings.TrimSpace(line), "[marketplaces.") {
return true
}
}
return false
}
func defaultRunCodexPluginCommand(home string, args ...string) codexCommandOutput {
command := codexCLIExecutable()
label := "codex " + strings.Join(args, " ")
if strings.TrimSpace(command) == "" {
return codexCommandOutput{Command: label, Err: fmt.Errorf("未找到可用的 Codex CLI(已跳过 WindowsApps alias)")}
}
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
defer cancel()
cmd := exec.CommandContext(ctx, command, args...)
hideSubprocessWindow(cmd)
cmd.Env = append(os.Environ(), "CODEX_HOME="+home)
out, err := cmd.CombinedOutput()
if ctx.Err() == context.DeadlineExceeded {
err = ctx.Err()
}
return codexCommandOutput{Command: label, Output: string(out), Err: err}
}
func codexCLIExecutable() string {
if path := usableCodexCLIExecutable(); path != "" {
return path
}
if path := bundledCodexCLIExecutable(); path != "" {
return path
}
if path, err := exec.LookPath("codex"); err == nil {
if usableCodexCLIPath(path) {
return path
}
}
if currentRuntimeGOOS() != "windows" {
return "codex"
}
return ""
}
func bundledCodexCLIExecutable() string {
resourcesDir := codexResourcesDir()
candidate := filepath.Join(resourcesDir, "codex")
if currentRuntimeGOOS() == "windows" {
candidate += ".exe"
}
if usableCodexCLIPath(candidate) {
return candidate
}
return ""
}
func usableCodexCLIExecutable() string {
if explicit := strings.TrimSpace(os.Getenv("CODEX_CLI_PATH")); usableCodexCLIPath(explicit) {
return explicit
}
if currentRuntimeGOOS() != "windows" {
return ""
}
for _, candidate := range discoverWindowsCodexRuntimeCLIs() {
if usableCodexCLIPath(candidate) {
return candidate
}
}
if path, err := exec.LookPath("codex.exe"); err == nil && usableCodexCLIPath(path) {
return path
}
return ""
}
func discoverWindowsCodexRuntimeCLIs() []string {
var candidates []string
add := func(path string) {
path = strings.TrimSpace(path)
if path != "" {
candidates = append(candidates, path)
}
}
for _, root := range []string{os.Getenv("LOCALAPPDATA"), filepath.Join(os.Getenv("USERPROFILE"), "AppData", "Local")} {
if strings.TrimSpace(root) == "" {
continue
}
binRoot := filepath.Join(root, "OpenAI", "Codex", "bin")
matches, _ := filepath.Glob(filepath.Join(binRoot, "*", "codex.exe"))
sort.Strings(matches)
for i := len(matches) - 1; i >= 0; i-- {
add(matches[i])
}
add(filepath.Join(binRoot, "codex.exe"))
}
return candidates
}
func usableCodexCLIPath(path string) bool {
if strings.TrimSpace(path) == "" || !fileExists(path) {
return false
}
if currentRuntimeGOOS() == "windows" && isWindowsAppsPath(path) {
return false
}
return true
}
func isWindowsAppsPath(path string) bool {
normalized := strings.ReplaceAll(filepath.Clean(path), `\`, `/`)
normalized = strings.ToLower(filepath.ToSlash(normalized))
for _, part := range strings.Split(normalized, "/") {
if part == "windowsapps" {
return true
}
}
return false
}
func outputPreview(output string) string {
output = strings.TrimSpace(output)
if output == "" {
return ""
}
output = strings.Join(strings.Fields(output), " ")
if len(output) > 240 {
output = output[:240] + "..."
}
return "(" + output + ")"
}
func repairCodexGoalsConfig(contents string) string {
return upsertTableKey(contents, "features", "goals", "true")
}
func codexConfigRepairMessage(result codexConfigRepairResult, options codexConfigRepairOptions, changed bool) string {
var parts []string
if options.Plugins {
if result.PluginCount == 0 {
parts = append(parts, "未发现可恢复的插件缓存")
} else if result.PluginConfigChanged {
parts = append(parts, fmt.Sprintf("已恢复插件配置:%d 个插件、%d 个市场源", result.PluginCount, result.MarketplaceCount))
} else {
parts = append(parts, fmt.Sprintf("插件配置已完整:%d 个插件、%d 个市场源", result.PluginCount, result.MarketplaceCount))
}
if options.RefreshMarketplaces {
switch result.MarketplaceRefreshStatus {
case "ok":
parts = append(parts, "Codex 插件市场已刷新/重读")
case "skipped":
parts = append(parts, "Codex 插件市场刷新已跳过")
case "failed":
if strings.TrimSpace(result.MarketplaceRefreshError) != "" {
parts = append(parts, "Codex 插件市场刷新失败:"+result.MarketplaceRefreshError)
} else {
parts = append(parts, "Codex 插件市场刷新失败")
}
}
}
}
if options.Goals {
if result.GoalsConfigChanged {
parts = append(parts, "已开启追求目标功能 features.goals")
} else {
parts = append(parts, "追求目标功能已开启")
}
}
if changed && result.BackupPath != nil {
parts = append(parts, "已备份原配置:"+*result.BackupPath)
}
if len(parts) == 0 {
return "没有需要修复的配置。"
}
return strings.Join(parts, ";") + "。"
}
func backupCodexConfig(configPath, label string) (string, error) {
backupPath := fmt.Sprintf("%s.before-%s-%s.bak", configPath, label, time.Now().Format("20060102150405"))
if fileExists(backupPath) {
for index := 2; ; index++ {
candidate := fmt.Sprintf("%s.before-%s-%s-%d.bak", configPath, label, time.Now().Format("20060102150405"), index)
if !fileExists(candidate) {
backupPath = candidate
break
}
}
}
return backupPath, copyFileIfExists(configPath, backupPath)
}
func discoverCodexMarketplaces(home string) []marketplaceSpec {
paths := []marketplaceSpec{
{Name: "openai-bundled", Source: filepath.Join(home, ".tmp", "bundled-marketplaces", "openai-bundled")},
{Name: "openai-curated", Source: filepath.Join(home, ".tmp", "plugins")},
}
if userHome, err := os.UserHomeDir(); err == nil && userHome != "" {
paths = append(paths, marketplaceSpec{Name: "openai-primary-runtime", Source: filepath.Join(userHome, ".cache", "codex-runtimes", "codex-primary-runtime", "plugins", "openai-primary-runtime")})
}
var marketplaces []marketplaceSpec
for _, marketplace := range paths {
if codexMarketplaceExists(marketplace.Source) {
marketplaces = append(marketplaces, marketplace)
}
}
return marketplaces
}
func codexMarketplaceExists(path string) bool {
if !isDir(path) {
return false
}
return fileExists(filepath.Join(path, ".agents", "plugins", "marketplace.json")) || isDir(filepath.Join(path, "plugins"))
}
func discoverCachedPluginEnables(home string) []pluginEnableSpec {
cacheRoot := filepath.Join(home, "plugins", "cache")
marketplaces := []string{"openai-curated", "openai-primary-runtime", "openai-bundled"}
var plugins []pluginEnableSpec
seen := map[string]bool{}
for _, marketplace := range marketplaces {
root := filepath.Join(cacheRoot, marketplace)
if !isDir(root) {
continue
}
entries, err := os.ReadDir(root)
if err != nil {
continue
}
for _, entry := range entries {
if !entry.IsDir() {
continue
}
name := entry.Name()
if !cachedPluginExists(filepath.Join(root, name)) {
continue
}
key := name + "@" + marketplace
if seen[key] {
continue
}
seen[key] = true
plugins = append(plugins, pluginEnableSpec{Name: name, Marketplace: marketplace})
}
}
sort.Slice(plugins, func(i, j int) bool {
left := plugins[i].Marketplace + "/" + plugins[i].Name
right := plugins[j].Marketplace + "/" + plugins[j].Name
return left < right
})
return plugins
}
func cachedPluginExists(path string) bool {
if fileExists(filepath.Join(path, ".codex-plugin", "plugin.json")) {
return true
}
entries, err := os.ReadDir(path)
if err != nil {
return false
}
for _, entry := range entries {
if entry.IsDir() && fileExists(filepath.Join(path, entry.Name(), ".codex-plugin", "plugin.json")) {
return true
}
}
return false
}
func repairNodeReplMCPConfig(home, contents string) (string, int) {
resourcesDir := codexResourcesDir()
nodeReplPath := filepath.Join(resourcesDir, "node_repl")
nodePath := filepath.Join(resourcesDir, "node")
if !fileExists(nodeReplPath) {
nodeReplPath = companionBinaryPath(managerBinary)
}
if !fileExists(nodePath) {
nodePath = companionBinaryPath(managerBinary)
}
updated := removeTable(removeTable(contents, "mcp_servers.node_repl"), "mcp_servers.node_repl.env")
lines := []string{
"[mcp_servers.node_repl]",
"args = []",
"command = " + quoteToml(nodeReplPath),
"startup_timeout_sec = 120",
"",
"[mcp_servers.node_repl.env]",
`BROWSER_USE_AVAILABLE_BACKENDS = "chrome,iab"`,
`BROWSER_USE_MARKETPLACE_NAME = "openai-bundled"`,
"CODEX_HOME = " + quoteToml(home),
`NODE_REPL_NATIVE_PIPE_CONNECT_TIMEOUT_MS = "1000"`,
`NODE_REPL_NODE_MODULE_DIRS = ""`,
"NODE_REPL_NODE_PATH = " + quoteToml(nodePath),
}
if codexCLIPath := codexCLIExecutable(); codexCLIPath != "" && fileExists(codexCLIPath) {
lines = append(lines[:8], append([]string{"CODEX_CLI_PATH = " + quoteToml(codexCLIPath)}, lines[8:]...)...)
}
if hashes := trustedBrowserClientHashes(home); len(hashes) > 0 {
lines = append(lines, "NODE_REPL_TRUSTED_BROWSER_CLIENT_SHA256S = "+quoteToml(strings.Join(hashes, ",")))
}
lines = append(lines,
"NODE_REPL_TRUSTED_CODE_PATHS = "+quoteToml(home),
`NODE_REPL_UNTRUSTED_ENV_ALLOWLIST = "BROWSER_USE_MARKETPLACE_NAME"`,
)
if servicePath := bundledComputerUseServicePath(home); servicePath != "" {
lines = append(lines, "SKY_CUA_SERVICE_PATH = "+quoteToml(servicePath))
}
return appendTomlBlock(updated, lines), 1
}
func trustedBrowserClientHashes(home string) []string {
var hashes []string
seen := map[string]bool{}
pattern := filepath.Join(home, "plugins", "cache", "openai-bundled", "browser", "*", "scripts", "browser-client.mjs")
matches, _ := filepath.Glob(pattern)
sort.Strings(matches)
for _, path := range matches {
data, err := os.ReadFile(path)
if err != nil {
continue
}
sum := sha256.Sum256(data)
hash := hex.EncodeToString(sum[:])
if !seen[hash] {
seen[hash] = true
hashes = append(hashes, hash)
}
}
return hashes
}
func bundledComputerUseServicePath(home string) string {
candidates := []string{
filepath.Join(home, ".tmp", "bundled-marketplaces", "openai-bundled", "plugins", "computer-use", "Codex Computer Use.app"),
}
matches, _ := filepath.Glob(filepath.Join(home, "plugins", "cache", "openai-bundled", "computer-use", "*", "Codex Computer Use.app"))
sort.Strings(matches)
candidates = append(candidates, matches...)
for i := len(candidates) - 1; i >= 0; i-- {
if isDir(candidates[i]) {
return candidates[i]
}
}
return ""
}
func codexResourcesDir() string {
if path := resolveCodexApp(loadSettings().CodexAppPath); path != "" && runtime.GOOS == "darwin" && strings.EqualFold(filepath.Ext(path), ".app") {
return filepath.Join(path, "Contents", "Resources")
}
if path := resolveCodexApp(loadSettings().CodexAppPath); path != "" && runtime.GOOS == "windows" {
if resources := filepath.Join(path, "resources"); isDir(resources) {
return resources
}
if resources := filepath.Join(path, "app", "resources"); isDir(resources) {
return resources
}
}
if runtime.GOOS == "darwin" && isDir("/Applications/ChatGPT.app/Contents/Resources") {
return "/Applications/ChatGPT.app/Contents/Resources"
}
return filepath.Dir(companionBinaryPath("codex"))
}
func appendTomlBlock(contents string, lines []string) string {
trimmedLines := append([]string{}, lines...)
for len(trimmedLines) > 0 && strings.TrimSpace(trimmedLines[len(trimmedLines)-1]) == "" {
trimmedLines = trimmedLines[:len(trimmedLines)-1]
}
if len(trimmedLines) == 0 {
return ensureTrailingNewline(contents)
}
updated := strings.TrimRight(contents, "\n")
if strings.TrimSpace(updated) != "" {
updated += "\n\n"
}
updated += strings.Join(trimmedLines, "\n")
return ensureTrailingNewline(updated)
}
func hasTable(contents, table string) bool {
header := "[" + table + "]"
for _, line := range splitLines(contents) {
if strings.TrimSpace(line) == header {
return true
}
}
return false
}
func upsertTableKey(contents, table, key, value string) string {
lines := splitLines(contents)
header := "[" + table + "]"
tableStart := -1
tableEnd := len(lines)
for i, line := range lines {
trimmed := strings.TrimSpace(line)
if strings.HasPrefix(trimmed, "[") && strings.HasSuffix(trimmed, "]") {
if tableStart >= 0 {
tableEnd = i
break
}
if trimmed == header {
tableStart = i
}
}
}
if tableStart < 0 {
return appendTomlBlock(contents, []string{header, key + " = " + value})
}
for i := tableStart + 1; i < tableEnd; i++ {
if rootLineKey(lines[i]) == key {
lines[i] = key + " = " + value
return ensureTrailingNewline(strings.Join(lines, "\n"))
}
}
lines = append(lines[:tableEnd], append([]string{key + " = " + value}, lines[tableEnd:]...)...)
return ensureTrailingNewline(strings.Join(lines, "\n"))
}
func runProviderSync(home string) providerSyncResult {
return runProviderSyncWithLock(home, true)
}
// runProviderSyncWithHeldLauncherGuard is used by the managed launcher, which
// already holds the launcher single-instance guard for its full lifetime.
func runProviderSyncWithHeldLauncherGuard(home string) providerSyncResult {
return runProviderSyncWithLock(home, false)
}
func runProviderSyncWithLock(home string, acquireLauncherGuard bool) providerSyncResult {
if !isDir(home) {
return providerSyncResult{Status: "skipped", Message: "Codex home not found: " + home, TargetProvider: "openai"}
}
releaseLock, err := acquireProviderSyncLock(home, "provider-sync")
if err != nil {
return providerSyncResult{Status: "skipped", Message: "Provider sync skipped: " + err.Error()}
}
defer releaseLock()
if acquireLauncherGuard {
releaseLauncherGuard, err := acquireProviderSyncLauncherGuard()
if err != nil {
return providerSyncResult{Status: "skipped", Message: "Provider sync skipped: " + err.Error()}
}
defer releaseLauncherGuard()
}
return runProviderSyncLocked(home)
}
// runProviderSyncLocked synchronizes history while the caller holds the
// provider-sync lock. It reads the provider only after that lock is held so a
// mode switch cannot change config.toml between provider selection and sync.
func runProviderSyncLocked(home string) providerSyncResult {
targetProvider := readCurrentProvider(filepath.Join(home, "config.toml"))
changes, err := collectSessionChanges(home, targetProvider)
if err != nil {
return providerSyncResult{Status: "skipped", Message: "Provider sync skipped: " + err.Error(), TargetProvider: targetProvider}
}
var rewriteChanges []sessionChange
for _, change := range changes {
if change.RewriteNeeded {
rewriteChanges = append(rewriteChanges, change)
}
}
sqliteCount := countSQLiteUpdates(filepath.Join(home, "state_5.sqlite"), targetProvider, changes)
globalCount, err := countGlobalStateUpdates(filepath.Join(home, ".codex-global-state.json"), changes)
if err != nil {
return providerSyncResult{Status: "skipped", Message: "Provider sync skipped: " + err.Error(), TargetProvider: targetProvider}
}
if len(rewriteChanges) == 0 && sqliteCount == 0 && globalCount == 0 {
return providerSyncResult{Status: "synced", Message: "Provider sync already up to date", TargetProvider: targetProvider}
}
if err := ensureProviderSyncWritersStopped(); err != nil {
return providerSyncResult{Status: "skipped", Message: "Provider sync skipped: " + err.Error(), TargetProvider: targetProvider}
}
backupDir, err := createProviderSyncBackup(home, targetProvider, rewriteChanges)
if err != nil {
return providerSyncResult{Status: "skipped", Message: "Provider sync skipped: " + err.Error(), TargetProvider: targetProvider}
}
if err := ensureProviderSyncWritersStopped(); err != nil {
return providerSyncFailureBeforeMutation(targetProvider, backupDir, err)
}
globalPath := filepath.Join(home, ".codex-global-state.json")
globalSnapshot, err := captureProviderSyncFileSnapshot(globalPath)
if err != nil {
return providerSyncFailureBeforeMutation(targetProvider, backupDir, err)
}
if err := applySessionChanges(rewriteChanges); err != nil {
return providerSyncSessionFailure(targetProvider, backupDir, err)
}
if err := ensureProviderSyncWritersStopped(); err != nil {
rollbackErr := rollbackProviderSyncFiles(rewriteChanges, globalSnapshot)
return providerSyncRollbackFailure(targetProvider, backupDir, err, rollbackErr)
}
if _, err := applyProviderSyncGlobalStateUpdate(globalPath, changes); err != nil {
rollbackErr := rollbackProviderSyncFiles(rewriteChanges, globalSnapshot)
return providerSyncRollbackFailure(targetProvider, backupDir, err, rollbackErr)
}
if err := ensureProviderSyncWritersStopped(); err != nil {
rollbackErr := rollbackProviderSyncFiles(rewriteChanges, globalSnapshot)
return providerSyncRollbackFailure(targetProvider, backupDir, err, rollbackErr)
}
sqliteRows, sqliteErr := applySQLiteUpdates(filepath.Join(home, "state_5.sqlite"), targetProvider, changes)
if sqliteErr != nil {
rollbackErr := rollbackProviderSyncFiles(rewriteChanges, globalSnapshot)
return providerSyncRollbackFailure(targetProvider, backupDir, sqliteErr, rollbackErr)
}
pruneProviderSyncBackups(home)
return providerSyncResult{Status: "synced", Message: "Provider sync complete", TargetProvider: targetProvider, BackupDir: &backupDir, ChangedSessionFiles: len(rewriteChanges), SQLiteRowsUpdated: sqliteRows}
}
func acquireProviderSyncLock(home, operation string) (func(), error) {
lockDir := filepath.Join(home, "tmp", "provider-sync.lock")
if err := os.MkdirAll(filepath.Dir(lockDir), 0o755); err != nil {
return nil, err
}
lockAcquired := false
if err := os.Mkdir(lockDir, 0o755); err != nil {
if stale, reason := providerSyncLockStale(lockDir, time.Now()); stale {
appendDiagnosticLog("provider_sync.stale_lock_removed", map[string]any{"lock": lockDir, "reason": reason})
_ = os.RemoveAll(lockDir)
if retryErr := os.Mkdir(lockDir, 0o755); retryErr == nil {
lockAcquired = true
}
}
if !lockAcquired {
return nil, fmt.Errorf("Provider sync lock exists: %s", lockDir)
}
} else {
lockAcquired = true
}
release := func() { _ = os.RemoveAll(lockDir) }
owner := map[string]any{"pid": os.Getpid(), "startedAt": time.Now().Unix(), "operation": strings.TrimSpace(operation)}
ownerData, err := json.Marshal(owner)
if err != nil {
release()
return nil, err
}
if err := os.WriteFile(filepath.Join(lockDir, "owner.json"), ownerData, 0o644); err != nil {
release()
return nil, err
}
return release, nil
}
func acquireProviderSyncMutationGuards(home, operation string) (func(), error) {
releaseProviderLock, err := acquireProviderSyncLock(home, operation)
if err != nil {
return nil, err
}
releaseLauncherGuard, err := acquireProviderSyncLauncherGuard()
if err != nil {
releaseProviderLock()
return nil, err
}
return func() {
releaseLauncherGuard()
releaseProviderLock()
}, nil
}
func ensureProviderSyncWritersStopped() error {
active, err := detectProviderSyncActiveProcesses()
if err != nil {
return fmt.Errorf("检查 ChatGPT/Codex 运行状态失败:%w", err)
}
active = uniqueConversationHistoryProcessNames(active)
if len(active) > 0 {
return fmt.Errorf("请先完全退出 ChatGPT 和 Codex 后重试(仍在运行:%s)", strings.Join(active, "、"))
}
return nil
}
func providerSyncFailureBeforeMutation(targetProvider, backupDir string, operationErr error) providerSyncResult {
return providerSyncResult{
Status: "failed",
Message: "Provider sync failed before history changes: " + operationErr.Error(),
TargetProvider: targetProvider,
BackupDir: &backupDir,
RollbackStatus: "not_started",
}
}
func providerSyncSessionFailure(targetProvider, backupDir string, operationErr error) providerSyncResult {
var mutationErr *providerSyncMutationError
if errors.As(operationErr, &mutationErr) {
if mutationErr.RollbackErr == nil {
rollbackStatus := "rolled_back"
message := "Provider sync failed: " + mutationErr.OperationErr.Error() + "; provider sync changes were rolled back"
if mutationErr.AppliedFiles == 0 {
rollbackStatus = "not_started"
message = "Provider sync failed before a session file was changed: " + mutationErr.OperationErr.Error()
}
return providerSyncResult{
Status: "failed",
Message: message,
TargetProvider: targetProvider,
BackupDir: &backupDir,
RollbackStatus: rollbackStatus,
}
}
return providerSyncResult{
Status: "failed",
Message: "Provider sync failed: " + mutationErr.OperationErr.Error() + "; rollback failed and history may be partially synchronized: " + mutationErr.RollbackErr.Error(),
TargetProvider: targetProvider,
BackupDir: &backupDir,
Partial: true,
RollbackStatus: "rollback_failed",
}
}
return providerSyncResult{
Status: "failed",
Message: "Provider sync failed and history state may be partial: " + operationErr.Error(),
TargetProvider: targetProvider,
BackupDir: &backupDir,
Partial: true,
RollbackStatus: "rollback_unknown",
}
}
func providerSyncRollbackFailure(targetProvider, backupDir string, operationErr, rollbackErr error) providerSyncResult {
message := "Provider sync failed: " + operationErr.Error()
if rollbackErr == nil {
message += "; provider sync changes were rolled back"
return providerSyncResult{Status: "failed", Message: message, TargetProvider: targetProvider, BackupDir: &backupDir, RollbackStatus: "rolled_back"}
}
message += "; rollback failed and history may be partially synchronized: " + rollbackErr.Error()
return providerSyncResult{Status: "failed", Message: message, TargetProvider: targetProvider, BackupDir: &backupDir, Partial: true, RollbackStatus: "rollback_failed"}
}
func rollbackProviderSyncFiles(changes []sessionChange, globalSnapshot providerSyncFileSnapshot) error {
if err := ensureProviderSyncWritersStopped(); err != nil {
return fmt.Errorf("rollback not attempted because a history writer is active: %w", err)
}
globalErr := restoreProviderSyncFileSnapshot(globalSnapshot)
sessionErr := restoreSessionChanges(changes)
return errors.Join(globalErr, sessionErr)
}
func providerSyncLockStale(lockDir string, now time.Time) (bool, string) {
var owner struct {
PID int `json:"pid"`
StartedAt int64 `json:"startedAt"`
}
if err := readJSON(filepath.Join(lockDir, "owner.json"), &owner); err == nil {
if owner.PID <= 0 && owner.StartedAt <= 0 {
return providerSyncUnknownOwnerLockStale(lockDir, now, "owner_invalid")
}
if owner.PID > 0 {
if providerSyncOwnerProcessRunning(owner.PID) {
return false, "owner_active"
}
return true, "owner_process_missing"
}
startedAt := time.Unix(owner.StartedAt, 0)
if owner.StartedAt > 0 && now.Sub(startedAt) > providerSyncLockTTL {
return true, "owner_timeout"
}
return false, "owner_active"
}
return providerSyncUnknownOwnerLockStale(lockDir, now, "owner_missing")
}
func providerSyncUnknownOwnerLockStale(lockDir string, now time.Time, reason string) (bool, string) {
info, err := os.Stat(lockDir)
if err != nil {
return true, "lock_stat_failed"
}
if now.Sub(info.ModTime()) > providerSyncUnknownOwnerLockTTL {
return true, reason + "_timeout"
}
return false, reason + "_recent"
}
func providerSyncOwnerProcessRunning(pid int) bool {
if pid <= 0 {
return false
}
if pid == os.Getpid() {
return true
}
running, err := processIDRunning(pid)
if err != nil {
// A detection failure must not make another process's active lock look
// stale, because deleting a live maintenance lock can corrupt history.
return true
}
return running
}
func readCurrentProvider(path string) string {
data, err := os.ReadFile(path)
if err != nil {
return "openai"
}
provider := rootKeyString(string(data), "model_provider")
if provider == "" {
return "openai"
}
return provider
}
func collectSessionChanges(home, targetProvider string) ([]sessionChange, error) {
var files []string
for _, dirname := range []string{"sessions", "archived_sessions"} {
root := filepath.Join(home, dirname)
if !isDir(root) {
continue
}
err := filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
if err != nil {