-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathcomputer_use.go
More file actions
780 lines (741 loc) · 32.9 KB
/
computer_use.go
File metadata and controls
780 lines (741 loc) · 32.9 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
package main
import (
"encoding/json"
"fmt"
"os"
"os/exec"
"path/filepath"
"runtime"
"sort"
"strings"
"time"
)
const (
computerUsePluginName = "computer-use"
computerUseMarketplace = "openai-bundled"
computerUsePluginVersion = "0.1.0-local"
)
func (s *server) loadComputerUseStatus() commandResult {
status := loadComputerUseStatus(codexHomeDir())
message := "Computer Use 状态已读取。"
resultStatus := "ok"
if !status.Supported {
resultStatus = "unsupported"
message = "Computer Use 修复目前只支持 Windows。"
} else if !status.AllReady {
resultStatus = "not_checked"
message = "Computer Use 尚未完全可用,可以点击一键修复。"
}
payload, _ := structToMap(status)
return commandResultWithStatus(resultStatus, message, payload)
}
func (s *server) repairComputerUse() commandResult {
home := codexHomeDir()
status, err := repairComputerUse(home, runtime.GOOS, true)
payload, _ := structToMap(status)
if err != nil {
status = loadComputerUseStatus(home)
status.Platform = runtime.GOOS
status.Supported = runtime.GOOS == "windows"
payload, _ = structToMap(status)
resultStatus := "failed"
if !status.Supported {
resultStatus = "unsupported"
}
return commandResultWithStatus(resultStatus, "Computer Use 修复失败:"+err.Error(), payload)
}
return commandResultWithStatus("ok", "Computer Use 已修复;请关闭所有 Codex 窗口后,从 Codex++ 入口重新启动,让环境变量、marketplace 和插件缓存生效。", payload)
}
func commandResultWithStatus(status, message string, payload map[string]any) commandResult {
result := commandResult{"status": status, "message": message}
for key, value := range payload {
result[key] = value
}
return result
}
func structToMap(value any) (map[string]any, error) {
data, err := json.Marshal(value)
if err != nil {
return map[string]any{}, err
}
var out map[string]any
if err := json.Unmarshal(data, &out); err != nil {
return map[string]any{}, err
}
return out, nil
}
func loadComputerUseStatus(home string) computerUseStatus {
home = filepath.Clean(home)
status := computerUseStatus{
Platform: runtime.GOOS,
Supported: runtime.GOOS == "windows",
CodexHome: home,
ProcessEnv: os.Getenv("CODEX_ELECTRON_ENABLE_WINDOWS_COMPUTER_USE"),
UserEnv: computerUseUserEnv(),
MarketplaceRoot: computerUseMarketplaceRoot(home),
ConfigPath: filepath.Join(home, "config.toml"),
}
fillComputerUseFileStatus(home, &status)
return status
}
func fillComputerUseFileStatus(home string, status *computerUseStatus) {
marketplaceRoot := computerUseMarketplaceRoot(home)
marketplacePlugin := filepath.Join(marketplaceRoot, "plugins", computerUsePluginName)
marketplaceManifestPath := filepath.Join(marketplaceRoot, ".agents", "plugins", "marketplace.json")
marketplacePluginPath := filepath.Join(marketplacePlugin, ".codex-plugin", "plugin.json")
cachePluginRoot := bestComputerUseCachedPluginRoot(home)
if cachePluginRoot == "" {
cachePluginRoot = computerUseCacheLatestRoot(home)
}
cachePluginPath := filepath.Join(cachePluginRoot, ".codex-plugin", "plugin.json")
helperTransport := computerUseHelperTransportPath(cachePluginRoot)
status.CodexHome = home
status.MarketplaceRoot = marketplaceRoot
status.MarketplaceManifestPath = marketplaceManifestPath
status.MarketplacePluginPath = marketplacePluginPath
status.MarketplaceReady = isDir(marketplaceRoot)
status.MarketplaceManifest = fileExists(marketplaceManifestPath)
status.MarketplacePlugin = fileExists(marketplacePluginPath)
status.CacheLatestPath = cachePluginPath
status.CacheLatest = fileExists(cachePluginPath)
status.CacheVersion = filepath.Base(cachePluginRoot)
status.HelperTransportPath = helperTransport
status.HelperTransport = fileExists(helperTransport)
status.EnvEnabled = status.ProcessEnv == "1" || status.UserEnv == "1"
config, _ := os.ReadFile(filepath.Join(home, "config.toml"))
contents := string(config)
marketplace := tableValues(contents, "marketplaces."+computerUseMarketplace)
plugin := tableValues(contents, fmt.Sprintf("plugins.%s", quoteToml(computerUsePluginName+"@"+computerUseMarketplace)))
nodeReplEnv := tableValues(contents, "mcp_servers.node_repl.env")
windows := tableValues(contents, "windows")
status.ConfigMarketplace = strings.TrimSpace(unquoteToml(marketplace["source_type"])) == "local" && strings.TrimSpace(unquoteToml(marketplace["source"])) != ""
status.ConfigPlugin = strings.TrimSpace(plugin["enabled"]) == "true"
status.ConfigNodeRepl = strings.TrimSpace(unquoteToml(nodeReplEnv["BROWSER_USE_MARKETPLACE_NAME"])) == computerUseMarketplace
status.ConfigWindows = strings.TrimSpace(unquoteToml(windows["sandbox"])) == "unelevated"
status.ConfigReady = status.ConfigMarketplace && status.ConfigPlugin && status.ConfigWindows
status.AllReady = status.Supported && status.EnvEnabled && status.MarketplaceManifest && status.MarketplacePlugin && status.CacheLatest && status.HelperTransport && status.ConfigReady
}
func repairComputerUse(home, platform string, setUserEnv bool) (computerUseStatus, error) {
home = filepath.Clean(home)
status := loadComputerUseStatus(home)
status.Platform = platform
status.Supported = platform == "windows"
if !status.Supported {
return status, fmt.Errorf("当前平台是 %s,只支持 Windows", platform)
}
if err := os.MkdirAll(home, 0o755); err != nil {
return loadComputerUseStatus(home), fmt.Errorf("创建 Codex home 失败 %s: %w", home, err)
}
marketplaceRoot := computerUseMarketplaceRoot(home)
marketplacePlugin := filepath.Join(marketplaceRoot, "plugins", computerUsePluginName)
if err := syncBundledMarketplaceFromInstalledCodex(marketplaceRoot); err != nil {
appendDiagnosticLog("computer_use.marketplace_sync_failed", map[string]any{
"marketplace_root": marketplaceRoot,
"error": err.Error(),
})
}
if err := os.MkdirAll(marketplaceRoot, 0o755); err != nil {
return loadComputerUseStatus(home), fmt.Errorf("创建 Computer Use marketplace 目录失败 %s: %w", marketplaceRoot, err)
}
usedLocalFallback, err := materializeComputerUseMarketplacePlugin(home, marketplacePlugin)
if err != nil {
return loadComputerUseStatus(home), err
}
if err := ensureComputerUseCachedPlugin(home, marketplacePlugin, usedLocalFallback); err != nil {
return loadComputerUseStatus(home), err
}
if isDir(marketplaceRoot) {
_ = makeTreeWritable(marketplaceRoot)
}
if err := updateComputerUseMarketplaceManifest(marketplaceRoot, usedLocalFallback); err != nil {
return loadComputerUseStatus(home), fmt.Errorf("写入 marketplace manifest 失败 %s: %w", marketplaceRoot, err)
}
backupPath, err := updateComputerUseCodexConfig(home, marketplaceRoot)
if err != nil {
return loadComputerUseStatus(home), fmt.Errorf("更新 config.toml 失败: %w", err)
}
if setUserEnv {
if err := setComputerUseUserEnv(); err != nil {
return loadComputerUseStatus(home), fmt.Errorf("设置用户环境变量失败: %w", err)
}
}
status = loadComputerUseStatus(home)
status.Platform = platform
status.Supported = true
status.BackupPath = backupPath
status.AllReady = status.Supported && status.EnvEnabled && status.MarketplaceManifest && status.MarketplacePlugin && status.CacheLatest && status.HelperTransport && status.ConfigReady
if err := validateComputerUseReady(status); err != nil {
return status, err
}
return status, nil
}
func computerUseMarketplaceRoot(home string) string {
return filepath.Join(home, ".tmp", "bundled-marketplaces", computerUseMarketplace)
}
func computerUseCacheRoot(home string) string {
return filepath.Join(home, "plugins", "cache", computerUseMarketplace, computerUsePluginName)
}
func computerUseCacheLatestRoot(home string) string {
return filepath.Join(computerUseCacheRoot(home), "latest")
}
func computerUseHelperTransportPath(root string) string {
return filepath.Join(root, "node_modules", "@oai", "sky", "dist", "project", "cua", "sky_js", "src", "targets", "windows", "internal", "helper_transport.js")
}
func bestComputerUseCachedPluginRoot(home string) string {
candidates := computerUseCachedPluginRoots(home)
for _, candidate := range candidates {
if fileExists(computerUseHelperTransportPath(candidate)) {
return candidate
}
}
if len(candidates) > 0 {
return candidates[0]
}
return ""
}
func computerUseCachedPluginRoots(home string) []string {
cacheRoot := computerUseCacheRoot(home)
var roots []string
latest := computerUseCacheLatestRoot(home)
if fileExists(filepath.Join(latest, ".codex-plugin", "plugin.json")) {
roots = append(roots, latest)
}
entries, err := os.ReadDir(cacheRoot)
if err != nil {
return roots
}
var versions []string
for _, entry := range entries {
if !entry.IsDir() || strings.EqualFold(entry.Name(), "latest") {
continue
}
versions = append(versions, entry.Name())
}
sort.Slice(versions, func(i, j int) bool {
return compareVersions(versions[i], versions[j]) > 0
})
for _, version := range versions {
root := filepath.Join(cacheRoot, version)
if fileExists(filepath.Join(root, ".codex-plugin", "plugin.json")) {
roots = append(roots, root)
}
}
return roots
}
func materializeComputerUseMarketplacePlugin(home, marketplacePlugin string) (bool, error) {
if fileExists(filepath.Join(marketplacePlugin, ".codex-plugin", "plugin.json")) {
return false, nil
}
if root := bestComputerUseCachedPluginRoot(home); root != "" {
if err := replaceDirectory(marketplacePlugin, root); err != nil {
return false, fmt.Errorf("从插件缓存补全 Computer Use marketplace 插件失败 %s -> %s: %w", root, marketplacePlugin, err)
}
if fileExists(filepath.Join(marketplacePlugin, ".codex-plugin", "plugin.json")) {
return false, nil
}
}
if err := os.MkdirAll(marketplacePlugin, 0o755); err != nil {
return true, fmt.Errorf("创建 Computer Use 插件目录失败 %s: %w", marketplacePlugin, err)
}
if err := writeComputerUsePluginTree(marketplacePlugin); err != nil {
return true, fmt.Errorf("写入本地 fallback 插件失败 %s: %w", marketplacePlugin, err)
}
return true, nil
}
func ensureComputerUseCachedPlugin(home, marketplacePlugin string, usedLocalFallback bool) error {
if root := bestComputerUseCachedPluginRoot(home); root != "" && fileExists(computerUseHelperTransportPath(root)) {
return nil
}
version := computerUsePluginVersion
if !usedLocalFallback {
if pluginVersion := computerUsePluginVersionFromRoot(marketplacePlugin); pluginVersion != "" {
version = pluginVersion
}
}
cacheRoot := computerUseCacheRoot(home)
cacheVersion := filepath.Join(cacheRoot, version)
cacheLatest := computerUseCacheLatestRoot(home)
if err := os.MkdirAll(cacheRoot, 0o755); err != nil {
return fmt.Errorf("创建插件缓存目录失败 %s: %w", cacheRoot, err)
}
if err := replaceDirectory(cacheVersion, marketplacePlugin); err != nil {
return fmt.Errorf("写入插件缓存失败 %s: %w", cacheVersion, err)
}
if err := replaceDirectory(cacheLatest, cacheVersion); err != nil {
return fmt.Errorf("更新 latest 插件缓存失败 %s: %w", cacheLatest, err)
}
return nil
}
func computerUsePluginVersionFromRoot(root string) string {
var manifest struct {
Version string `json:"version"`
}
if err := readJSON(filepath.Join(root, ".codex-plugin", "plugin.json"), &manifest); err != nil {
return ""
}
version := strings.TrimSpace(manifest.Version)
if version == "" || version == "." || version == ".." || strings.ContainsAny(version, `/\:`) {
return ""
}
return version
}
func syncBundledMarketplaceFromInstalledCodex(marketplaceRoot string) error {
if runtime.GOOS != "windows" {
return nil
}
sourceRoot := installedBundledMarketplaceRoot()
if sourceRoot == "" || samePath(sourceRoot, marketplaceRoot) {
return nil
}
tempRoot := marketplaceRoot + ".sync-tmp-" + time.Now().Format("20060102150405")
if err := os.RemoveAll(tempRoot); err != nil {
return err
}
defer os.RemoveAll(tempRoot)
if err := copyDirectory(sourceRoot, tempRoot); err != nil {
return err
}
if err := makeTreeWritable(tempRoot); err != nil {
return err
}
if isDir(marketplaceRoot) {
_ = makeTreeWritable(marketplaceRoot)
}
if err := os.RemoveAll(marketplaceRoot); err != nil {
return err
}
return os.Rename(tempRoot, marketplaceRoot)
}
func installedBundledMarketplaceRoot() string {
if runtime.GOOS != "windows" {
return ""
}
var candidates []string
addCandidate := func(path string) {
path = strings.TrimSpace(path)
if path == "" {
return
}
for _, candidate := range []string{
filepath.Join(path, "resources", "plugins", computerUseMarketplace),
filepath.Join(path, "app", "resources", "plugins", computerUseMarketplace),
filepath.Join(filepath.Dir(path), "app", "resources", "plugins", computerUseMarketplace),
} {
if candidate != "" {
candidates = append(candidates, candidate)
}
}
}
settings := loadSettings()
addCandidate(resolveCodexApp(settings.CodexAppPath))
addCandidate(resolveCodexApp(""))
for _, root := range windowsInstalledCodexPackageRoots() {
addCandidate(root)
}
for _, candidate := range candidates {
if fileExists(filepath.Join(candidate, ".agents", "plugins", "marketplace.json")) {
return candidate
}
}
return ""
}
func windowsInstalledCodexPackageRoots() []string {
if runtime.GOOS != "windows" {
return nil
}
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`},
}
var roots []string
for _, command := range commands {
cmd := exec.Command(command[0], command[1:]...)
hideSubprocessWindow(cmd)
out, err := cmd.Output()
if err != nil {
continue
}
for _, line := range strings.Split(strings.TrimSpace(string(out)), "\n") {
line = strings.TrimSpace(line)
if line != "" {
roots = append(roots, line)
}
}
}
return roots
}
func makeTreeWritable(root string) error {
return filepath.WalkDir(root, func(path string, entry os.DirEntry, err error) error {
if err != nil {
return err
}
if entry.IsDir() {
return os.Chmod(path, 0o755)
}
return os.Chmod(path, 0o644)
})
}
func samePath(left, right string) bool {
left = filepath.Clean(left)
right = filepath.Clean(right)
if runtime.GOOS == "windows" {
return strings.EqualFold(left, right)
}
return left == right
}
func writeComputerUsePluginTree(root string) error {
files := map[string]string{
filepath.Join(root, ".codex-plugin", "plugin.json"): computerUsePluginJSON(),
filepath.Join(root, "skills", "computer-use", "SKILL.md"): computerUseSkillMarkdown(),
filepath.Join(root, "node_modules", "@oai", "sky", "package.json"): `{
"name": "@oai/sky",
"version": "` + computerUsePluginVersion + `",
"type": "module",
"private": true
}
`,
filepath.Join(root, "node_modules", "@oai", "sky", "bin", "windows", "codex-computer-use.exe"): "# Placeholder executable path for Codex Desktop Windows Computer Use resolution.\n# The local helper transport module implements the actual request handling.\n",
filepath.Join(root, "node_modules", "@oai", "sky", "dist", "project", "cua", "sky_js", "src", "targets", "windows", "internal", "helper_transport.js"): computerUseHelperTransportJS(),
}
for path, contents := range files {
if err := atomicWrite(path, []byte(contents)); err != nil {
return err
}
}
return nil
}
func computerUsePluginJSON() string {
return `{
"name": "computer-use",
"version": "` + computerUsePluginVersion + `",
"description": "Local Windows Computer Use compatibility helper for Codex Desktop.",
"author": {
"name": "Local"
},
"homepage": "https://openai.com/",
"repository": "https://openai.com/",
"license": "Proprietary",
"keywords": ["computer-use", "windows", "desktop"],
"skills": "./skills/",
"interface": {
"displayName": "Computer Use",
"shortDescription": "Control this Windows desktop from Codex",
"longDescription": "Local compatibility plugin that provides the Windows helper paths expected by Codex Desktop Computer Use.",
"developerName": "Local",
"category": "Productivity",
"capabilities": ["Interactive", "Read", "Write"],
"websiteURL": "https://openai.com/",
"privacyPolicyURL": "https://openai.com/policies/row-privacy-policy/",
"termsOfServiceURL": "https://openai.com/policies/row-terms-of-use/",
"defaultPrompt": ["Look at my screen and help me navigate"],
"brandColor": "#10A37F",
"screenshots": []
}
}
`
}
func computerUseSkillMarkdown() string {
return `---
name: computer-use
description: Local Windows Computer Use compatibility helper for Codex Desktop. Provides the @oai/sky paths that the Desktop app expects when CODEX_ELECTRON_ENABLE_WINDOWS_COMPUTER_USE=1.
---
# Computer Use
This local compatibility plugin is installed by CodexTools. It supplies the Windows helper transport paths that Codex Desktop resolves for Computer Use.
The Desktop app must be launched with ` + "`CODEX_ELECTRON_ENABLE_WINDOWS_COMPUTER_USE=1`" + `. CodexTools writes that as a user environment variable, so restart Codex after repair.
`
}
func updateComputerUseMarketplaceManifest(marketplaceRoot string, forceLocalEntry bool) error {
manifestPath := filepath.Join(marketplaceRoot, ".agents", "plugins", "marketplace.json")
var manifest map[string]any
if err := readJSON(manifestPath, &manifest); err != nil || manifest == nil {
manifest = map[string]any{
"name": computerUseMarketplace,
"interface": map[string]any{"displayName": "OpenAI Bundled"},
"plugins": []any{},
}
}
manifest["name"] = computerUseMarketplace
if _, ok := manifest["interface"].(map[string]any); !ok {
manifest["interface"] = map[string]any{"displayName": "OpenAI Bundled"}
}
if !forceLocalEntry && computerUseManifestHasEntry(manifest) {
return atomicWriteJSON(manifestPath, manifest)
}
entry := map[string]any{
"name": computerUsePluginName,
"source": map[string]any{
"source": "local",
"path": "./plugins/computer-use",
},
"policy": map[string]any{
"installation": "INSTALLED_BY_DEFAULT",
"authentication": "ON_INSTALL",
},
"category": "Productivity",
}
var plugins []any
if existing, ok := manifest["plugins"].([]any); ok {
for _, item := range existing {
itemMap, _ := item.(map[string]any)
if stringFromAny(itemMap["name"]) == computerUsePluginName {
continue
}
plugins = append(plugins, item)
}
}
manifest["plugins"] = append([]any{entry}, plugins...)
return atomicWriteJSON(manifestPath, manifest)
}
func computerUseManifestHasEntry(manifest map[string]any) bool {
if existing, ok := manifest["plugins"].([]any); ok {
for _, item := range existing {
itemMap, _ := item.(map[string]any)
if stringFromAny(itemMap["name"]) == computerUsePluginName {
return true
}
}
}
return false
}
func validateComputerUseReady(status computerUseStatus) error {
var missing []string
if !status.EnvEnabled {
missing = append(missing, "环境变量 CODEX_ELECTRON_ENABLE_WINDOWS_COMPUTER_USE")
}
if !status.MarketplaceManifest {
missing = append(missing, status.MarketplaceManifestPath)
}
if !status.MarketplacePlugin {
missing = append(missing, status.MarketplacePluginPath)
}
if !status.CacheLatest {
missing = append(missing, status.CacheLatestPath)
}
if !status.HelperTransport {
missing = append(missing, status.HelperTransportPath)
}
if !status.ConfigReady {
missing = append(missing, status.ConfigPath)
}
if len(missing) > 0 {
return fmt.Errorf("Computer Use 修复后仍缺少关键项目:%s", strings.Join(missing, ";"))
}
return nil
}
func updateComputerUseCodexConfig(home, marketplaceRoot string) (*string, error) {
configPath := filepath.Join(home, "config.toml")
contents := readFile(configPath)
updated := upsertTomlTable(contents, "marketplaces."+computerUseMarketplace, []string{
"last_updated = " + quoteToml(time.Now().UTC().Format(time.RFC3339)),
`source_type = "local"`,
"source = " + quoteToml(computerUseConfigSourcePath(marketplaceRoot)),
})
updated = upsertTomlTable(updated, fmt.Sprintf("plugins.%s", quoteToml(computerUsePluginName+"@"+computerUseMarketplace)), []string{
"enabled = true",
})
updated, _ = repairNodeReplMCPConfig(home, updated)
updated = upsertTomlTable(updated, "windows", []string{
`sandbox = "unelevated"`,
})
return writeCodexConfigWithBackup(configPath, updated, "computer-use")
}
func computerUseConfigSourcePath(path string) string {
if runtime.GOOS == "windows" {
if strings.HasPrefix(path, `\\?\`) {
return path
}
return `\\?\` + path
}
return path
}
func setComputerUseUserEnv() error {
_ = os.Setenv("CODEX_ELECTRON_ENABLE_WINDOWS_COMPUTER_USE", "1")
if runtime.GOOS != "windows" {
return nil
}
script := `[Environment]::SetEnvironmentVariable('CODEX_ELECTRON_ENABLE_WINDOWS_COMPUTER_USE','1','User'); $env:CODEX_ELECTRON_ENABLE_WINDOWS_COMPUTER_USE='1'; try { $signature = @'
using System;
using System.Runtime.InteropServices;
public static class CodexEnvBroadcast {
[DllImport("user32.dll", SetLastError=true, CharSet=CharSet.Auto)]
public static extern IntPtr SendMessageTimeout(IntPtr hWnd, uint Msg, UIntPtr wParam, string lParam, uint fuFlags, uint uTimeout, out UIntPtr lpdwResult);
}
'@; if (-not ('CodexEnvBroadcast' -as [type])) { Add-Type -TypeDefinition $signature }; $result = [UIntPtr]::Zero; [CodexEnvBroadcast]::SendMessageTimeout([IntPtr]0xffff, 0x001A, [UIntPtr]::Zero, 'Environment', 0x0002, 5000, [ref]$result) | Out-Null } catch { }`
cmd := exec.Command("powershell", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-Command", script)
hideSubprocessWindow(cmd)
return cmd.Run()
}
func computerUseUserEnv() string {
if runtime.GOOS != "windows" {
return ""
}
return windowsRegistryString(`HKEY_CURRENT_USER\Environment`, "CODEX_ELECTRON_ENABLE_WINDOWS_COMPUTER_USE")
}
func computerUseHelperTransportJS() string {
return "import { execFile } from \"node:child_process\";\n" +
"import { appendFile, mkdir } from \"node:fs/promises\";\n" +
"import { dirname, join } from \"node:path\";\n" +
"import { promisify } from \"node:util\";\n\n" +
"const execFileAsync = promisify(execFile);\n" +
"const logPath = join(process.env.LOCALAPPDATA || process.env.TEMP || \".\", \"OpenAI\", \"Codex\", \"computer-use-local-helper.log\");\n\n" +
"async function log(entry) {\n" +
" try {\n" +
" await mkdir(dirname(logPath), { recursive: true });\n" +
" await appendFile(logPath, new Date().toISOString() + \" \" + JSON.stringify(entry) + \"\\n\", \"utf8\");\n" +
" } catch {\n" +
" }\n" +
"}\n\n" +
"function encodePowerShell(script) {\n" +
" return Buffer.from(script, \"utf16le\").toString(\"base64\");\n" +
"}\n\n" +
"async function runPowerShell(script, timeout = 30000) {\n" +
" const { stdout } = await execFileAsync(\"powershell.exe\", [\"-NoProfile\", \"-NonInteractive\", \"-ExecutionPolicy\", \"Bypass\", \"-EncodedCommand\", encodePowerShell(script)], {\n" +
" encoding: \"utf8\",\n" +
" env: process.env,\n" +
" timeout,\n" +
" windowsHide: true,\n" +
" maxBuffer: 64 * 1024 * 1024,\n" +
" });\n" +
" const text = stdout.trim();\n" +
" return text.length === 0 ? null : JSON.parse(text);\n" +
"}\n\n" +
"function ps(strings) {\n" +
" return strings.join(\"\\n\");\n" +
"}\n\n" +
"function numberFrom(params, names, fallback = 0) {\n" +
" for (const name of names) {\n" +
" const value = params?.[name];\n" +
" if (typeof value === \"number\" && Number.isFinite(value)) return value;\n" +
" if (typeof value === \"string\" && value.trim() !== \"\" && Number.isFinite(Number(value))) return Number(value);\n" +
" }\n" +
" return fallback;\n" +
"}\n\n" +
"function buttonFrom(params) {\n" +
" const raw = String(params?.button || params?.mouseButton || \"left\").toLowerCase();\n" +
" if (raw.includes(\"right\")) return \"right\";\n" +
" if (raw.includes(\"middle\")) return \"middle\";\n" +
" return \"left\";\n" +
"}\n\n" +
"function keyFrom(params) {\n" +
" return String(params?.key || params?.keys || params?.text || params?.value || \"\");\n" +
"}\n\n" +
"function textFrom(params) {\n" +
" return String(params?.text ?? params?.value ?? params?.input ?? \"\");\n" +
"}\n\n" +
"const user32Script = ps([\n" +
" \"Add-Type -TypeDefinition @\\\"\",\n" +
" \"using System;\",\n" +
" \"using System.Runtime.InteropServices;\",\n" +
" \"public static class CodexUser32 {\",\n" +
" \" [DllImport(\\\"user32.dll\\\")] public static extern bool SetCursorPos(int X, int Y);\",\n" +
" \" [DllImport(\\\"user32.dll\\\")] public static extern void mouse_event(uint dwFlags, uint dx, uint dy, int dwData, UIntPtr dwExtraInfo);\",\n" +
" \"}\",\n" +
" \"\\\"@\",\n" +
"]);\n\n" +
"function mouseFlags(button, action) {\n" +
" if (button === \"right\") return action === \"down\" ? \"0x0008\" : \"0x0010\";\n" +
" if (button === \"middle\") return action === \"down\" ? \"0x0020\" : \"0x0040\";\n" +
" return action === \"down\" ? \"0x0002\" : \"0x0004\";\n" +
"}\n\n" +
"async function screenshot() {\n" +
" return await runPowerShell(ps([\n" +
" \"Add-Type -AssemblyName System.Windows.Forms\",\n" +
" \"Add-Type -AssemblyName System.Drawing\",\n" +
" \"$bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen\",\n" +
" \"$bitmap = New-Object System.Drawing.Bitmap $bounds.Width, $bounds.Height\",\n" +
" \"$graphics = [System.Drawing.Graphics]::FromImage($bitmap)\",\n" +
" \"$graphics.CopyFromScreen($bounds.Left, $bounds.Top, 0, 0, $bounds.Size)\",\n" +
" \"$stream = New-Object System.IO.MemoryStream\",\n" +
" \"$bitmap.Save($stream, [System.Drawing.Imaging.ImageFormat]::Png)\",\n" +
" \"$graphics.Dispose()\",\n" +
" \"$bitmap.Dispose()\",\n" +
" \"$bytes = $stream.ToArray()\",\n" +
" \"$stream.Dispose()\",\n" +
" \"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\",\n" +
" \"[Console]::Write((ConvertTo-Json -Compress @{ mimeType = 'image/png'; data = [Convert]::ToBase64String($bytes); width = $bounds.Width; height = $bounds.Height; left = $bounds.Left; top = $bounds.Top }))\",\n" +
" ]), 30000);\n" +
"}\n\n" +
"async function screenInfo() {\n" +
" return await runPowerShell(ps([\n" +
" \"Add-Type -AssemblyName System.Windows.Forms\",\n" +
" \"$bounds = [System.Windows.Forms.SystemInformation]::VirtualScreen\",\n" +
" \"[Console]::OutputEncoding = [System.Text.Encoding]::UTF8\",\n" +
" \"[Console]::Write((ConvertTo-Json -Compress @{ width = $bounds.Width; height = $bounds.Height; left = $bounds.Left; top = $bounds.Top }))\",\n" +
" ]));\n" +
"}\n\n" +
"async function moveMouse(params) {\n" +
" const x = Math.round(numberFrom(params, [\"x\", \"X\", \"left\"]));\n" +
" const y = Math.round(numberFrom(params, [\"y\", \"Y\", \"top\"]));\n" +
" return await runPowerShell(ps([user32Script, \"[CodexUser32]::SetCursorPos(\" + x + \", \" + y + \") | Out-Null\", \"[Console]::Write('{\\\"ok\\\":true}')\"]));\n" +
"}\n\n" +
"async function clickMouse(params, count = 1) {\n" +
" const x = Math.round(numberFrom(params, [\"x\", \"X\", \"left\"], Number.NaN));\n" +
" const y = Math.round(numberFrom(params, [\"y\", \"Y\", \"top\"], Number.NaN));\n" +
" const button = buttonFrom(params);\n" +
" const down = mouseFlags(button, \"down\");\n" +
" const up = mouseFlags(button, \"up\");\n" +
" const lines = [user32Script];\n" +
" if (Number.isFinite(x) && Number.isFinite(y)) lines.push(\"[CodexUser32]::SetCursorPos(\" + x + \", \" + y + \") | Out-Null\");\n" +
" lines.push(\"for ($i = 0; $i -lt \" + count + \"; $i++) {\", \" [CodexUser32]::mouse_event(\" + down + \", 0, 0, 0, [UIntPtr]::Zero)\", \" Start-Sleep -Milliseconds 35\", \" [CodexUser32]::mouse_event(\" + up + \", 0, 0, 0, [UIntPtr]::Zero)\", \" Start-Sleep -Milliseconds 70\", \"}\", \"[Console]::Write('{\\\"ok\\\":true}')\");\n" +
" return await runPowerShell(ps(lines));\n" +
"}\n\n" +
"async function dragMouse(params) {\n" +
" const fromX = Math.round(numberFrom(params, [\"fromX\", \"startX\", \"x1\", \"x\"]));\n" +
" const fromY = Math.round(numberFrom(params, [\"fromY\", \"startY\", \"y1\", \"y\"]));\n" +
" const toX = Math.round(numberFrom(params, [\"toX\", \"endX\", \"x2\"]));\n" +
" const toY = Math.round(numberFrom(params, [\"toY\", \"endY\", \"y2\"]));\n" +
" return await runPowerShell(ps([user32Script, \"[CodexUser32]::SetCursorPos(\" + fromX + \", \" + fromY + \") | Out-Null\", \"Start-Sleep -Milliseconds 80\", \"[CodexUser32]::mouse_event(0x0002, 0, 0, 0, [UIntPtr]::Zero)\", \"Start-Sleep -Milliseconds 120\", \"[CodexUser32]::SetCursorPos(\" + toX + \", \" + toY + \") | Out-Null\", \"Start-Sleep -Milliseconds 120\", \"[CodexUser32]::mouse_event(0x0004, 0, 0, 0, [UIntPtr]::Zero)\", \"[Console]::Write('{\\\"ok\\\":true}')\"]));\n" +
"}\n\n" +
"async function scrollMouse(params) {\n" +
" const delta = Math.round(numberFrom(params, [\"delta\", \"wheelDelta\"], 0) || -120 * numberFrom(params, [\"amount\", \"clicks\"], 1));\n" +
" return await runPowerShell(ps([user32Script, \"[CodexUser32]::mouse_event(0x0800, 0, 0, \" + delta + \", [UIntPtr]::Zero)\", \"[Console]::Write('{\\\"ok\\\":true}')\"]));\n" +
"}\n\n" +
"function sendKeysLiteral(text) {\n" +
" return text.replaceAll(\"{\", \"{{}\").replaceAll(\"}\", \"{}}\").replaceAll(\"+\", \"{+}\").replaceAll(\"^\", \"{^}\").replaceAll(\"%\", \"{%}\").replaceAll(\"~\", \"{~}\").replaceAll(\"(\", \"{(}\").replaceAll(\")\", \"{)}\").replaceAll(\"[\", \"{[}\").replaceAll(\"]\", \"{]}\").replaceAll(\"\\n\", \"{ENTER}\");\n" +
"}\n\n" +
"function normalizeKey(key) {\n" +
" const value = String(key).trim();\n" +
" const upper = value.toUpperCase();\n" +
" const aliases = { ENTER: \"{ENTER}\", RETURN: \"{ENTER}\", ESC: \"{ESC}\", ESCAPE: \"{ESC}\", TAB: \"{TAB}\", BACKSPACE: \"{BACKSPACE}\", DELETE: \"{DELETE}\", DEL: \"{DELETE}\", SPACE: \" \", UP: \"{UP}\", DOWN: \"{DOWN}\", LEFT: \"{LEFT}\", RIGHT: \"{RIGHT}\", HOME: \"{HOME}\", END: \"{END}\", PAGEUP: \"{PGUP}\", PAGEDOWN: \"{PGDN}\" };\n" +
" if (aliases[upper]) return aliases[upper];\n" +
" if (/^F([1-9]|1[0-2])$/.test(upper)) return \"{\" + upper + \"}\";\n" +
" return sendKeysLiteral(value);\n" +
"}\n\n" +
"async function sendKeys(keys) {\n" +
" const encoded = Buffer.from(keys, \"utf8\").toString(\"base64\");\n" +
" return await runPowerShell(ps([\"Add-Type -AssemblyName System.Windows.Forms\", \"$keys = [System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('\" + encoded + \"'))\", \"[System.Windows.Forms.SendKeys]::SendWait($keys)\", \"[Console]::Write('{\\\"ok\\\":true}')\"]));\n" +
"}\n\n" +
"async function typeText(params) {\n" +
" return await sendKeys(sendKeysLiteral(textFrom(params)));\n" +
"}\n\n" +
"async function keypress(params) {\n" +
" return await sendKeys(normalizeKey(keyFrom(params)));\n" +
"}\n\n" +
"export class WindowsHelperTransport {\n" +
" constructor({ helperArgs = [], helperCommand = null } = {}) {\n" +
" this.helperArgs = helperArgs;\n" +
" this.helperCommand = helperCommand;\n" +
" log({ event: \"transport-created\", helperCommand, helperArgs }).catch(() => {});\n" +
" }\n\n" +
" async request(method, params = {}, options = {}) {\n" +
" await log({ event: \"request\", method, params, hasTurnMetadata: !!options?.codexTurnMetadata });\n" +
" const name = String(method || \"\").replace(/[-_]/g, \"\").toLowerCase();\n" +
" if (name === \"ping\") return \"pong\";\n" +
" if ([\"screenshot\", \"takescreenshot\", \"capture\", \"captureimage\", \"capturescreen\", \"screencapture\"].includes(name)) return await screenshot(params);\n" +
" if ([\"screeninfo\", \"getscreeninfo\", \"displays\", \"getdisplays\", \"screenstate\"].includes(name)) return await screenInfo(params);\n" +
" if ([\"movemouse\", \"mousemove\", \"move\"].includes(name)) return await moveMouse(params);\n" +
" if ([\"click\", \"mouseclick\", \"clickmouse\"].includes(name)) return await clickMouse(params, 1);\n" +
" if ([\"doubleclick\", \"mousedoubleclick\"].includes(name)) return await clickMouse(params, 2);\n" +
" if ([\"drag\", \"mousedrag\", \"dragmouse\"].includes(name)) return await dragMouse(params);\n" +
" if ([\"scroll\", \"mousescroll\", \"scrollmouse\"].includes(name)) return await scrollMouse(params);\n" +
" if ([\"type\", \"typetext\", \"text\"].includes(name)) return await typeText(params);\n" +
" if ([\"keypress\", \"presskey\", \"key\", \"sendkey\"].includes(name)) return await keypress(params);\n" +
" if ([\"close\", \"shutdown\"].includes(name)) return { ok: true };\n" +
" await log({ event: \"unknown-method\", method, params });\n" +
" throw new Error(\"Unsupported local Computer Use helper method: \" + method);\n" +
" }\n\n" +
" async close() {\n" +
" await log({ event: \"transport-closed\" });\n" +
" }\n" +
"}\n"
}