Skip to content

👾 Open Computer Use – Open-Source Alternative to Codex Computer Use

Add experimental Windows computer-use runtime

Leo164a1c89f4e7
diff --git a/README.md b/README.md
index 90240cb..c7df4d0 100644
--- a/README.md
+++ b/README.md
@@ -4,7 +4,7 @@
[![Open Computer Use custom demo cover](./docs/generated/readme-assets/open-computer-use-demo-cover.png)](https://youtu.be/2s6aVpGiwaQ)
-`open-computer-use` is an open-source `Computer Use` service exposed over `MCP`, so any AI agent or MCP client can call it directly and use computer interaction capabilities on macOS.
+`open-computer-use` is an open-source `Computer Use` service exposed over `MCP`, so any AI agent or MCP client can call it directly and use computer interaction capabilities on macOS. An experimental Windows runtime now lives in this repo too, with the same 9-tool surface implemented as a standalone Go-built `.exe`.
This project was inspired by OpenAI's recently released [Codex Computer Use](https://openai.com/index/codex-for-almost-everything/). It showed that non-intrusive CUA can be built on top of macOS Accessibility, which is why I decided to build an open-source version.
@@ -12,7 +12,7 @@ I bootstrapped this repo with my earlier [harness template](https://github.com/i
## Quick Start
-Install it globally first:
+The npm package currently ships the macOS app bundle. Install it globally first:
```bash
npm i -g open-computer-use
@@ -63,6 +63,24 @@ open-computer-use doctor
open-computer-use -h
```
+## Windows Runtime
+
+The Windows runtime is intentionally separate from the macOS Swift `.app`. It is built from `apps/OpenComputerUseWindows` and uses Windows UI Automation first, then Win32 window messages for fallback input.
+
+```bash
+# Build a Windows arm64 executable from this repo
+./scripts/build-open-computer-use-windows.sh --arch arm64
+
+# On Windows, run it directly
+open-computer-use.exe mcp
+open-computer-use.exe call list_apps
+open-computer-use.exe call --calls "[{\"tool\":\"get_app_state\",\"args\":{\"app\":\"notepad\"}},{\"tool\":\"type_text\",\"args\":{\"app\":\"notepad\",\"text\":\"hello\"}}]"
+```
+
+Run the `.exe` in the signed-in desktop session. Running it as a Windows service or a detached SSH-only process may not expose top-level UI Automation windows.
+
+By default, the Windows runtime only attaches to already running apps, does not call `SetFocus`, and avoids the UIA `ValuePattern.SetValue` fallback for `type_text` because some apps bring themselves forward from that path. If you explicitly want the old foreground behavior, set `OPEN_COMPUTER_USE_WINDOWS_ALLOW_APP_LAUNCH=1` to allow app launch fallback, `OPEN_COMPUTER_USE_WINDOWS_ALLOW_FOCUS_ACTIONS=1` to allow the `SetFocus` secondary action, and `OPEN_COMPUTER_USE_WINDOWS_ALLOW_UIA_TEXT_FALLBACK=1` to allow UIA text fallback.
+
## Cursor Motion
Cursor Motion is an open-source cursor motion system for macOS, based on public information shared by members of the Software.Inc team. You can run it from source or download the app from the [Releases page](https://github.com/iFurySt/open-codex-computer-use/releases).
diff --git a/README.zh-CN.md b/README.zh-CN.md
index 0c05cfd..c149571 100644
--- a/README.zh-CN.md
+++ b/README.zh-CN.md
@@ -4,7 +4,7 @@
[![open-computer-use 自定义演示封面](./docs/generated/readme-assets/open-computer-use-demo-cover.png)](https://youtu.be/2s6aVpGiwaQ)
-`open-computer-use` 是一个开源的 `Computer Use` 服务,已经包装成 `MCP` 协议,支持所有的 AI Agent 或 MCP Client 快速调用,实现 macOS 上的 `Computer Use` 能力
+`open-computer-use` 是一个开源的 `Computer Use` 服务,已经包装成 `MCP` 协议,支持所有的 AI Agent 或 MCP Client 快速调用,实现 macOS 上的 `Computer Use` 能力。仓库里也已经新增实验性的 Windows runtime,用 Go 生成独立 `.exe`,暴露同样的 9 个 tool。
项目的背后是 OpenAI 刚发布的 [Codex Computer Use](https://openai.com/index/codex-for-almost-everything/),让我看到了基于 Accessibility 可以实现非抢占式 CUA 能力,因此决定复刻一个开源版本
@@ -12,7 +12,7 @@
## Quick Start
-先全局安装:
+当前 npm 包发布的是 macOS app bundle,先全局安装:
```bash
npm i -g open-computer-use
@@ -70,6 +70,24 @@ open-computer-use doctor
open-computer-use -h
```
+## Windows Runtime
+
+Windows 侧不复用 Swift `.app`,而是放在 `apps/OpenComputerUseWindows` 里独立构建;执行时优先走 Windows UI Automation,必要时用 Win32 window message 做 fallback。
+
+```bash
+# 从仓库里构建 Windows arm64 exe
+./scripts/build-open-computer-use-windows.sh --arch arm64
+
+# 在 Windows 里直接运行
+open-computer-use.exe mcp
+open-computer-use.exe call list_apps
+open-computer-use.exe call --calls "[{\"tool\":\"get_app_state\",\"args\":{\"app\":\"notepad\"}},{\"tool\":\"type_text\",\"args\":{\"app\":\"notepad\",\"text\":\"hello\"}}]"
+```
+
+这个 `.exe` 需要跑在已登录的桌面 session 里。作为 Windows service 或纯 SSH 脱离桌面运行时,系统可能不给它暴露顶层 UI Automation 窗口。
+
+默认情况下,Windows runtime 只连接已经运行的 app,不会自动启动目标 app,也不会执行 `SetFocus`;`type_text` 也会避开 UIA `ValuePattern.SetValue` fallback,因为有些 app 会在这条路径里主动把自己带到前台。如果确实需要旧的前台行为,可以设置 `OPEN_COMPUTER_USE_WINDOWS_ALLOW_APP_LAUNCH=1` 允许启动 fallback,设置 `OPEN_COMPUTER_USE_WINDOWS_ALLOW_FOCUS_ACTIONS=1` 允许 `SetFocus` secondary action,设置 `OPEN_COMPUTER_USE_WINDOWS_ALLOW_UIA_TEXT_FALLBACK=1` 允许 UIA text fallback。
+
## Cursor Motion
Cursor Motion 是一个面向 macOS 的开源光标运动系统,基于 Software.Inc 几位大佬的公开信息实现的开源版本,可以代码里运行,也可以到 [Releases 页面](https://github.com/iFurySt/open-codex-computer-use/releases) 下载 app 运行。
diff --git a/apps/OpenComputerUseWindows/go.mod b/apps/OpenComputerUseWindows/go.mod
new file mode 100644
index 0000000..bdb1994
--- /dev/null
+++ b/apps/OpenComputerUseWindows/go.mod
@@ -0,0 +1,3 @@
+module github.com/iFurySt/open-codex-computer-use/apps/opencomputerusewindows
+
+go 1.22
diff --git a/apps/OpenComputerUseWindows/main.go b/apps/OpenComputerUseWindows/main.go
new file mode 100644
index 0000000..ec70522
--- /dev/null
+++ b/apps/OpenComputerUseWindows/main.go
@@ -0,0 +1,978 @@
+package main
+
+import (
+ "context"
+ _ "embed"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "runtime"
+ "strconv"
+ "strings"
+ "time"
+)
+
+var version = "0.1.28"
+
+//go:embed runtime.ps1
+var windowsRuntimeScript string
+
+const serverInstructions = "Computer Use tools let you interact with Windows apps by performing UI actions.\n\nBegin by calling `get_app_state` every turn you want to use Computer Use to get the latest state before acting. The available tools are list_apps, get_app_state, click, perform_secondary_action, scroll, drag, type_text, press_key, and set_value.\n\nPrefer element-targeted interactions over coordinate clicks when an index for the targeted element is available. Windows actions use UI Automation patterns first and fall back to window messages when an app does not expose the needed pattern. The Windows runtime does not auto-launch apps, perform SetFocus, or use UIA text fallback by default, so background-capable actions do not intentionally steal the user's foreground focus."
+
+type toolDefinition struct {
+ Name string `json:"name"`
+ Description string `json:"description"`
+ Annotations map[string]any `json:"annotations,omitempty"`
+ InputSchema map[string]any `json:"inputSchema"`
+}
+
+type contentItem struct {
+ Type string `json:"type"`
+ Text string `json:"text,omitempty"`
+ Data string `json:"data,omitempty"`
+ MimeType string `json:"mimeType,omitempty"`
+}
+
+type toolCallResult struct {
+ Content []contentItem `json:"content"`
+ IsError bool `json:"isError"`
+}
+
+func textResult(text string, isError bool) toolCallResult {
+ return toolCallResult{Content: []contentItem{{Type: "text", Text: text}}, IsError: isError}
+}
+
+type appDescriptor struct {
+ Name string `json:"name"`
+ BundleIdentifier string `json:"bundleIdentifier,omitempty"`
+ PID int `json:"pid"`
+}
+
+type frame struct {
+ X float64 `json:"x"`
+ Y float64 `json:"y"`
+ Width float64 `json:"width"`
+ Height float64 `json:"height"`
+}
+
+func (f frame) renderedLocalFrame() string {
+ return fmt.Sprintf("{{x: %.0f, y: %.0f, width: %.0f, height: %.0f}}", f.X, f.Y, f.Width, f.Height)
+}
+
+type elementRecord struct {
+ Index int `json:"index"`
+ RuntimeID []int `json:"runtimeId,omitempty"`
+ AutomationID string `json:"automationId,omitempty"`
+ Name string `json:"name,omitempty"`
+ ControlType string `json:"controlType,omitempty"`
+ LocalizedControlType string `json:"localizedControlType,omitempty"`
+ ClassName string `json:"className,omitempty"`
+ Value string `json:"value,omitempty"`
+ NativeWindowHandle int64 `json:"nativeWindowHandle,omitempty"`
+ Frame *frame `json:"frame,omitempty"`
+ Actions []string `json:"actions,omitempty"`
+}
+
+type appSnapshot struct {
+ App appDescriptor `json:"app"`
+ WindowTitle string `json:"windowTitle,omitempty"`
+ WindowBounds *frame `json:"windowBounds,omitempty"`
+ ScreenshotPNGBase64 string `json:"screenshotPngBase64,omitempty"`
+ TreeLines []string `json:"treeLines,omitempty"`
+ FocusedSummary string `json:"focusedSummary,omitempty"`
+ SelectedText string `json:"selectedText,omitempty"`
+ Elements []elementRecord `json:"elements,omitempty"`
+}
+
+func (s *appSnapshot) renderedText() string {
+ if s == nil {
+ return ""
+ }
+ appRef := s.App.BundleIdentifier
+ if appRef == "" {
+ appRef = s.App.Name
+ }
+ title := s.WindowTitle
+ if strings.TrimSpace(title) == "" {
+ title = s.App.Name
+ }
+
+ lines := []string{
+ fmt.Sprintf("App=%s (pid %d)", appRef, s.App.PID),
+ fmt.Sprintf("Window: %q, App: %s.", title, s.App.Name),
+ }
+ lines = append(lines, s.TreeLines...)
+ if strings.TrimSpace(s.SelectedText) != "" {
+ lines = append(lines, "", fmt.Sprintf("Selected text: [%s]", s.SelectedText))
+ } else if strings.TrimSpace(s.FocusedSummary) != "" {
+ lines = append(lines, "", fmt.Sprintf("The focused UI element is %s.", s.FocusedSummary))
+ }
+ return strings.Join(lines, "\n")
+}
+
+func (s *appSnapshot) result() toolCallResult {
+ result := toolCallResult{
+ Content: []contentItem{{Type: "text", Text: s.renderedText()}},
+ }
+ if s != nil && s.ScreenshotPNGBase64 != "" {
+ result.Content = append(result.Content, contentItem{
+ Type: "image",
+ Data: s.ScreenshotPNGBase64,
+ MimeType: "image/png",
+ })
+ }
+ return result
+}
+
+type psRequest struct {
+ Tool string `json:"tool"`
+ App string `json:"app,omitempty"`
+ Element *elementRecord `json:"element,omitempty"`
+ X *float64 `json:"x,omitempty"`
+ Y *float64 `json:"y,omitempty"`
+ FromX *float64 `json:"from_x,omitempty"`
+ FromY *float64 `json:"from_y,omitempty"`
+ ToX *float64 `json:"to_x,omitempty"`
+ ToY *float64 `json:"to_y,omitempty"`
+ ClickCount int `json:"click_count,omitempty"`
+ MouseButton string `json:"mouse_button,omitempty"`
+ Action string `json:"action,omitempty"`
+ Direction string `json:"direction,omitempty"`
+ Pages float64 `json:"pages,omitempty"`
+ Text string `json:"text,omitempty"`
+ Key string `json:"key,omitempty"`
+ Value string `json:"value,omitempty"`
+ WindowBounds *frame `json:"windowBounds,omitempty"`
+}
+
+type psResponse struct {
+ OK bool `json:"ok"`
+ Text string `json:"text,omitempty"`
+ Error string `json:"error,omitempty"`
+ Snapshot *appSnapshot `json:"snapshot,omitempty"`
+}
+
+type service struct {
+ snapshots map[string]*appSnapshot
+}
+
+func newService() *service {
+ return &service{snapshots: map[string]*appSnapshot{}}
+}
+
+func (s *service) callTool(name string, args map[string]any) toolCallResult {
+ switch name {
+ case "list_apps":
+ return s.listApps()
+ case "get_app_state":
+ return s.getAppState(requiredString(args, "app"))
+ case "click":
+ return s.click(
+ requiredString(args, "app"),
+ optionalString(args, "element_index"),
+ optionalFloat(args, "x"),
+ optionalFloat(args, "y"),
+ intValue(optionalFloat(args, "click_count"), 1),
+ defaultString(optionalString(args, "mouse_button"), "left"),
+ )
+ case "perform_secondary_action":
+ return s.performSecondaryAction(
+ requiredString(args, "app"),
+ requiredString(args, "element_index"),
+ requiredString(args, "action"),
+ )
+ case "scroll":
+ return s.scroll(
+ requiredString(args, "app"),
+ requiredString(args, "direction"),
+ requiredString(args, "element_index"),
+ floatValue(optionalFloat(args, "pages"), 1),
+ )
+ case "drag":
+ return s.drag(
+ requiredString(args, "app"),
+ requiredFloat(args, "from_x"),
+ requiredFloat(args, "from_y"),
+ requiredFloat(args, "to_x"),
+ requiredFloat(args, "to_y"),
+ )
+ case "type_text":
+ return s.typeText(requiredString(args, "app"), requiredString(args, "text"))
+ case "press_key":
+ return s.pressKey(requiredString(args, "app"), requiredString(args, "key"))
+ case "set_value":
+ return s.setValue(requiredString(args, "app"), requiredString(args, "element_index"), requiredString(args, "value"))
+ default:
+ return textResult(fmt.Sprintf("unsupportedTool(%q)", name), true)
+ }
+}
+
+func (s *service) listApps() toolCallResult {
+ response, err := runPowerShell(psRequest{Tool: "list_apps"})
+ if err != nil {
+ return textResult(err.Error(), true)
+ }
+ if !response.OK {
+ return textResult(response.Error, true)
+ }
+ if strings.TrimSpace(response.Text) == "" {
+ response.Text = "No running top-level apps are visible to this Windows runtime."
+ }
+ return textResult(response.Text, false)
+}
+
+func (s *service) getAppState(app string) toolCallResult {
+ if app == "" {
+ return textResult("Missing required argument: app", true)
+ }
+ snapshot, result := s.refreshSnapshot(app, psRequest{Tool: "get_app_state", App: app})
+ if result.IsError {
+ return result
+ }
+ return snapshot.result()
+}
+
+func (s *service) click(app, elementIndex string, x, y *float64, clickCount int, mouseButton string) toolCallResult {
+ if app == "" {
+ return textResult("Missing required argument: app", true)
+ }
+ if elementIndex == "" && (x == nil || y == nil) {
+ return textResult("click requires either element_index or x/y", true)
+ }
+ snapshot := s.currentSnapshot(app)
+ if snapshot == nil {
+ return textResult("No app state is available for "+app+". Run get_app_state before action tools.", true)
+ }
+ request := psRequest{
+ Tool: "click",
+ App: app,
+ X: x,
+ Y: y,
+ ClickCount: clickCount,
+ MouseButton: mouseButton,
+ WindowBounds: snapshot.WindowBounds,
+ }
+ if elementIndex != "" {
+ record, err := lookupElement(snapshot, elementIndex)
+ if err != nil {
+ return textResult(err.Error(), true)
+ }
+ request.Element = record
+ }
+ return s.actionResult(app, request)
+}
+
+func (s *service) performSecondaryAction(app, elementIndex, action string) toolCallResult {
+ if app == "" {
+ return textResult("Missing required argument: app", true)
+ }
+ if elementIndex == "" {
+ return textResult("Missing required argument: element_index", true)
+ }
+ if action == "" {
+ return textResult("Missing required argument: action", true)
+ }
+ snapshot := s.currentSnapshot(app)
+ if snapshot == nil {
+ return textResult("No app state is available for "+app+". Run get_app_state before action tools.", true)
+ }
+ record, err := lookupElement(snapshot, elementIndex)
+ if err != nil {
+ return textResult(err.Error(), true)
+ }
+ return s.actionResult(app, psRequest{Tool: "perform_secondary_action", App: app, Element: record, Action: action})
+}
+
+func (s *service) scroll(app, direction, elementIndex string, pages float64) toolCallResult {
+ if app == "" {
+ return textResult("Missing required argument: app", true)
+ }
+ if elementIndex == "" {
+ return textResult("Missing required argument: element_index", true)
+ }
+ normalized := strings.ToLower(direction)
+ if normalized != "up" && normalized != "down" && normalized != "left" && normalized != "right" {
+ return textResult("Invalid scroll direction: "+direction, true)
+ }
+ if pages <= 0 {
+ return textResult("pages must be > 0", true)
+ }
+ snapshot := s.currentSnapshot(app)
+ if snapshot == nil {
+ return textResult("No app state is available for "+app+". Run get_app_state before action tools.", true)
+ }
+ record, err := lookupElement(snapshot, elementIndex)
+ if err != nil {
+ return textResult(err.Error(), true)
+ }
+ return s.actionResult(app, psRequest{Tool: "scroll", App: app, Element: record, Direction: normalized, Pages: pages})
+}
+
+func (s *service) drag(app string, fromX, fromY, toX, toY *float64) toolCallResult {
+ if app == "" {
+ return textResult("Missing required argument: app", true)
+ }
+ if fromX == nil {
+ return textResult("Missing required argument: from_x", true)
+ }
+ if fromY == nil {
+ return textResult("Missing required argument: from_y", true)
+ }
+ if toX == nil {
+ return textResult("Missing required argument: to_x", true)
+ }
+ if toY == nil {
+ return textResult("Missing required argument: to_y", true)
+ }
+ snapshot := s.currentSnapshot(app)
+ if snapshot == nil {
+ return textResult("No app state is available for "+app+". Run get_app_state before action tools.", true)
+ }
+ return s.actionResult(app, psRequest{Tool: "drag", App: app, FromX: fromX, FromY: fromY, ToX: toX, ToY: toY, WindowBounds: snapshot.WindowBounds})
+}
+
+func (s *service) typeText(app, text string) toolCallResult {
+ if app == "" {
+ return textResult("Missing required argument: app", true)
+ }
+ if text == "" {
+ return textResult("Missing required argument: text", true)
+ }
+ if s.currentSnapshot(app) == nil {
+ return textResult("No app state is available for "+app+". Run get_app_state before action tools.", true)
+ }
+ return s.actionResult(app, psRequest{Tool: "type_text", App: app, Text: text})
+}
+
+func (s *service) pressKey(app, key string) toolCallResult {
+ if app == "" {
+ return textResult("Missing required argument: app", true)
+ }
+ if key == "" {
+ return textResult("Missing required argument: key", true)
+ }
+ if s.currentSnapshot(app) == nil {
+ return textResult("No app state is available for "+app+". Run get_app_state before action tools.", true)
+ }
+ return s.actionResult(app, psRequest{Tool: "press_key", App: app, Key: key})
+}
+
+func (s *service) setValue(app, elementIndex, value string) toolCallResult {
+ if app == "" {
+ return textResult("Missing required argument: app", true)
+ }
+ if elementIndex == "" {
+ return textResult("Missing required argument: element_index", true)
+ }
+ snapshot := s.currentSnapshot(app)
+ if snapshot == nil {
+ return textResult("No app state is available for "+app+". Run get_app_state before action tools.", true)
+ }
+ record, err := lookupElement(snapshot, elementIndex)
+ if err != nil {
+ return textResult(err.Error(), true)
+ }
+ return s.actionResult(app, psRequest{Tool: "set_value", App: app, Element: record, Value: value})
+}
+
+func (s *service) actionResult(app string, request psRequest) toolCallResult {
+ snapshot, result := s.refreshSnapshot(app, request)
+ if result.IsError {
+ return result
+ }
+ return snapshot.result()
+}
+
+func (s *service) currentSnapshot(app string) *appSnapshot {
+ return s.snapshots[strings.ToLower(app)]
+}
+
+func (s *service) refreshSnapshot(app string, request psRequest) (*appSnapshot, toolCallResult) {
+ response, err := runPowerShell(request)
+ if err != nil {
+ return nil, textResult(err.Error(), true)
+ }
+ if !response.OK {
+ return nil, textResult(response.Error, true)
+ }
+ if response.Snapshot == nil {
+ return nil, textResult("Windows runtime did not return an app snapshot.", true)
+ }
+ s.rememberSnapshot(app, response.Snapshot)
+ return response.Snapshot, toolCallResult{}
+}
+
+func (s *service) rememberSnapshot(query string, snapshot *appSnapshot) {
+ keys := []string{query, snapshot.App.Name, snapshot.App.BundleIdentifier, strconv.Itoa(snapshot.App.PID)}
+ for _, key := range keys {
+ key = strings.ToLower(strings.TrimSpace(key))
+ if key != "" {
+ s.snapshots[key] = snapshot
+ }
+ }
+}
+
+func lookupElement(snapshot *appSnapshot, elementIndex string) (*elementRecord, error) {
+ index, err := strconv.Atoi(elementIndex)
+ if err != nil {
+ return nil, fmt.Errorf("unknown element_index %q", elementIndex)
+ }
+ for _, record := range snapshot.Elements {
+ if record.Index == index {
+ copy := record
+ return &copy, nil
+ }
+ }
+ return nil, fmt.Errorf("unknown element_index %q", elementIndex)
+}
+
+func runPowerShell(request psRequest) (*psResponse, error) {
+ if runtime.GOOS != "windows" {
+ return nil, errors.New("Windows Computer Use runtime requires powershell.exe on Windows")
+ }
+
+ tempDir, err := os.MkdirTemp("", "open-computer-use-windows-*")
+ if err != nil {
+ return nil, err
+ }
+ defer os.RemoveAll(tempDir)
+
+ scriptPath := filepath.Join(tempDir, "runtime.ps1")
+ operationPath := filepath.Join(tempDir, "operation.json")
+ if err := os.WriteFile(scriptPath, []byte(windowsRuntimeScript), 0o600); err != nil {
+ return nil, err
+ }
+ operationData, err := json.Marshal(request)
+ if err != nil {
+ return nil, err
+ }
+ if err := os.WriteFile(operationPath, operationData, 0o600); err != nil {
+ return nil, err
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
+ defer cancel()
+
+ cmd := exec.CommandContext(ctx, "powershell.exe", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-File", scriptPath, operationPath)
+ output, err := cmd.CombinedOutput()
+ if ctx.Err() == context.DeadlineExceeded {
+ return nil, errors.New("Windows runtime timed out after 30s")
+ }
+ if err != nil {
+ text := strings.TrimSpace(string(output))
+ if text == "" {
+ text = err.Error()
+ }
+ return nil, fmt.Errorf("Windows runtime failed: %s", text)
+ }
+
+ var response psResponse
+ if err := json.Unmarshal(output, &response); err != nil {
+ return nil, fmt.Errorf("Windows runtime returned invalid JSON: %w: %s", err, strings.TrimSpace(string(output)))
+ }
+ return &response, nil
+}
+
+func requiredString(args map[string]any, key string) string {
+ value, _ := args[key].(string)
+ return strings.TrimSpace(value)
+}
+
+func optionalString(args map[string]any, key string) string {
+ value, _ := args[key].(string)
+ return value
+}
+
+func requiredFloat(args map[string]any, key string) *float64 {
+ return optionalFloat(args, key)
+}
+
+func optionalFloat(args map[string]any, key string) *float64 {
+ switch value := args[key].(type) {
+ case float64:
+ return &value
+ case int:
+ float := float64(value)
+ return &float
+ case json.Number:
+ float, err := value.Float64()
+ if err == nil {
+ return &float
+ }
+ }
+ return nil
+}
+
+func intValue(value *float64, fallback int) int {
+ if value == nil {
+ return fallback
+ }
+ return int(*value)
+}
+
+func floatValue(value *float64, fallback float64) float64 {
+ if value == nil {
+ return fallback
+ }
+ return *value
+}
+
+func defaultString(value, fallback string) string {
+ if strings.TrimSpace(value) == "" {
+ return fallback
+ }
+ return value
+}
+
+func toolDefinitions() []toolDefinition {
+ return []toolDefinition{
+ {
+ Name: "click",
+ Description: "Click an element by index or pixel coordinates from screenshot. This tool is part of plugin `Computer Use`.",
+ Annotations: defaultAnnotations(),
+ InputSchema: objectSchema(map[string]any{
+ "app": stringProperty("App name or bundle identifier"),
+ "element_index": stringProperty("Element index to click"),
+ "x": numberProperty("X coordinate in screenshot pixel coordinates"),
+ "y": numberProperty("Y coordinate in screenshot pixel coordinates"),
+ "click_count": integerProperty("Number of clicks. Defaults to 1"),
+ "mouse_button": enumStringProperty("Mouse button to click. Defaults to left.", []string{"left", "right", "middle"}),
+ }, []string{"app"}),
+ },
+ {
+ Name: "drag",
+ Description: "Drag from one point to another using pixel coordinates. This tool is part of plugin `Computer Use`.",
+ Annotations: defaultAnnotations(),
+ InputSchema: objectSchema(map[string]any{
+ "app": stringProperty("App name or bundle identifier"),
+ "from_x": numberProperty("Start X coordinate"),
+ "from_y": numberProperty("Start Y coordinate"),
+ "to_x": numberProperty("End X coordinate"),
+ "to_y": numberProperty("End Y coordinate"),
+ }, []string{"app", "from_x", "from_y", "to_x", "to_y"}),
+ },
+ {
+ Name: "get_app_state",
+ Description: "Get the state of an already running app's key window and return a screenshot and accessibility tree. This must be called once per assistant turn before interacting with the app. This tool is part of plugin `Computer Use`.",
+ Annotations: readOnlyAnnotations(),
+ InputSchema: objectSchema(map[string]any{
+ "app": stringProperty("App name or bundle identifier"),
+ }, []string{"app"}),
+ },
+ {
+ Name: "list_apps",
+ Description: "List the apps on this computer. Returns the set of apps that are currently running, as well as any that have been used in the last 14 days, including details on usage frequency. This tool is part of plugin `Computer Use`.",
+ Annotations: readOnlyAnnotations(),
+ InputSchema: objectSchema(map[string]any{}, nil),
+ },
+ {
+ Name: "perform_secondary_action",
+ Description: "Invoke a secondary accessibility action exposed by an element. This tool is part of plugin `Computer Use`.",
+ Annotations: defaultAnnotations(),
+ InputSchema: objectSchema(map[string]any{
+ "app": stringProperty("App name or bundle identifier"),
+ "element_index": stringProperty("Element identifier"),
+ "action": stringProperty("Secondary accessibility action name"),
+ }, []string{"app", "element_index", "action"}),
+ },
+ {
+ Name: "press_key",
+ Description: "Press a key or key-combination on the keyboard, including modifier and navigation keys.\n - This supports xdotool's `key` syntax.\n - Examples: \"a\", \"Return\", \"Tab\", \"super+c\", \"Up\", \"KP_0\" (for the numpad 0). This tool is part of plugin `Computer Use`.",
+ Annotations: defaultAnnotations(),
+ InputSchema: objectSchema(map[string]any{
+ "app": stringProperty("App name or bundle identifier"),
+ "key": stringProperty("Key or key-combination to press"),
+ }, []string{"app", "key"}),
+ },
+ {
+ Name: "scroll",
+ Description: "Scroll an element in a direction by a number of pages. This tool is part of plugin `Computer Use`.",
+ Annotations: defaultAnnotations(),
+ InputSchema: objectSchema(map[string]any{
+ "app": stringProperty("App name or bundle identifier"),
+ "direction": stringProperty("Scroll direction: up, down, left, or right"),
+ "element_index": stringProperty("Element identifier"),
+ "pages": numberProperty("Number of pages to scroll. Fractional values are supported. Defaults to 1"),
+ }, []string{"app", "element_index", "direction"}),
+ },
+ {
+ Name: "set_value",
+ Description: "Set the value of a settable accessibility element. This tool is part of plugin `Computer Use`.",
+ Annotations: defaultAnnotations(),
+ InputSchema: objectSchema(map[string]any{
+ "app": stringProperty("App name or bundle identifier"),
+ "element_index": stringProperty("Element identifier"),
+ "value": stringProperty("Value to assign"),
+ }, []string{"app", "element_index", "value"}),
+ },
+ {
+ Name: "type_text",
+ Description: "Type literal text using keyboard input. This tool is part of plugin `Computer Use`.",
+ Annotations: defaultAnnotations(),
+ InputSchema: objectSchema(map[string]any{
+ "app": stringProperty("App name or bundle identifier"),
+ "text": stringProperty("Literal text to type"),
+ }, []string{"app", "text"}),
+ },
+ }
+}
+
+func objectSchema(properties map[string]any, required []string) map[string]any {
+ schema := map[string]any{
+ "type": "object",
+ "properties": properties,
+ "additionalProperties": false,
+ }
+ if len(required) > 0 {
+ schema["required"] = required
+ }
+ return schema
+}
+
+func defaultAnnotations() map[string]any {
+ return map[string]any{"destructiveHint": false, "openWorldHint": false}
+}
+
+func readOnlyAnnotations() map[string]any {
+ return map[string]any{"destructiveHint": false, "idempotentHint": true, "openWorldHint": false, "readOnlyHint": true}
+}
+
+func stringProperty(description string) map[string]any {
+ return map[string]any{"type": "string", "description": description}
+}
+
+func enumStringProperty(description string, values []string) map[string]any {
+ property := stringProperty(description)
+ property["enum"] = values
+ return property
+}
+
+func numberProperty(description string) map[string]any {
+ return map[string]any{"type": "number", "description": description}
+}
+
+func integerProperty(description string) map[string]any {
+ return map[string]any{"type": "integer", "description": description}
+}
+
+func main() {
+ if err := runCLI(os.Args[1:], os.Stdout); err != nil {
+ fmt.Fprintln(os.Stderr, err)
+ os.Exit(1)
+ }
+}
+
+func runCLI(args []string, stdout io.Writer) error {
+ if len(args) == 0 {
+ fmt.Fprint(stdout, helpText(""))
+ return nil
+ }
+
+ switch args[0] {
+ case "-h", "--help", "help":
+ topic := ""
+ if len(args) > 1 {
+ topic = args[1]
+ }
+ fmt.Fprint(stdout, helpText(topic))
+ return nil
+ case "-v", "--version", "version":
+ fmt.Fprintln(stdout, version)
+ return nil
+ case "mcp":
+ return runMCP(os.Stdin, stdout)
+ case "doctor":
+ fmt.Fprintln(stdout, "Windows runtime: UI Automation and Win32 window-message bridge are available when this process runs in the signed-in desktop session.")
+ return nil
+ case "list-apps":
+ result := newService().callTool("list_apps", map[string]any{})
+ if result.IsError {
+ return errors.New(result.Content[0].Text)
+ }
+ fmt.Fprintln(stdout, result.Content[0].Text)
+ return nil
+ case "snapshot":
+ if len(args) != 2 {
+ return errors.New("snapshot requires an app name, process name, window title, or pid")
+ }
+ result := newService().callTool("get_app_state", map[string]any{"app": args[1]})
+ if result.IsError {
+ return errors.New(result.Content[0].Text)
+ }
+ fmt.Fprintln(stdout, result.Content[0].Text)
+ return nil
+ case "call":
+ output, hasError, err := runCallCommand(args[1:], newService())
+ if err != nil {
+ return err
+ }
+ encoded, err := json.MarshalIndent(output, "", " ")
+ if err != nil {
+ return err
+ }
+ fmt.Fprintln(stdout, string(encoded))
+ if hasError {
+ return errors.New("tool call returned isError=true")
+ }
+ return nil
+ default:
+ return fmt.Errorf("unknown command: %s\n\n%s", args[0], helpText(""))
+ }
+}
+
+func runCallCommand(args []string, svc *service) (any, bool, error) {
+ if len(args) == 0 {
+ return nil, false, errors.New("call requires a tool name or --calls/--calls-file")
+ }
+
+ var toolName, argsJSON, argsFile, callsJSON, callsFile string
+ for index := 0; index < len(args); index++ {
+ arg := args[index]
+ switch arg {
+ case "--args":
+ index++
+ if index >= len(args) {
+ return nil, false, errors.New("--args requires a value")
+ }
+ argsJSON = args[index]
+ case "--args-file":
+ index++
+ if index >= len(args) {
+ return nil, false, errors.New("--args-file requires a value")
+ }
+ argsFile = args[index]
+ case "--calls":
+ index++
+ if index >= len(args) {
+ return nil, false, errors.New("--calls requires a value")
+ }
+ callsJSON = args[index]
+ case "--calls-file":
+ index++
+ if index >= len(args) {
+ return nil, false, errors.New("--calls-file requires a value")
+ }
+ callsFile = args[index]
+ default:
+ if strings.HasPrefix(arg, "-") {
+ return nil, false, fmt.Errorf("unknown call option: %s", arg)
+ }
+ if toolName != "" {
+ return nil, false, errors.New("call accepts at most one tool name")
+ }
+ toolName = arg
+ }
+ }
+
+ if callsJSON != "" || callsFile != "" {
+ if toolName != "" || argsJSON != "" || argsFile != "" {
+ return nil, false, errors.New("call sequence does not accept a tool name, --args, or --args-file")
+ }
+ calls, err := readCallSequence(callsJSON, callsFile)
+ if err != nil {
+ return nil, false, err
+ }
+ var outputs []map[string]any
+ hasError := false
+ for _, call := range calls {
+ result := svc.callTool(call.Tool, call.Args)
+ outputs = append(outputs, map[string]any{"tool": call.Tool, "result": result})
+ if result.IsError {
+ hasError = true
+ break
+ }
+ }
+ return outputs, hasError, nil
+ }
+
+ if toolName == "" {
+ return nil, false, errors.New("call requires a tool name or --calls/--calls-file")
+ }
+ arguments, err := readArguments(argsJSON, argsFile)
+ if err != nil {
+ return nil, false, err
+ }
+ result := svc.callTool(toolName, arguments)
+ return result, result.IsError, nil
+}
+
+type callSpec struct {
+ Tool string
+ Args map[string]any
+}
+
+func readArguments(inline, file string) (map[string]any, error) {
+ if inline != "" && file != "" {
+ return nil, errors.New("Use either inline JSON or a JSON file, not both")
+ }
+ if inline == "" && file == "" {
+ return map[string]any{}, nil
+ }
+ source, err := readJSONSource(inline, file)
+ if err != nil {
+ return nil, err
+ }
+ var args map[string]any
+ decoder := json.NewDecoder(strings.NewReader(source))
+ decoder.UseNumber()
+ if err := decoder.Decode(&args); err != nil {
+ return nil, fmt.Errorf("Invalid JSON input: %w", err)
+ }
+ if args == nil {
+ return nil, errors.New("--args must be a JSON object")
+ }
+ return args, nil
+}
+
+func readCallSequence(inline, file string) ([]callSpec, error) {
+ if inline != "" && file != "" {
+ return nil, errors.New("Use either --calls or --calls-file, not both")
+ }
+ source, err := readJSONSource(inline, file)
+ if err != nil {
+ return nil, err
+ }
+ var raw []map[string]any
+ decoder := json.NewDecoder(strings.NewReader(source))
+ decoder.UseNumber()
+ if err := decoder.Decode(&raw); err != nil {
+ return nil, fmt.Errorf("Invalid JSON input: %w", err)
+ }
+ calls := make([]callSpec, 0, len(raw))
+ for index, item := range raw {
+ name, _ := item["tool"].(string)
+ if name == "" {
+ name, _ = item["name"].(string)
+ }
+ if name == "" {
+ return nil, fmt.Errorf("call sequence item #%d requires a non-empty tool", index+1)
+ }
+ args, _ := item["args"].(map[string]any)
+ if args == nil {
+ args, _ = item["arguments"].(map[string]any)
+ }
+ if args == nil {
+ args = map[string]any{}
+ }
+ calls = append(calls, callSpec{Tool: name, Args: args})
+ }
+ return calls, nil
+}
+
+func readJSONSource(inline, file string) (string, error) {
+ if inline != "" {
+ return inline, nil
+ }
+ if file == "" {
+ return "", errors.New("JSON input is required")
+ }
+ data, err := os.ReadFile(file)
+ if err != nil {
+ return "", err
+ }
+ return string(data), nil
+}
+
+func runMCP(stdin io.Reader, stdout io.Writer) error {
+ svc := newService()
+ decoder := json.NewDecoder(stdin)
+ encoder := json.NewEncoder(stdout)
+ for {
+ var request map[string]any
+ if err := decoder.Decode(&request); err != nil {
+ if errors.Is(err, io.EOF) {
+ return nil
+ }
+ _ = encoder.Encode(jsonRPCError(nil, -32700, "Invalid JSON-RPC payload"))
+ continue
+ }
+ response := handleMCPRequest(request, svc)
+ if response != nil {
+ if err := encoder.Encode(response); err != nil {
+ return err
+ }
+ }
+ }
+}
+
+func handleMCPRequest(request map[string]any, svc *service) map[string]any {
+ id := request["id"]
+ method, _ := request["method"].(string)
+ params, _ := request["params"].(map[string]any)
+ switch method {
+ case "initialize":
+ return jsonRPCResult(id, map[string]any{
+ "protocolVersion": "2025-03-26",
+ "serverInfo": map[string]any{
+ "name": "open-computer-use",
+ "version": version,
+ },
+ "capabilities": map[string]any{"tools": map[string]any{"listChanged": false}},
+ "instructions": serverInstructions,
+ })
+ case "notifications/initialized", "notifications/turn-ended":
+ return nil
+ case "ping":
+ return jsonRPCResult(id, map[string]any{})
+ case "tools/list":
+ return jsonRPCResult(id, map[string]any{"tools": toolDefinitions()})
+ case "tools/call":
+ name, _ := params["name"].(string)
+ arguments, _ := params["arguments"].(map[string]any)
+ if arguments == nil {
+ arguments = map[string]any{}
+ }
+ return jsonRPCResult(id, svc.callTool(name, arguments))
+ default:
+ if method == "" {
+ return nil
+ }
+ return jsonRPCError(id, -32601, "Method not found: "+method)
+ }
+}
+
+func jsonRPCResult(id any, result any) map[string]any {
+ return map[string]any{"jsonrpc": "2.0", "id": id, "result": result}
+}
+
+func jsonRPCError(id any, code int, message string) map[string]any {
+ return map[string]any{
+ "jsonrpc": "2.0",
+ "id": id,
+ "error": map[string]any{"code": code, "message": message},
+ }
+}
+
+func helpText(command string) string {
+ switch command {
+ case "mcp":
+ return "Usage:\n open-computer-use.exe mcp\n\nStart the stdio MCP server.\n"
+ case "call":
+ return "Usage:\n open-computer-use.exe call <tool> [--args '<json-object>']\n open-computer-use.exe call --calls '<json-array>'\n\nThe JSON array form keeps all calls in one process so element_index state can be reused.\n"
+ case "snapshot":
+ return "Usage:\n open-computer-use.exe snapshot <app>\n\nPrint the current Windows UI Automation snapshot for the target app.\n"
+ default:
+ return `Open Computer Use for Windows
+
+Usage:
+ open-computer-use.exe [command] [options]
+
+Commands:
+ mcp Start the stdio MCP server.
+ doctor Print Windows runtime notes.
+ list-apps Print running apps with top-level windows.
+ snapshot <app> Print the current UI Automation snapshot for an app.
+ call <tool> Call one tool, or run a JSON array of tool calls.
+ help [command] Show general or command-specific help.
+ version Print the CLI version.
+
+Notes:
+ The Windows runtime uses UI Automation first, then Win32 window messages for
+ fallback input. Run it in the signed-in desktop session, not as a service.
+`
+ }
+}
diff --git a/apps/OpenComputerUseWindows/main_test.go b/apps/OpenComputerUseWindows/main_test.go
new file mode 100644
index 0000000..d496836
--- /dev/null
+++ b/apps/OpenComputerUseWindows/main_test.go
@@ -0,0 +1,90 @@
+package main
+
+import (
+ "bytes"
+ "encoding/json"
+ "strings"
+ "testing"
+)
+
+func TestToolDefinitionCount(t *testing.T) {
+ if got := len(toolDefinitions()); got != 9 {
+ t.Fatalf("toolDefinitions() count = %d, want 9", got)
+ }
+}
+
+func TestCallSequenceStopsAfterFirstToolError(t *testing.T) {
+ output, hasError, err := runCallCommand([]string{
+ "--calls",
+ `[{"tool":"not_a_tool"},{"tool":"list_apps"}]`,
+ }, newService())
+ if err != nil {
+ t.Fatal(err)
+ }
+ if !hasError {
+ t.Fatal("expected hasError")
+ }
+ items, ok := output.([]map[string]any)
+ if !ok {
+ t.Fatalf("output type = %T", output)
+ }
+ if len(items) != 1 {
+ t.Fatalf("sequence output count = %d, want 1", len(items))
+ }
+}
+
+func TestReadArgumentsAcceptsJSONObject(t *testing.T) {
+ args, err := readArguments(`{"app":"Notepad","pages":2}`, "")
+ if err != nil {
+ t.Fatal(err)
+ }
+ if args["app"] != "Notepad" {
+ t.Fatalf("app = %v", args["app"])
+ }
+ if args["pages"].(json.Number).String() != "2" {
+ t.Fatalf("pages = %v", args["pages"])
+ }
+}
+
+func TestMCPInitializeResponseContainsToolsCapability(t *testing.T) {
+ request := map[string]any{
+ "jsonrpc": "2.0",
+ "id": float64(1),
+ "method": "initialize",
+ "params": map[string]any{},
+ }
+ response := handleMCPRequest(request, newService())
+ result, ok := response["result"].(map[string]any)
+ if !ok {
+ t.Fatalf("missing result: %#v", response)
+ }
+ capabilities := result["capabilities"].(map[string]any)
+ if _, ok := capabilities["tools"]; !ok {
+ t.Fatalf("missing tools capability: %#v", capabilities)
+ }
+}
+
+func TestCLIHelpMentionsWindowsRuntime(t *testing.T) {
+ var out bytes.Buffer
+ if err := runCLI([]string{"--help"}, &out); err != nil {
+ t.Fatal(err)
+ }
+ if !strings.Contains(out.String(), "Open Computer Use for Windows") {
+ t.Fatalf("help text did not mention Windows runtime:\n%s", out.String())
+ }
+}
+
+func TestWindowsRuntimeForegroundActionsRequireOptIn(t *testing.T) {
+ if !strings.Contains(windowsRuntimeScript, "OPEN_COMPUTER_USE_WINDOWS_ALLOW_APP_LAUNCH") {
+ t.Fatal("Windows app launch fallback must remain opt-in")
+ }
+ if !strings.Contains(windowsRuntimeScript, "OPEN_COMPUTER_USE_WINDOWS_ALLOW_FOCUS_ACTIONS") {
+ t.Fatal("Windows SetFocus action must remain opt-in")
+ }
+ if !strings.Contains(windowsRuntimeScript, "OPEN_COMPUTER_USE_WINDOWS_ALLOW_UIA_TEXT_FALLBACK") {
+ t.Fatal("Windows UIA text fallback must remain opt-in")
+ }
+ if !strings.Contains(serverInstructions, "does not auto-launch apps, perform SetFocus, or use UIA text fallback by default") {
+ t.Fatal("MCP instructions must document the Windows background-focus policy")
+ }
+}
diff --git a/apps/OpenComputerUseWindows/runtime.ps1 b/apps/OpenComputerUseWindows/runtime.ps1
new file mode 100644
index 0000000..95dcfd7
--- /dev/null
+++ b/apps/OpenComputerUseWindows/runtime.ps1
@@ -0,0 +1,931 @@
+param(
+ [Parameter(Mandatory = $true)]
+ [string]$OperationPath
+)
+
+$ErrorActionPreference = "Stop"
+
+Add-Type -AssemblyName UIAutomationClient
+Add-Type -AssemblyName UIAutomationTypes
+Add-Type -AssemblyName System.Drawing
+
+Add-Type -TypeDefinition @"
+using System;
+using System.Runtime.InteropServices;
+
+public static class OCUWin32 {
+ [StructLayout(LayoutKind.Sequential)]
+ public struct RECT {
+ public int Left;
+ public int Top;
+ public int Right;
+ public int Bottom;
+ }
+
+ [StructLayout(LayoutKind.Sequential)]
+ public struct POINT {
+ public int X;
+ public int Y;
+ }
+
+ [DllImport("user32.dll")]
+ public static extern bool GetWindowRect(IntPtr hWnd, out RECT rect);
+
+ [DllImport("user32.dll")]
+ public static extern bool ScreenToClient(IntPtr hWnd, ref POINT point);
+
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)]
+ public static extern bool PostMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);
+
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)]
+ public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, IntPtr lParam);
+
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)]
+ public static extern IntPtr SendMessage(IntPtr hWnd, UInt32 msg, IntPtr wParam, string lParam);
+}
+"@
+
+$WM_SETTEXT = 0x000C
+$WM_MOUSEMOVE = 0x0200
+$WM_LBUTTONDOWN = 0x0201
+$WM_LBUTTONUP = 0x0202
+$WM_RBUTTONDOWN = 0x0204
+$WM_RBUTTONUP = 0x0205
+$WM_MBUTTONDOWN = 0x0207
+$WM_MBUTTONUP = 0x0208
+$WM_MOUSEWHEEL = 0x020A
+$WM_MOUSEHWHEEL = 0x020E
+$WM_KEYDOWN = 0x0100
+$WM_KEYUP = 0x0101
+$WM_CHAR = 0x0102
+$EM_SETSEL = 0x00B1
+$EM_REPLACESEL = 0x00C2
+
+function Test-EnvFlagEnabled([string]$name) {
+ $value = [Environment]::GetEnvironmentVariable($name)
+ if ([string]::IsNullOrWhiteSpace($value)) {
+ return $false
+ }
+ $normalized = $value.Trim().ToLowerInvariant()
+ return @("1", "true", "yes", "on") -contains $normalized
+}
+
+function New-Frame($x, $y, $width, $height) {
+ if ($width -lt 0 -or $height -lt 0) {
+ return $null
+ }
+ [pscustomobject]@{
+ x = [double]$x
+ y = [double]$y
+ width = [double]$width
+ height = [double]$height
+ }
+}
+
+function ConvertTo-LParam([int]$x, [int]$y) {
+ $packed = (($y -band 0xffff) -shl 16) -bor ($x -band 0xffff)
+ [IntPtr]$packed
+}
+
+function ConvertTo-WheelWParam([int]$delta) {
+ $packed = (($delta -band 0xffff) -shl 16)
+ [IntPtr]$packed
+}
+
+function Get-WindowRectFrame([IntPtr]$hwnd) {
+ $rect = New-Object OCUWin32+RECT
+ if ([OCUWin32]::GetWindowRect($hwnd, [ref]$rect)) {
+ return New-Frame $rect.Left $rect.Top ($rect.Right - $rect.Left) ($rect.Bottom - $rect.Top)
+ }
+ return $null
+}
+
+function Get-ElementFrame($element, $windowBounds) {
+ try {
+ $rect = $element.Current.BoundingRectangle
+ if ($rect.IsEmpty -or $rect.Width -le 0 -or $rect.Height -le 0) {
+ return $null
+ }
+ if ($null -ne $windowBounds) {
+ return New-Frame ($rect.X - $windowBounds.x) ($rect.Y - $windowBounds.y) $rect.Width $rect.Height
+ }
+ return New-Frame $rect.X $rect.Y $rect.Width $rect.Height
+ } catch {
+ return $null
+ }
+}
+
+function Get-ScreenPoint($localFrame, $windowBounds) {
+ if ($null -eq $localFrame -or $null -eq $windowBounds) {
+ return $null
+ }
+ [pscustomobject]@{
+ x = [int][math]::Round($windowBounds.x + $localFrame.x + ($localFrame.width / 2))
+ y = [int][math]::Round($windowBounds.y + $localFrame.y + ($localFrame.height / 2))
+ }
+}
+
+function Send-MouseClick([IntPtr]$hwnd, [int]$screenX, [int]$screenY, [string]$button, [int]$count) {
+ $point = New-Object OCUWin32+POINT
+ $point.X = $screenX
+ $point.Y = $screenY
+ [void][OCUWin32]::ScreenToClient($hwnd, [ref]$point)
+ $lParam = ConvertTo-LParam $point.X $point.Y
+
+ $down = $WM_LBUTTONDOWN
+ $up = $WM_LBUTTONUP
+ $downFlag = 0x0001
+ if ($button -eq "right") {
+ $down = $WM_RBUTTONDOWN
+ $up = $WM_RBUTTONUP
+ $downFlag = 0x0002
+ } elseif ($button -eq "middle") {
+ $down = $WM_MBUTTONDOWN
+ $up = $WM_MBUTTONUP
+ $downFlag = 0x0010
+ }
+
+ $repeat = [math]::Max(1, $count)
+ for ($i = 0; $i -lt $repeat; $i++) {
+ [void][OCUWin32]::PostMessage($hwnd, $WM_MOUSEMOVE, [IntPtr]::Zero, $lParam)
+ [void][OCUWin32]::PostMessage($hwnd, $down, [IntPtr]$downFlag, $lParam)
+ Start-Sleep -Milliseconds 35
+ [void][OCUWin32]::PostMessage($hwnd, $up, [IntPtr]::Zero, $lParam)
+ Start-Sleep -Milliseconds 50
+ }
+}
+
+function Send-Drag([IntPtr]$hwnd, [int]$fromX, [int]$fromY, [int]$toX, [int]$toY) {
+ $start = New-Object OCUWin32+POINT
+ $start.X = $fromX
+ $start.Y = $fromY
+ [void][OCUWin32]::ScreenToClient($hwnd, [ref]$start)
+ $end = New-Object OCUWin32+POINT
+ $end.X = $toX
+ $end.Y = $toY
+ [void][OCUWin32]::ScreenToClient($hwnd, [ref]$end)
+
+ $steps = 12
+ $startParam = ConvertTo-LParam $start.X $start.Y
+ [void][OCUWin32]::PostMessage($hwnd, $WM_MOUSEMOVE, [IntPtr]::Zero, $startParam)
+ [void][OCUWin32]::PostMessage($hwnd, $WM_LBUTTONDOWN, [IntPtr]1, $startParam)
+ for ($i = 1; $i -le $steps; $i++) {
+ $x = [int][math]::Round($start.X + (($end.X - $start.X) * $i / $steps))
+ $y = [int][math]::Round($start.Y + (($end.Y - $start.Y) * $i / $steps))
+ [void][OCUWin32]::PostMessage($hwnd, $WM_MOUSEMOVE, [IntPtr]1, (ConvertTo-LParam $x $y))
+ Start-Sleep -Milliseconds 20
+ }
+ [void][OCUWin32]::PostMessage($hwnd, $WM_LBUTTONUP, [IntPtr]::Zero, (ConvertTo-LParam $end.X $end.Y))
+}
+
+function Send-Scroll([IntPtr]$hwnd, [int]$screenX, [int]$screenY, [string]$direction, [double]$pages) {
+ $point = New-Object OCUWin32+POINT
+ $point.X = $screenX
+ $point.Y = $screenY
+ [void][OCUWin32]::ScreenToClient($hwnd, [ref]$point)
+ $lParam = ConvertTo-LParam $point.X $point.Y
+ $delta = [int][math]::Round(120 * $pages)
+ $message = $WM_MOUSEWHEEL
+ if ($direction -eq "down" -or $direction -eq "right") {
+ $delta = -1 * $delta
+ }
+ if ($direction -eq "left" -or $direction -eq "right") {
+ $message = $WM_MOUSEHWHEEL
+ }
+ [void][OCUWin32]::PostMessage($hwnd, $message, (ConvertTo-WheelWParam $delta), $lParam)
+}
+
+function Send-Text([IntPtr]$hwnd, [string]$text) {
+ foreach ($char in $text.ToCharArray()) {
+ [void][OCUWin32]::PostMessage($hwnd, $WM_CHAR, [IntPtr][int][char]$char, [IntPtr]::Zero)
+ Start-Sleep -Milliseconds 8
+ }
+}
+
+function Send-TextToEditHandle([IntPtr]$hwnd, [string]$text, $element) {
+ if ($hwnd -eq [IntPtr]::Zero) {
+ return $false
+ }
+
+ try {
+ [void][OCUWin32]::SendMessage($hwnd, $EM_SETSEL, [IntPtr](-1), [IntPtr](-1))
+ [void][OCUWin32]::SendMessage($hwnd, $EM_REPLACESEL, [IntPtr]1, $text)
+ return $true
+ } catch {
+ }
+
+ try {
+ $current = ""
+ if ($null -ne $element) {
+ $current = Get-ElementValue $element
+ }
+ [void][OCUWin32]::SendMessage($hwnd, $WM_SETTEXT, [IntPtr]::Zero, ($current + $text))
+ return $true
+ } catch {
+ return $false
+ }
+}
+
+function Get-VirtualKey([string]$key) {
+ $normalized = $key.ToLowerInvariant()
+ $map = @{
+ "return" = 0x0D; "enter" = 0x0D; "tab" = 0x09; "escape" = 0x1B; "esc" = 0x1B
+ "backspace" = 0x08; "back_space" = 0x08; "delete" = 0x2E; "space" = 0x20
+ "left" = 0x25; "up" = 0x26; "right" = 0x27; "down" = 0x28
+ "home" = 0x24; "end" = 0x23; "page_up" = 0x21; "prior" = 0x21; "page_down" = 0x22; "next" = 0x22
+ }
+ if ($map.ContainsKey($normalized)) {
+ return $map[$normalized]
+ }
+ if ($normalized -match "^f([1-9]|1[0-2])$") {
+ return 0x70 + [int]$Matches[1] - 1
+ }
+ if ($normalized -match "^kp_([0-9])$") {
+ return 0x60 + [int]$Matches[1]
+ }
+ if ($normalized.Length -eq 1) {
+ $code = [int][char]$normalized.ToUpperInvariant()[0]
+ if (($code -ge 0x30 -and $code -le 0x39) -or ($code -ge 0x41 -and $code -le 0x5A)) {
+ return $code
+ }
+ }
+ throw "Unsupported key: $key"
+}
+
+function Send-Key([IntPtr]$hwnd, [string]$key) {
+ $parts = $key -split "\+"
+ $main = $parts[$parts.Length - 1]
+ $modifiers = @()
+ for ($i = 0; $i -lt $parts.Length - 1; $i++) {
+ switch ($parts[$i].ToLowerInvariant()) {
+ "ctrl" { $modifiers += 0x11 }
+ "control" { $modifiers += 0x11 }
+ "shift" { $modifiers += 0x10 }
+ "alt" { $modifiers += 0x12 }
+ "super" { $modifiers += 0x5B }
+ "win" { $modifiers += 0x5B }
+ "cmd" { $modifiers += 0x5B }
+ }
+ }
+ foreach ($modifier in $modifiers) {
+ [void][OCUWin32]::PostMessage($hwnd, $WM_KEYDOWN, [IntPtr]$modifier, [IntPtr]::Zero)
+ }
+ $vk = Get-VirtualKey $main
+ [void][OCUWin32]::PostMessage($hwnd, $WM_KEYDOWN, [IntPtr]$vk, [IntPtr]::Zero)
+ Start-Sleep -Milliseconds 25
+ [void][OCUWin32]::PostMessage($hwnd, $WM_KEYUP, [IntPtr]$vk, [IntPtr]::Zero)
+ [array]::Reverse($modifiers)
+ foreach ($modifier in $modifiers) {
+ [void][OCUWin32]::PostMessage($hwnd, $WM_KEYUP, [IntPtr]$modifier, [IntPtr]::Zero)
+ }
+}
+
+function Resolve-App([string]$query) {
+ $normalized = $query.Trim()
+ $processQuery = $normalized
+ if ($processQuery.EndsWith(".exe", [System.StringComparison]::OrdinalIgnoreCase)) {
+ $processQuery = $processQuery.Substring(0, $processQuery.Length - 4)
+ }
+ $processes = @(Get-Process | Where-Object { $_.MainWindowHandle -ne 0 })
+ $pidValue = 0
+ if ([int]::TryParse($normalized, [ref]$pidValue)) {
+ $match = $processes | Where-Object { $_.Id -eq $pidValue } | Select-Object -First 1
+ if ($null -ne $match) {
+ return $match
+ }
+ }
+
+ $match = $processes | Where-Object {
+ $_.ProcessName -ieq $processQuery -or
+ "$($_.ProcessName).exe" -ieq $normalized -or
+ $_.MainWindowTitle -ieq $normalized -or
+ $_.MainWindowTitle -ilike "*$normalized*"
+ } | Select-Object -First 1
+ if ($null -ne $match) {
+ return $match
+ }
+
+ if (Test-EnvFlagEnabled "OPEN_COMPUTER_USE_WINDOWS_ALLOW_APP_LAUNCH") {
+ try {
+ $started = Start-Process -FilePath $normalized -PassThru
+ for ($i = 0; $i -lt 20; $i++) {
+ Start-Sleep -Milliseconds 250
+ $candidate = Get-Process -Id $started.Id -ErrorAction SilentlyContinue
+ if ($null -ne $candidate -and $candidate.MainWindowHandle -ne 0) {
+ return $candidate
+ }
+ }
+ } catch {
+ }
+ }
+
+ throw "appNotFound(`"$query`")"
+}
+
+function Get-MainElement($process) {
+ if ($process.MainWindowHandle -ne 0) {
+ return [Windows.Automation.AutomationElement]::FromHandle([IntPtr]$process.MainWindowHandle)
+ }
+ $condition = New-Object Windows.Automation.PropertyCondition ([Windows.Automation.AutomationElement]::ProcessIdProperty), $process.Id
+ $children = [Windows.Automation.AutomationElement]::RootElement.FindAll([Windows.Automation.TreeScope]::Children, $condition)
+ if ($children.Count -gt 0) {
+ return $children.Item(0)
+ }
+ throw "No top-level UI Automation window is available for $($process.ProcessName). Run the Windows runtime in the signed-in desktop session."
+}
+
+function Get-WindowBounds($process, $element) {
+ $hwnd = [IntPtr]$process.MainWindowHandle
+ if ($hwnd -ne [IntPtr]::Zero) {
+ $fromWin32 = Get-WindowRectFrame $hwnd
+ if ($null -ne $fromWin32) {
+ return $fromWin32
+ }
+ }
+ try {
+ $rect = $element.Current.BoundingRectangle
+ if (-not $rect.IsEmpty -and $rect.Width -gt 0 -and $rect.Height -gt 0) {
+ return New-Frame $rect.X $rect.Y $rect.Width $rect.Height
+ }
+ } catch {
+ }
+ return $null
+}
+
+function Get-PatternNames($element) {
+ $names = New-Object System.Collections.Generic.List[string]
+ foreach ($pattern in $element.GetSupportedPatterns()) {
+ $programmatic = $pattern.ProgrammaticName
+ if ($programmatic -like "InvokePatternIdentifiers.Pattern") { $names.Add("Invoke") }
+ elseif ($programmatic -like "TogglePatternIdentifiers.Pattern") { $names.Add("Toggle") }
+ elseif ($programmatic -like "SelectionItemPatternIdentifiers.Pattern") { $names.Add("Select") }
+ elseif ($programmatic -like "ExpandCollapsePatternIdentifiers.Pattern") {
+ try {
+ $state = $element.GetCurrentPattern([Windows.Automation.ExpandCollapsePattern]::Pattern).Current.ExpandCollapseState
+ if ($state -eq [Windows.Automation.ExpandCollapseState]::Collapsed) { $names.Add("Expand") }
+ elseif ($state -eq [Windows.Automation.ExpandCollapseState]::Expanded) { $names.Add("Collapse") }
+ } catch {
+ $names.Add("Expand")
+ $names.Add("Collapse")
+ }
+ }
+ elseif ($programmatic -like "ScrollItemPatternIdentifiers.Pattern") { $names.Add("ScrollIntoView") }
+ elseif ($programmatic -like "ScrollPatternIdentifiers.Pattern") { $names.Add("Scroll") }
+ elseif ($programmatic -like "ValuePatternIdentifiers.Pattern") { $names.Add("SetValue") }
+ }
+ if ($names.Count -gt 0) {
+ return @($names | Select-Object -Unique)
+ }
+ return @()
+}
+
+function Get-ElementString($element, [string]$propertyName) {
+ try {
+ $value = $element.Current.$propertyName
+ if ($null -eq $value) {
+ return ""
+ }
+ return [string]$value
+ } catch {
+ return ""
+ }
+}
+
+function Get-ElementInt64($element, [string]$propertyName) {
+ try {
+ return [int64]$element.Current.$propertyName
+ } catch {
+ return 0
+ }
+}
+
+function Get-ElementControlTypeName($element) {
+ try {
+ $controlType = $element.Current.ControlType
+ if ($null -eq $controlType) {
+ return ""
+ }
+ return [string]$controlType.ProgrammaticName
+ } catch {
+ return ""
+ }
+}
+
+function Get-ElementValue($element) {
+ try {
+ $valuePattern = $element.GetCurrentPattern([Windows.Automation.ValuePattern]::Pattern)
+ $value = $valuePattern.Current.Value
+ if ($null -eq $value) {
+ return ""
+ }
+ $text = [string]$value
+ if ($text.Length -gt 500) {
+ return $text.Substring(0, 500)
+ }
+ return $text
+ } catch {
+ return ""
+ }
+}
+
+function Get-ElementRecord($element, [int]$index, $windowBounds) {
+ $frame = Get-ElementFrame $element $windowBounds
+ $runtimeId = @()
+ try { $runtimeId = @($element.GetRuntimeId()) } catch {}
+ [pscustomobject]@{
+ index = $index
+ runtimeId = $runtimeId
+ automationId = Get-ElementString $element "AutomationId"
+ name = Get-ElementString $element "Name"
+ controlType = Get-ElementControlTypeName $element
+ localizedControlType = Get-ElementString $element "LocalizedControlType"
+ className = Get-ElementString $element "ClassName"
+ value = Get-ElementValue $element
+ nativeWindowHandle = Get-ElementInt64 $element "NativeWindowHandle"
+ frame = $frame
+ actions = @(Get-PatternNames $element)
+ }
+}
+
+function Get-ElementTitle($record) {
+ if (-not [string]::IsNullOrWhiteSpace($record.name)) {
+ return $record.name
+ }
+ if (-not [string]::IsNullOrWhiteSpace($record.automationId)) {
+ return "ID: $($record.automationId)"
+ }
+ return ""
+}
+
+function Render-Tree($element, $windowBounds) {
+ $records = New-Object System.Collections.Generic.List[object]
+ $lines = New-Object System.Collections.Generic.List[string]
+ $visited = New-Object System.Collections.Generic.HashSet[string]
+ $nextIndex = 0
+
+ function Visit($node, [int]$depth) {
+ if ($script:nextIndex -ge 500 -or $depth -gt 16) {
+ return
+ }
+ $runtime = ""
+ try { $runtime = (@($node.GetRuntimeId()) -join ".") } catch { $runtime = [guid]::NewGuid().ToString() }
+ if (-not $script:visited.Add($runtime)) {
+ return
+ }
+
+ $index = $script:nextIndex
+ $script:nextIndex++
+ $record = Get-ElementRecord $node $index $script:windowBounds
+ $script:records.Add($record)
+
+ $role = $record.localizedControlType
+ if ([string]::IsNullOrWhiteSpace($role)) {
+ $role = $record.controlType
+ }
+ $title = Get-ElementTitle $record
+ $actionsSegment = ""
+ if ($record.actions.Count -gt 0) {
+ $actionsSegment = " Secondary Actions: " + ($record.actions -join ", ")
+ }
+ $valueSegment = ""
+ if (-not [string]::IsNullOrWhiteSpace($record.value) -and $record.value -ne $title) {
+ $safeValue = (($record.value -replace "`r", "\\r") -replace "`n", "\\n")
+ $valueSegment = " Value: $safeValue"
+ }
+ $frameSegment = ""
+ if ($null -ne $record.frame) {
+ $frameSegment = " Frame: {{x: {0}, y: {1}, width: {2}, height: {3}}}" -f [int][math]::Round($record.frame.x), [int][math]::Round($record.frame.y), [int][math]::Round($record.frame.width), [int][math]::Round($record.frame.height)
+ }
+ $script:lines.Add(("`t" * ($depth + 1)) + "$index $role $title$valueSegment$actionsSegment$frameSegment")
+
+ try {
+ $children = $node.FindAll([Windows.Automation.TreeScope]::Children, [Windows.Automation.Condition]::TrueCondition)
+ for ($i = 0; $i -lt $children.Count; $i++) {
+ Visit $children.Item($i) ($depth + 1)
+ }
+ } catch {
+ }
+ }
+
+ $script:records = $records
+ $script:lines = $lines
+ $script:visited = $visited
+ $script:nextIndex = $nextIndex
+ $script:windowBounds = $windowBounds
+ Visit $element 0
+
+ [pscustomobject]@{
+ records = $records.ToArray()
+ lines = $lines.ToArray()
+ }
+}
+
+function Capture-WindowPngBase64($bounds) {
+ if ($null -eq $bounds -or $bounds.width -le 0 -or $bounds.height -le 0) {
+ return $null
+ }
+ try {
+ $bitmap = New-Object System.Drawing.Bitmap ([int][math]::Round($bounds.width)), ([int][math]::Round($bounds.height))
+ $graphics = [System.Drawing.Graphics]::FromImage($bitmap)
+ $graphics.CopyFromScreen([int][math]::Round($bounds.x), [int][math]::Round($bounds.y), 0, 0, $bitmap.Size)
+ $stream = New-Object System.IO.MemoryStream
+ $bitmap.Save($stream, [System.Drawing.Imaging.ImageFormat]::Png)
+ $graphics.Dispose()
+ $bitmap.Dispose()
+ $bytes = $stream.ToArray()
+ $stream.Dispose()
+ return [Convert]::ToBase64String($bytes)
+ } catch {
+ return $null
+ }
+}
+
+function Get-FocusedSummary($processId) {
+ try {
+ $focused = [Windows.Automation.AutomationElement]::FocusedElement
+ if ($null -ne $focused -and $focused.Current.ProcessId -eq $processId) {
+ $role = $focused.Current.LocalizedControlType
+ $name = $focused.Current.Name
+ if ([string]::IsNullOrWhiteSpace($name)) {
+ return $role
+ }
+ return "$role $name"
+ }
+ } catch {
+ }
+ return $null
+}
+
+function Get-SelectedText($processId) {
+ try {
+ $focused = [Windows.Automation.AutomationElement]::FocusedElement
+ if ($null -eq $focused -or $focused.Current.ProcessId -ne $processId) {
+ return $null
+ }
+ $textPattern = $focused.GetCurrentPattern([Windows.Automation.TextPattern]::Pattern)
+ $selection = $textPattern.GetSelection()
+ if ($selection.Count -gt 0) {
+ return $selection.Item(0).GetText(2048)
+ }
+ } catch {
+ }
+ return $null
+}
+
+function Build-Snapshot([string]$query) {
+ $process = Resolve-App $query
+ $element = Get-MainElement $process
+ $bounds = Get-WindowBounds $process $element
+ $rendered = Render-Tree $element $bounds
+ [pscustomobject]@{
+ app = [pscustomobject]@{
+ name = $process.ProcessName
+ bundleIdentifier = $process.ProcessName
+ pid = [int]$process.Id
+ }
+ windowTitle = $process.MainWindowTitle
+ windowBounds = $bounds
+ screenshotPngBase64 = Capture-WindowPngBase64 $bounds
+ treeLines = @($rendered.lines)
+ focusedSummary = Get-FocusedSummary $process.Id
+ selectedText = Get-SelectedText $process.Id
+ elements = @($rendered.records)
+ }
+}
+
+function List-Apps {
+ $lines = New-Object System.Collections.Generic.List[string]
+ foreach ($process in (Get-Process | Where-Object { $_.MainWindowHandle -ne 0 } | Sort-Object ProcessName, Id)) {
+ $title = $process.MainWindowTitle
+ if ([string]::IsNullOrWhiteSpace($title)) {
+ $title = "untitled"
+ }
+ $lines.Add(("{0} -- {1} [running, pid={2}, window={3}]" -f $process.ProcessName, $process.ProcessName, $process.Id, $title))
+ }
+ return ($lines -join "`n")
+}
+
+function Same-RuntimeId($left, $right) {
+ if ($null -eq $left -or $null -eq $right -or $left.Count -ne $right.Count) {
+ return $false
+ }
+ for ($i = 0; $i -lt $left.Count; $i++) {
+ if ([int]$left[$i] -ne [int]$right[$i]) {
+ return $false
+ }
+ }
+ return $true
+}
+
+function Get-AllElements($root) {
+ $items = New-Object System.Collections.Generic.List[object]
+ $items.Add($root)
+ try {
+ $descendants = $root.FindAll([Windows.Automation.TreeScope]::Descendants, [Windows.Automation.Condition]::TrueCondition)
+ for ($i = 0; $i -lt $descendants.Count; $i++) {
+ $items.Add($descendants.Item($i))
+ }
+ } catch {
+ }
+ return $items.ToArray()
+}
+
+function Find-Element($process, $record) {
+ if ($null -eq $record) {
+ return $null
+ }
+ $root = Get-MainElement $process
+ foreach ($element in (Get-AllElements $root)) {
+ try {
+ if (Same-RuntimeId @($element.GetRuntimeId()) @($record.runtimeId)) {
+ return $element
+ }
+ } catch {
+ }
+ }
+ foreach ($element in (Get-AllElements $root)) {
+ try {
+ $sameAutomationId = -not [string]::IsNullOrWhiteSpace($record.automationId) -and $element.Current.AutomationId -eq $record.automationId
+ $sameName = -not [string]::IsNullOrWhiteSpace($record.name) -and $element.Current.Name -eq $record.name
+ $sameType = $element.Current.ControlType.ProgrammaticName -eq $record.controlType
+ if (($sameAutomationId -or $sameName) -and $sameType) {
+ return $element
+ }
+ } catch {
+ }
+ }
+ return $null
+}
+
+function Get-CurrentPatternOrNull($element, $pattern) {
+ try {
+ return $element.GetCurrentPattern($pattern)
+ } catch {
+ return $null
+ }
+}
+
+function Invoke-PreferredClick($element) {
+ $invoke = Get-CurrentPatternOrNull $element ([Windows.Automation.InvokePattern]::Pattern)
+ if ($null -ne $invoke) {
+ $invoke.Invoke()
+ return $true
+ }
+ $selection = Get-CurrentPatternOrNull $element ([Windows.Automation.SelectionItemPattern]::Pattern)
+ if ($null -ne $selection) {
+ $selection.Select()
+ return $true
+ }
+ $toggle = Get-CurrentPatternOrNull $element ([Windows.Automation.TogglePattern]::Pattern)
+ if ($null -ne $toggle) {
+ $toggle.Toggle()
+ return $true
+ }
+ return $false
+}
+
+function Invoke-SecondaryAction($element, [string]$action) {
+ switch ($action.ToLowerInvariant()) {
+ "invoke" {
+ $pattern = Get-CurrentPatternOrNull $element ([Windows.Automation.InvokePattern]::Pattern)
+ if ($null -ne $pattern) { $pattern.Invoke(); return }
+ }
+ "toggle" {
+ $pattern = Get-CurrentPatternOrNull $element ([Windows.Automation.TogglePattern]::Pattern)
+ if ($null -ne $pattern) { $pattern.Toggle(); return }
+ }
+ "select" {
+ $pattern = Get-CurrentPatternOrNull $element ([Windows.Automation.SelectionItemPattern]::Pattern)
+ if ($null -ne $pattern) { $pattern.Select(); return }
+ }
+ "expand" {
+ $pattern = Get-CurrentPatternOrNull $element ([Windows.Automation.ExpandCollapsePattern]::Pattern)
+ if ($null -ne $pattern) { $pattern.Expand(); return }
+ }
+ "collapse" {
+ $pattern = Get-CurrentPatternOrNull $element ([Windows.Automation.ExpandCollapsePattern]::Pattern)
+ if ($null -ne $pattern) { $pattern.Collapse(); return }
+ }
+ "scrollintoview" {
+ $pattern = Get-CurrentPatternOrNull $element ([Windows.Automation.ScrollItemPattern]::Pattern)
+ if ($null -ne $pattern) { $pattern.ScrollIntoView(); return }
+ }
+ "setfocus" {
+ if (-not (Test-EnvFlagEnabled "OPEN_COMPUTER_USE_WINDOWS_ALLOW_FOCUS_ACTIONS")) {
+ throw "SetFocus is disabled by default to avoid stealing user focus; set OPEN_COMPUTER_USE_WINDOWS_ALLOW_FOCUS_ACTIONS=1 to enable it."
+ }
+ $element.SetFocus()
+ return
+ }
+ }
+ throw "$action is not a valid secondary action for $($operation.element.index)"
+}
+
+function Invoke-Scroll($element, [string]$direction, [double]$pages) {
+ $scroll = Get-CurrentPatternOrNull $element ([Windows.Automation.ScrollPattern]::Pattern)
+ if ($null -eq $scroll) {
+ return $false
+ }
+ $horizontal = [Windows.Automation.ScrollAmount]::NoAmount
+ $vertical = [Windows.Automation.ScrollAmount]::NoAmount
+ if ($direction -eq "up") { $vertical = [Windows.Automation.ScrollAmount]::LargeDecrement }
+ elseif ($direction -eq "down") { $vertical = [Windows.Automation.ScrollAmount]::LargeIncrement }
+ elseif ($direction -eq "left") { $horizontal = [Windows.Automation.ScrollAmount]::LargeDecrement }
+ elseif ($direction -eq "right") { $horizontal = [Windows.Automation.ScrollAmount]::LargeIncrement }
+ $repeat = [math]::Max(1, [int][math]::Ceiling($pages))
+ for ($i = 0; $i -lt $repeat; $i++) {
+ $scroll.Scroll($horizontal, $vertical)
+ Start-Sleep -Milliseconds 40
+ }
+ return $true
+}
+
+function Find-TextEntryElement($process) {
+ try {
+ $focused = [Windows.Automation.AutomationElement]::FocusedElement
+ if ($null -ne $focused -and $focused.Current.ProcessId -eq $process.Id) {
+ $focusedValue = Get-CurrentPatternOrNull $focused ([Windows.Automation.ValuePattern]::Pattern)
+ if ($null -ne $focusedValue -and -not $focusedValue.Current.IsReadOnly) {
+ return $focused
+ }
+ }
+ } catch {
+ }
+
+ $root = Get-MainElement $process
+ foreach ($element in (Get-AllElements $root)) {
+ $valuePattern = Get-CurrentPatternOrNull $element ([Windows.Automation.ValuePattern]::Pattern)
+ if ($null -eq $valuePattern -or $valuePattern.Current.IsReadOnly) {
+ continue
+ }
+ $controlType = Get-ElementControlTypeName $element
+ if ($controlType -like "*Edit*" -or $controlType -like "*Document*") {
+ return $element
+ }
+ }
+
+ foreach ($element in (Get-AllElements $root)) {
+ $valuePattern = Get-CurrentPatternOrNull $element ([Windows.Automation.ValuePattern]::Pattern)
+ if ($null -ne $valuePattern -and -not $valuePattern.Current.IsReadOnly) {
+ return $element
+ }
+ }
+
+ return $null
+}
+
+function Get-NativeWindowHandle($element) {
+ $handle = Get-ElementInt64 $element "NativeWindowHandle"
+ if ($handle -le 0) {
+ return [IntPtr]::Zero
+ }
+ return [IntPtr]$handle
+}
+
+function Test-TextWindowHandleCandidate($process, $element) {
+ if ($null -eq $element) {
+ return $false
+ }
+ $handle = Get-NativeWindowHandle $element
+ if ($handle -eq [IntPtr]::Zero -or $handle -eq [IntPtr]$process.MainWindowHandle) {
+ return $false
+ }
+ $controlType = Get-ElementControlTypeName $element
+ $className = Get-ElementString $element "ClassName"
+ return (
+ $controlType -like "*Edit*" -or
+ $controlType -like "*Document*" -or
+ $className -like "*Edit*" -or
+ $className -like "*Rich*" -or
+ $className -like "*Text*"
+ )
+}
+
+function Find-TextEntryWindowHandle($process, $preferredElement) {
+ if (Test-TextWindowHandleCandidate $process $preferredElement) {
+ return Get-NativeWindowHandle $preferredElement
+ }
+
+ $root = Get-MainElement $process
+ foreach ($element in (Get-AllElements $root)) {
+ if (-not (Test-TextWindowHandleCandidate $process $element)) {
+ continue
+ }
+ $valuePattern = Get-CurrentPatternOrNull $element ([Windows.Automation.ValuePattern]::Pattern)
+ if ($null -ne $valuePattern -and -not $valuePattern.Current.IsReadOnly) {
+ return Get-NativeWindowHandle $element
+ }
+ }
+
+ foreach ($element in (Get-AllElements $root)) {
+ if (Test-TextWindowHandleCandidate $process $element) {
+ return Get-NativeWindowHandle $element
+ }
+ }
+
+ return [IntPtr]::Zero
+}
+
+function Invoke-TypeText($process, [string]$text) {
+ $element = Find-TextEntryElement $process
+ $targetHwnd = Find-TextEntryWindowHandle $process $element
+ if ($targetHwnd -ne [IntPtr]::Zero -and (Send-TextToEditHandle $targetHwnd $text $element)) {
+ return $true
+ }
+
+ if ($null -ne $element) {
+ $valuePattern = Get-CurrentPatternOrNull $element ([Windows.Automation.ValuePattern]::Pattern)
+ if ($null -ne $valuePattern -and -not $valuePattern.Current.IsReadOnly) {
+ if (-not (Test-EnvFlagEnabled "OPEN_COMPUTER_USE_WINDOWS_ALLOW_UIA_TEXT_FALLBACK")) {
+ throw "UIA ValuePattern text fallback is disabled by default because it may bring the target app to the foreground; set OPEN_COMPUTER_USE_WINDOWS_ALLOW_UIA_TEXT_FALLBACK=1 to enable it."
+ }
+ $current = ""
+ try { $current = [string]$valuePattern.Current.Value } catch {}
+ $valuePattern.SetValue($current + $text)
+ return $true
+ }
+ }
+ return $false
+}
+
+$operation = Get-Content -Raw -Path $OperationPath | ConvertFrom-Json
+
+try {
+ if ($operation.tool -eq "list_apps") {
+ $response = [pscustomobject]@{ ok = $true; text = (List-Apps) }
+ } elseif ($operation.tool -eq "get_app_state") {
+ $response = [pscustomobject]@{ ok = $true; snapshot = (Build-Snapshot $operation.app) }
+ } else {
+ $process = Resolve-App $operation.app
+ $hwnd = [IntPtr]$process.MainWindowHandle
+ $windowBounds = $operation.windowBounds
+ $element = Find-Element $process $operation.element
+
+ switch ($operation.tool) {
+ "click" {
+ $handled = $false
+ if ($null -ne $element -and $operation.mouse_button -ne "right" -and $operation.mouse_button -ne "middle") {
+ $handled = Invoke-PreferredClick $element
+ }
+ if (-not $handled) {
+ if ($null -ne $operation.element -and $null -ne $operation.element.frame) {
+ $point = Get-ScreenPoint $operation.element.frame $windowBounds
+ } else {
+ $point = [pscustomobject]@{
+ x = [int][math]::Round($windowBounds.x + [double]$operation.x)
+ y = [int][math]::Round($windowBounds.y + [double]$operation.y)
+ }
+ }
+ Send-MouseClick $hwnd $point.x $point.y $operation.mouse_button ([int]$operation.click_count)
+ }
+ }
+ "perform_secondary_action" {
+ if ($null -eq $element) { throw "unknown element_index '$($operation.element.index)'" }
+ Invoke-SecondaryAction $element $operation.action
+ }
+ "scroll" {
+ $handled = $false
+ if ($null -ne $element) {
+ $handled = Invoke-Scroll $element $operation.direction ([double]$operation.pages)
+ }
+ if (-not $handled) {
+ $point = Get-ScreenPoint $operation.element.frame $windowBounds
+ Send-Scroll $hwnd $point.x $point.y $operation.direction ([double]$operation.pages)
+ }
+ }
+ "drag" {
+ Send-Drag $hwnd ([int][math]::Round($windowBounds.x + [double]$operation.from_x)) ([int][math]::Round($windowBounds.y + [double]$operation.from_y)) ([int][math]::Round($windowBounds.x + [double]$operation.to_x)) ([int][math]::Round($windowBounds.y + [double]$operation.to_y))
+ }
+ "type_text" {
+ if (-not (Invoke-TypeText $process $operation.text)) {
+ Send-Text $hwnd $operation.text
+ }
+ }
+ "press_key" {
+ Send-Key $hwnd $operation.key
+ }
+ "set_value" {
+ if ($null -eq $element) { throw "unknown element_index '$($operation.element.index)'" }
+ $valuePattern = Get-CurrentPatternOrNull $element ([Windows.Automation.ValuePattern]::Pattern)
+ if ($null -eq $valuePattern) {
+ throw "Cannot set a value for an element that is not settable"
+ }
+ $valuePattern.SetValue($operation.value)
+ }
+ default {
+ throw "unsupportedTool(`"$($operation.tool)`")"
+ }
+ }
+
+ Start-Sleep -Milliseconds 120
+ $response = [pscustomobject]@{ ok = $true; snapshot = (Build-Snapshot $operation.app) }
+ }
+} catch {
+ $message = $_.Exception.Message
+ if (-not [string]::IsNullOrWhiteSpace($_.ScriptStackTrace)) {
+ $message = "$message at $($_.ScriptStackTrace)"
+ }
+ $response = [pscustomobject]@{ ok = $false; error = $message }
+}
+
+$response | ConvertTo-Json -Depth 50 -Compress
diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md
index afccf8c..35df995 100644
--- a/docs/ARCHITECTURE.md
+++ b/docs/ARCHITECTURE.md
@@ -1,6 +1,6 @@
# 架构总览
-这个仓库当前已经从模板收敛成一个 Swift 实现的本地 `computer-use` 项目,目标是在开源前提下提供一版可运行、可验证、可继续演进的 macOS automation MCP server。
+这个仓库当前已经从模板收敛成一个本地 `computer-use` 项目。主线仍是 Swift 实现的 macOS automation MCP server,同时新增了实验性的 Windows runtime,用独立 Go `.exe` 暴露同一组 9 个 Computer Use tools。
## 当前目录结构
@@ -10,6 +10,8 @@
本地 GUI fixture app,用来承载低风险、可预测的点击/输入/滚动/拖拽验证路径。
- `apps/OpenComputerUseSmokeSuite`
端到端 smoke runner,会拉起 fixture 和 MCP server,并通过 JSON-RPC 真实调用 9 个 tools。
+- `apps/OpenComputerUseWindows`
+ 实验性 Windows runtime。它不依赖 Swift 或 `.app` bundle,Go CLI/MCP 入口会嵌入 PowerShell UI Automation bridge,构建产物是 `open-computer-use.exe`。
- `packages/OpenComputerUseKit`
核心库,包含:
- MCP stdio transport 与 tool registry
@@ -23,7 +25,7 @@
- `experiments/StandaloneCursor`
新的独立 Swift cursor viewer,直接复用 `scripts/cursor-motion-re/official_cursor_motion.py` 里收敛出来的候选路径、score 与 raw spring timeline,用来观察更贴近 binary lift 的表现。
- `scripts/`
- 仓库级自动化命令,包括 smoke test、`.app` 打包入口、npm 分发脚本,以及 `scripts/computer-use-cli/` 这个用于探测官方 bundled `computer-use` 的 Go helper。
+ 仓库级自动化命令,包括 smoke test、`.app` 打包入口、Windows `.exe` 构建入口、npm 分发脚本,以及 `scripts/computer-use-cli/` 这个用于探测官方 bundled `computer-use` 的 Go helper。
- `docs/`
逆向分析、执行计划、history 和项目约束。
@@ -94,6 +96,16 @@
- lab 的 cursor 视觉继续以 `scripts/render-synthesized-software-cursor.swift` 为参考:优先使用仓库里保存的官方 `252x252` runtime baseline 图,缺失时再退回脚本里的 procedural pointer/fog 近似;settle 态也改成中心固定的小幅摆角,而不是继续沿 XY 轻微漂移。
- 当前它不接真实 tool call,也不回写主 `SoftwareCursorOverlay`,目的是把实验噪音与产品行为边界隔离开。
+### 6. Windows Runtime
+
+- Windows runtime 位于 `apps/OpenComputerUseWindows`,以 Go 维护 CLI、`call --calls` sequence、MCP JSON-RPC、tool schema 和进程内 snapshot cache。
+- 构建入口是 `scripts/build-open-computer-use-windows.sh --arch arm64|amd64`,默认输出到 `dist/windows/<arch>/open-computer-use.exe`;当前 npm 包仍只发布 macOS app bundle,Windows 分发还没有接入 release package。
+- Go runtime 通过 `go:embed` 带上 `runtime.ps1`,执行 tool call 时临时落盘并调用 Windows PowerShell。PowerShell bridge 使用 `System.Windows.Automation` 做 app/window/element discovery、tree rendering、UIA pattern action、ValuePattern set value 和 ScrollPattern scroll;当目标 app 不暴露对应 pattern 时,fallback 到 `PostMessage` / `SendMessage` 形式的 Win32 window message。
+- Windows runtime 默认只连接已经运行的 app,不会在 `get_app_state` 找不到进程时自动 `Start-Process`,也不会默认允许 `SetFocus` secondary action;这两条前台抢占路径分别需要 `OPEN_COMPUTER_USE_WINDOWS_ALLOW_APP_LAUNCH=1` 和 `OPEN_COMPUTER_USE_WINDOWS_ALLOW_FOCUS_ACTIONS=1` 显式打开。`type_text` 默认优先对可写文本控件的 child HWND 发送 `EM_SETSEL` / `EM_REPLACESEL`,不再默认走可能触发前台激活的 UIA `ValuePattern.SetValue` fallback;需要旧行为时必须设置 `OPEN_COMPUTER_USE_WINDOWS_ALLOW_UIA_TEXT_FALLBACK=1`。UIA pattern 和 Win32 message fallback 本身仍是 best-effort:很多控件可以在后台响应,但 Windows 没有一套对所有 GUI toolkit 都等价于 macOS AX 的后台键鼠输入模型。
+- 这 9 个 tool 的协议面与 macOS 主线保持一致:`list_apps`、`get_app_state`、`click`、`perform_secondary_action`、`scroll`、`drag`、`type_text`、`press_key`、`set_value`。其中 element-targeted action 会优先复用上一轮 `get_app_state` 的 runtime id / automation metadata,coordinate action 使用 screenshot/window-relative 坐标。
+- Windows UI Automation 需要运行在已登录用户的桌面 session 里。通过 SSH 作为脱离桌面的后台进程运行时,PowerShell 可以启动并返回 JSON,但系统可能不给它暴露顶层窗口;这种情况下 `list_apps` 会是空,`get_app_state` 可能返回 `appNotFound(...)`。
+- 当前 Windows 侧仍是功能性第一版:没有 visual cursor overlay、没有 installer/onboarding、没有 code signing,也没有独立的 Windows smoke fixture。后续 TODO 记录在 `docs/exec-plans/active/20260422-windows-computer-use-runtime.md`。
+
## 关键边界
- 开源版当前不复刻官方闭源实现里的 caller signing、私有 IPC、完整 overlay choreography 和 plugin 自安装逻辑。
@@ -111,6 +123,8 @@
- app 打包:`./scripts/build-open-computer-use-app.sh debug`
- npm staging:`node ./scripts/npm/build-packages.mjs`
- release tgz:`./scripts/release-package.sh`
+- Windows runtime 单测:`(cd apps/OpenComputerUseWindows && go test ./...)`
+- Windows exe 构建:`./scripts/build-open-computer-use-windows.sh --arch arm64`
- 对比样本:`artifacts/tool-comparisons/20260417-focus-behavior/`
- 手工诊断:
- `.build/debug/OpenComputerUse doctor`
diff --git a/docs/QUALITY_SCORE.md b/docs/QUALITY_SCORE.md
index 7b7a1c0..150ae6b 100644
--- a/docs/QUALITY_SCORE.md
+++ b/docs/QUALITY_SCORE.md
@@ -12,6 +12,7 @@
| 区域 | 评分 | 原因 | 下一步 |
| --- | --- | --- | --- |
| 产品面 | B | 已经有 Swift 本地 `computer-use` MCP server、默认 app 模式权限引导,以及一轮按官方 surface / result 行为收敛过的 9 个 tools。 | 继续收敛复杂 AX 场景下的 state rendering 细节、权限 UI 和更清晰的用户错误提示。 |
+| Windows runtime | C | 已新增独立 Go `.exe`,通过 Windows UI Automation + Win32 window message 暴露同样 9 个 tools、MCP server 和 `call --calls`;默认不再自动启动 app、执行 `SetFocus`,或让 `type_text` 走可能抢前台的 UIA text fallback,但仍是功能性第一版。 | 补交互式桌面 smoke、Windows fixture、installer/signing/release 分发,以及更原生的 Go UIA 实现或更稳定的 bridge。 |
| 架构文档 | B | 顶层结构、fixture bridge、app 模式和验证路径已经落文档。 | 后续补 release artifact、code signing / notarization 和 host 集成方式。 |
| 测试 | B | `swift test` + smoke suite 已覆盖 9 个 tools 的回归,并新增了针对“前台焦点是否被抢占”的手工对比样本沉淀。 | 增加更多普通 app 的录制回归,减少只依赖 fixture 和一次性手工检查。 |
| 可观测性 | C | 已有 `doctor`、`snapshot`、smoke 输出,以及一组仓库内留档的官方 `computer-use` / 本仓库实现对比样本。 | 补统一日志级别、失败上下文和 release artifact 里的诊断信息,把一次性样本收敛成可重复采集流程。 |
diff --git a/docs/exec-plans/active/20260422-windows-computer-use-runtime.md b/docs/exec-plans/active/20260422-windows-computer-use-runtime.md
new file mode 100644
index 0000000..c3a4916
--- /dev/null
+++ b/docs/exec-plans/active/20260422-windows-computer-use-runtime.md
@@ -0,0 +1,97 @@
+# Windows Computer Use Runtime
+
+## 目标
+
+把当前只覆盖 macOS Accessibility 的 `open-computer-use` 扩展到 Windows,优先让同一组 9 个 Computer Use tools 能通过独立 `.exe` 跑起来,并保留后续补强路径。
+
+## 范围
+
+- 包含:
+ - Windows 独立 runtime,不耦合 Swift `.app`。
+ - Go CLI / MCP / `call --calls` 入口。
+ - `list_apps`、`get_app_state`、`click`、`perform_secondary_action`、`scroll`、`drag`、`type_text`、`press_key`、`set_value` 的功能性实现。
+ - Windows `.exe` 构建脚本和基础 Go 单测。
+ - 架构文档、README 和 history。
+- 不包含:
+ - 替换 macOS Swift 主线。
+ - Windows installer、code signing、npm release artifact。
+ - visual cursor overlay。
+ - 完整 Windows fixture / smoke suite。
+
+## 背景
+
+- 相关文档:
+ - `docs/ARCHITECTURE.md`
+ - `docs/QUALITY_SCORE.md`
+ - `docs/exec-plans/active/20260422-remaining-tool-official-alignment.md`
+- 相关代码路径:
+ - `apps/OpenComputerUseWindows/`
+ - `scripts/build-open-computer-use-windows.sh`
+ - `packages/OpenComputerUseKit/Sources/OpenComputerUseKit/ToolDefinitions.swift`
+ - `packages/OpenComputerUseKit/Sources/OpenComputerUseKit/ComputerUseToolDispatcher.swift`
+- 已知约束:
+ - Windows UI Automation 需要 runtime 运行在已登录桌面 session;脱离桌面的 SSH/service 进程可能看不到顶层窗口。
+ - 第一版以 Go 生成 `.exe` 为交付边界,但 UIA 操作通过嵌入式 PowerShell bridge 调 Windows 内置 .NET UI Automation API。
+ - Win32 window message fallback 能减少真实鼠标抢占,但不同 GUI toolkit 对后台消息支持不一致。
+ - Windows 没有一套对任意 app 都等价于 macOS AX 的后台键鼠模型;当前策略是 UIA pattern 优先、window message best-effort,并把启动 app / `SetFocus` / UIA text fallback 这类前台抢占路径做成显式 opt-in。
+
+## 风险
+
+- 风险:PowerShell bridge 比纯 Go UIA 慢,也更依赖 Windows PowerShell 5.1 / .NET Framework 可用性。
+ - 缓解方式:Go runtime 先把协议面、状态复用和构建产物稳定下来;后续可把 bridge 内部逐步替换成原生 Go COM/UIA。
+- 风险:SSH 验证进程不在交互式桌面上下文里,导致误判 `list_apps` / `get_app_state`。
+ - 缓解方式:把 SSH 仅作为 exe 启动、JSON/MCP、错误路径验证;真实 UI 操作补交互式桌面 smoke。
+- 风险:窗口消息 fallback 对 Electron、WinUI、UWP、浏览器等复杂 app 的行为差异较大。
+ - 缓解方式:UIA pattern 优先,fallback 行为明确记录;后续加 Windows fixture 和真实 app 样本。
+
+## 里程碑
+
+1. 完成 Windows Go runtime 骨架和 9-tool 功能性实现。
+2. 完成 `.exe` 构建脚本、Go 单测、MCP/tools list 和 SSH 基础验证。
+3. 补交互式桌面 smoke、Windows fixture、release packaging 和更原生 UIA 实现。
+
+## 验证方式
+
+- 命令:
+ - `(cd apps/OpenComputerUseWindows && go test ./...)`
+ - `./scripts/build-open-computer-use-windows.sh --arch arm64`
+ - `open-computer-use.exe --version`
+ - `open-computer-use.exe call list_apps`
+ - `open-computer-use.exe mcp`
+- 手工检查:
+ - 在已登录 Windows 桌面里打开 Notepad,运行 `get_app_state -> set_value/type_text/press_key/click` sequence。
+ - 确认 action 后返回最新 state text 和截图。
+- 观测检查:
+ - 确认 SSH/service 环境下的空窗口列表被明确呈现,不把它误写成 UIA 逻辑失败。
+
+## 进度记录
+
+- [x] 新增 `apps/OpenComputerUseWindows`,用 Go 实现 CLI、MCP、tool schema、`call --calls` 和 snapshot cache。
+- [x] 嵌入 Windows PowerShell UIA bridge,实现 9 个 tools 的功能性路径。
+- [x] 新增 Windows arm64/amd64 `.exe` 构建脚本。
+- [x] 新增 Go 单测,并接入仓库基础 CI。
+- [x] 通过 SSH 到 Windows 验证 `.exe --version`、`call list_apps` 和 MCP initialize/tools list。
+- [x] 通过 Windows Codex App session history 定位首轮真实 MCP 测试问题:`list_apps` 正常,`get_app_state` 对 `Notepad` 返回 `Argument types do not match`,对 `notepad.exe` 返回 `appNotFound(...)`。
+- [x] 修正 Windows app 匹配和 UIA tree rendering 容错,避免单个控件属性异常导致整个 `get_app_state` 失败。
+- [x] 通过交互式 Windows scheduled task 复现并验证 `get_app_state -> type_text -> get_app_state`,确认 Notepad 文本区能写入 `hello windows mcp`,并在后续 snapshot 中显示 ValuePattern 值。
+- [x] 收紧 Windows 后台运行默认策略:找不到 app 时不再自动启动,`SetFocus` 默认禁用,只能通过环境变量显式开启。
+- [x] 将 `type_text` 默认路径从 UIA `ValuePattern.SetValue` 改为 child HWND `EM_SETSEL` / `EM_REPLACESEL` 优先;可能把 app 带到前台的 UIA text fallback 改成环境变量显式开启。
+- [x] 通过交互式 Windows scheduled task 验证新 `type_text` 路径:`get_app_state -> type_text -> get_app_state` 三步均 `isError=false`,Notepad 文本包含 `bgmsg-*` marker,前台窗口调用前后均为 Codex。
+- [ ] 在交互式 Windows 桌面 session 补 Notepad / Edge 等真实 UI action smoke。
+- [ ] 增加 Windows fixture 和可重复 smoke runner。
+- [ ] 评估用 `PrintWindow` / Windows Graphics Capture 补一条不依赖窗口可见性的 background screenshot 路径。
+- [ ] 为必须依赖前台输入的 app/toolkit 场景补更明确的 capability/error,避免静默退到抢焦点行为。
+- [ ] 将 Windows artifact 接入 release packaging,并补 signing / installer 方案。
+- [ ] 评估把 PowerShell bridge 替换为原生 Go COM/UIA 的收益和风险。
+
+## 决策记录
+
+- 2026-04-22:Windows runtime 不复用 Swift `.app`,采用独立 Go `.exe`,避免把 macOS 权限/onboarding 模型强行带到 Windows。
+- 2026-04-22:第一版用 Go 管协议、状态和分发边界,用嵌入式 PowerShell 调 Windows UI Automation / Win32 API,优先完成 9-tool 功能性闭环。
+- 2026-04-22:保留 `call --calls` 的同进程状态复用语义,Windows action tool 优先消费上一轮 `get_app_state` 的 `element_index` metadata。
+- 2026-04-22:真实 Codex App 测试显示 `list_apps` 可用,但 `get_app_state` 仍会被 UIA 属性读取异常拖垮;Windows snapshot renderer 改成字段级安全读取,并支持 `notepad.exe` 这类进程名输入。
+- 2026-04-22:PowerShell 对 .NET generic list 的 `@(...)` 包装会在返回对象时触发 `Argument types do not match`;Windows bridge 统一改成 `.ToArray()` 返回 UIA records/element collections。
+- 2026-04-22:`type_text` 不再只给顶层窗口发 `WM_CHAR`;优先寻找同进程可写 `ValuePattern` 文本元素并追加文本,找不到再走 window-message fallback。
+- 2026-04-22:为避免 Windows tools 主动抢占用户焦点,`Resolve-App` 默认不再 `Start-Process` 目标 app,`SetFocus` secondary action 默认返回错误;需要前台行为时分别设置 `OPEN_COMPUTER_USE_WINDOWS_ALLOW_APP_LAUNCH=1` 或 `OPEN_COMPUTER_USE_WINDOWS_ALLOW_FOCUS_ACTIONS=1`。
+- 2026-04-22:Notepad 实测反馈 `type_text` 的 UIA `ValuePattern.SetValue` 会把窗口带到前台;默认改为 child HWND `EM_REPLACESEL` 后台消息路径,旧 UIA fallback 需要 `OPEN_COMPUTER_USE_WINDOWS_ALLOW_UIA_TEXT_FALLBACK=1`。
+- 2026-04-22:Windows 交互式 scheduled task 验证显示新 `type_text` 能写入 Notepad 且不会把前台从 Codex 切到 Notepad;Notepad 文本控件 UIA class 为 `RichEditD2DPT`,有 child native handle,可接收 `EM_REPLACESEL`。
diff --git a/docs/histories/2026-04/20260422-1246-add-windows-computer-use-runtime.md b/docs/histories/2026-04/20260422-1246-add-windows-computer-use-runtime.md
new file mode 100644
index 0000000..df17151
--- /dev/null
+++ b/docs/histories/2026-04/20260422-1246-add-windows-computer-use-runtime.md
@@ -0,0 +1,41 @@
+## [2026-04-22 12:46] | Task: Add Windows Computer Use Runtime
+
+### 🤖 Execution Context
+* **Agent ID**: `Codex`
+* **Base Model**: `GPT-5`
+* **Runtime**: `Codex CLI`
+
+### 📥 User Query
+> Extend the project beyond macOS Accessibility to Windows, avoid coupling to Swift `.app`, consider Go-generated `.exe`, and prioritize functional implementation of the 9 Computer Use tools for background computer use. Use the UTM Windows host over SSH for testing where practical, and leave TODOs if the full scope is too large.
+
+### 🛠 Changes Overview
+**Scope:** Windows runtime, build scripts, CI, docs
+
+**Key Actions:**
+- **[Runtime]**: Added `apps/OpenComputerUseWindows`, a Go CLI/MCP runtime exposing the same 9 Computer Use tools, `call --calls`, MCP initialize/tools list, and per-process snapshot cache.
+- **[Bridge]**: Embedded a Windows PowerShell UI Automation bridge for app/window discovery, accessibility tree snapshots, screenshots, UIA pattern actions, ValuePattern, ScrollPattern, and Win32 window-message fallback input.
+- **[Build/CI]**: Added `scripts/build-open-computer-use-windows.sh` for arm64/amd64 `.exe` builds and wired Go tests into `scripts/ci.sh`.
+- **[Docs]**: Updated README, architecture, quality score, and added an active Windows runtime execution plan with the remaining TODOs.
+- **[Follow-up Fix]**: Used Windows Codex App session history to identify `get_app_state` failures after `list_apps` succeeded, then hardened process matching and UIA tree rendering against `Argument types do not match`.
+- **[Interactive Validation]**: Verified through an interactive Windows scheduled task that `get_app_state -> type_text -> get_app_state` writes `hello windows mcp` into Notepad and returns the updated UIA value.
+- **[Background Policy]**: Removed the default app-launch fallback and disabled `SetFocus` by default so Windows tools do not intentionally steal foreground focus; both behaviors remain available through explicit environment variables.
+- **[Type Text Focus Fix]**: Changed `type_text` to prefer child-window `EM_SETSEL` / `EM_REPLACESEL` messages and made the UIA `ValuePattern.SetValue` text fallback opt-in because Notepad can foreground itself from that UIA path.
+- **[Focus Validation]**: Re-ran an interactive Windows scheduled task against Notepad; `get_app_state -> type_text -> get_app_state` returned three non-error results, wrote a `bgmsg-*` marker, and left the foreground window title as `Codex` before and after the call.
+
+### 🧠 Design Intent (Why)
+Windows should have its own executable boundary instead of inheriting macOS `.app` and Swift/AppKit assumptions. The first slice keeps the public tool protocol stable and makes the runtime buildable/testable as a `.exe`; the bridge can be replaced with more native Go UIA internals later without changing MCP or CLI callers.
+
+Windows UI Automation can often operate on background windows through control patterns such as `ValuePattern`, `InvokePattern`, and `ScrollPattern`, but Windows does not provide one universal macOS-AX-equivalent background keyboard/mouse model for every GUI toolkit. The runtime therefore avoids the known foreground-taking paths by default and treats launch, focus, and UIA text fallback as explicit opt-in behavior.
+
+### 📁 Files Modified
+- `apps/OpenComputerUseWindows/go.mod`
+- `apps/OpenComputerUseWindows/main.go`
+- `apps/OpenComputerUseWindows/main_test.go`
+- `apps/OpenComputerUseWindows/runtime.ps1`
+- `scripts/build-open-computer-use-windows.sh`
+- `scripts/ci.sh`
+- `README.md`
+- `README.zh-CN.md`
+- `docs/ARCHITECTURE.md`
+- `docs/QUALITY_SCORE.md`
+- `docs/exec-plans/active/20260422-windows-computer-use-runtime.md`
diff --git a/scripts/build-open-computer-use-windows.sh b/scripts/build-open-computer-use-windows.sh
new file mode 100755
index 0000000..479df0b
--- /dev/null
+++ b/scripts/build-open-computer-use-windows.sh
@@ -0,0 +1,71 @@
+#!/usr/bin/env bash
+
+set -euo pipefail
+
+repo_root="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
+arch="arm64"
+configuration="release"
+out_dir="${repo_root}/dist/windows"
+
+print_help() {
+ cat <<'EOF'
+Usage:
+ scripts/build-open-computer-use-windows.sh [options]
+
+Options:
+ --arch arm64|amd64 Windows target architecture. Defaults to arm64.
+ --configuration release Reserved for parity with the macOS build script.
+ --out-dir <dir> Output directory. Defaults to dist/windows.
+ -h, --help Show help.
+EOF
+}
+
+while [[ $# -gt 0 ]]; do
+ case "$1" in
+ --arch)
+ arch="${2:?--arch requires a value}"
+ shift 2
+ ;;
+ --configuration)
+ configuration="${2:?--configuration requires a value}"
+ shift 2
+ ;;
+ --out-dir)
+ out_dir="$(cd "${repo_root}" && mkdir -p "$2" && cd "$2" && pwd)"
+ shift 2
+ ;;
+ -h|--help)
+ print_help
+ exit 0
+ ;;
+ *)
+ echo "Unknown argument: $1" >&2
+ print_help >&2
+ exit 1
+ ;;
+ esac
+done
+
+case "${arch}" in
+ arm64|amd64) ;;
+ *)
+ echo "Unsupported Windows arch: ${arch}" >&2
+ exit 1
+ ;;
+esac
+
+version="$(node -e "console.log(require('./plugins/open-computer-use/.codex-plugin/plugin.json').version)")"
+module_dir="${repo_root}/apps/OpenComputerUseWindows"
+output_dir="${out_dir}/${arch}"
+mkdir -p "${output_dir}"
+
+(
+ cd "${module_dir}"
+ GOOS=windows GOARCH="${arch}" CGO_ENABLED=0 go build \
+ -trimpath \
+ -ldflags "-s -w -X main.version=${version}" \
+ -o "${output_dir}/open-computer-use.exe" \
+ .
+)
+
+echo "Built ${configuration} Windows runtime: ${output_dir}/open-computer-use.exe"
diff --git a/scripts/ci.sh b/scripts/ci.sh
index ae9885e..63392c0 100755
--- a/scripts/ci.sh
+++ b/scripts/ci.sh
@@ -16,4 +16,11 @@ while IFS= read -r file; do
node --check "$file"
done < <(find "${repo_root}/scripts" -type f -name '*.mjs' | sort)
+if command -v go >/dev/null 2>&1; then
+ (
+ cd "${repo_root}/apps/OpenComputerUseWindows"
+ go test ./...
+ )
+fi
+
echo "基础 CI 检查通过"