ok-use 0.1.0__tar.gz
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- ok_use-0.1.0/PKG-INFO +199 -0
- ok_use-0.1.0/README.md +177 -0
- ok_use-0.1.0/ok_use/__init__.py +2 -0
- ok_use-0.1.0/ok_use/__main__.py +5 -0
- ok_use-0.1.0/ok_use/advisor.py +112 -0
- ok_use-0.1.0/ok_use/bridge.py +156 -0
- ok_use-0.1.0/ok_use/browser.py +369 -0
- ok_use-0.1.0/ok_use/control.py +716 -0
- ok_use-0.1.0/ok_use/http.py +44 -0
- ok_use-0.1.0/ok_use/install.py +263 -0
- ok_use-0.1.0/ok_use/server.py +643 -0
- ok_use-0.1.0/ok_use/settings.py +20 -0
- ok_use-0.1.0/ok_use/task.py +110 -0
- ok_use-0.1.0/ok_use/uia.py +432 -0
- ok_use-0.1.0/ok_use/win32.py +715 -0
- ok_use-0.1.0/ok_use.egg-info/PKG-INFO +199 -0
- ok_use-0.1.0/ok_use.egg-info/SOURCES.txt +21 -0
- ok_use-0.1.0/ok_use.egg-info/dependency_links.txt +1 -0
- ok_use-0.1.0/ok_use.egg-info/entry_points.txt +2 -0
- ok_use-0.1.0/ok_use.egg-info/requires.txt +8 -0
- ok_use-0.1.0/ok_use.egg-info/top_level.txt +1 -0
- ok_use-0.1.0/pyproject.toml +28 -0
- ok_use-0.1.0/setup.cfg +4 -0
ok_use-0.1.0/PKG-INFO
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: ok-use
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Computer-use style MCP server for the Windows desktop: background window control and admin-level operation
|
|
5
|
+
Project-URL: Homepage, https://github.com/ok-oldking/ok-use
|
|
6
|
+
Project-URL: Repository, https://github.com/ok-oldking/ok-use
|
|
7
|
+
Keywords: mcp,computer-use,windows,automation,ui-automation,agent
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: Operating System :: Microsoft :: Windows
|
|
10
|
+
Classifier: Topic :: Desktop Environment
|
|
11
|
+
Classifier: Topic :: Software Development :: Testing
|
|
12
|
+
Requires-Python: >=3.11
|
|
13
|
+
Description-Content-Type: text/markdown
|
|
14
|
+
Requires-Dist: mcp>=2.3
|
|
15
|
+
Requires-Dist: uvicorn
|
|
16
|
+
Requires-Dist: starlette
|
|
17
|
+
Requires-Dist: psutil
|
|
18
|
+
Requires-Dist: pillow>=10
|
|
19
|
+
Requires-Dist: pywin32
|
|
20
|
+
Requires-Dist: playwright>=1.50
|
|
21
|
+
Requires-Dist: comtypes>=1.4
|
|
22
|
+
|
|
23
|
+
# ok-use
|
|
24
|
+
|
|
25
|
+
An MCP server that gives a coding agent (Claude Code, Codex, …) computer use on Windows. It replaces
|
|
26
|
+
the built-in computer-use tool with one that works on **any app**, without per-app permission tiers.
|
|
27
|
+
The workflow is the same (screenshot → act → screenshot), and it adds per-window **background** control
|
|
28
|
+
(the user keeps their mouse and keyboard) and an **elevated (admin)** mode.
|
|
29
|
+
|
|
30
|
+
## Install (instructions for coding agents)
|
|
31
|
+
|
|
32
|
+
If a user asks you to install this repository, run these two commands in PowerShell, then tell the
|
|
33
|
+
user to restart the agent (or start a new session):
|
|
34
|
+
|
|
35
|
+
```powershell
|
|
36
|
+
uv tool install --force git+https://github.com/ok-oldking/ok-use
|
|
37
|
+
```
|
|
38
|
+
|
|
39
|
+
```powershell
|
|
40
|
+
ok-use setup
|
|
41
|
+
```
|
|
42
|
+
|
|
43
|
+
`ok-use setup` opens **one UAC prompt**. Tell the user to approve it; you can't click it yourself.
|
|
44
|
+
If `uv` is missing, install it first with
|
|
45
|
+
`powershell -ExecutionPolicy Bypass -c "irm https://astral.sh/uv/install.ps1 | iex"`. If `ok-use` is not
|
|
46
|
+
found right after installing, run it as `& "$env:USERPROFILE\.local\bin\ok-use.exe" setup`.
|
|
47
|
+
|
|
48
|
+
What setup does:
|
|
49
|
+
|
|
50
|
+
1. Registers the scheduled task `OK Use MCP`, which can start the server as administrator later
|
|
51
|
+
without another UAC prompt. This is the step that needs the UAC approval.
|
|
52
|
+
2. Adds the `ok-use` stdio server to Claude Code (`~/.claude.json`, user scope) and to Codex
|
|
53
|
+
(`~/.codex/config.toml`), for each one it finds.
|
|
54
|
+
3. Denies Claude Code's built-in computer use (`mcp__computer-use` in `~/.claude/settings.json`), so the
|
|
55
|
+
agent uses ok-use in its place.
|
|
56
|
+
|
|
57
|
+
After that, the agent starts `ok-use` on demand like any stdio MCP server. The stdio process is a small
|
|
58
|
+
bridge: it starts the elevated server through the task, relays the agent's messages to it over
|
|
59
|
+
loopback HTTP with a bearer token, and starts it again if it has exited. The elevated server exits
|
|
60
|
+
after 30 minutes without requests.
|
|
61
|
+
|
|
62
|
+
| Command | |
|
|
63
|
+
| --- | --- |
|
|
64
|
+
| `ok-use status` | what is installed and running |
|
|
65
|
+
| `ok-use setup --no-admin` | skip the task (no UAC prompt): ok-use runs with the agent's own privileges |
|
|
66
|
+
| `ok-use setup --agent claude` | configure only this agent (`claude`, `codex`; repeatable) |
|
|
67
|
+
| `ok-use setup --keep-builtin` | leave the built-in computer use enabled |
|
|
68
|
+
| `ok-use setup --at-logon` | also start the elevated server at every logon |
|
|
69
|
+
| `ok-use uninstall` | remove the task and the agent config, then run `uv tool uninstall ok-use` |
|
|
70
|
+
| `uv tool upgrade ok-use` | update; re-run `ok-use setup` if the install path changed |
|
|
71
|
+
|
|
72
|
+
For other MCP clients, `ok-use config` prints the stdio entry.
|
|
73
|
+
|
|
74
|
+
## Development
|
|
75
|
+
|
|
76
|
+
```powershell
|
|
77
|
+
uv venv --python 3.12; uv pip install -e .
|
|
78
|
+
.\.venv\Scripts\python.exe -m ok_use --local # stdio in this process (the agent's privileges)
|
|
79
|
+
.\.venv\Scripts\python.exe -m ok_use --http # HTTP on 127.0.0.1:8791 + bearer token
|
|
80
|
+
.\.venv\Scripts\python.exe -m ok_use --elevate # HTTP, relaunched as administrator (UAC)
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
The HTTP token is generated once and kept in `%APPDATA%\ok-use\settings.json` (or pass `--token`, or
|
|
84
|
+
set `OKUSE_TOKEN`). A running HTTP server writes its URL and token to `%APPDATA%\ok-use\server.json`.
|
|
85
|
+
The server started by the task logs to `%APPDATA%\ok-use\server.log`.
|
|
86
|
+
|
|
87
|
+
## Choosing a method
|
|
88
|
+
|
|
89
|
+
The server's instructions tell the agent to call `inspect_window` once per new app. It reports what kind of
|
|
90
|
+
app the window is and the tools to use for it:
|
|
91
|
+
|
|
92
|
+
| Kind | Typical apps | Method |
|
|
93
|
+
| --- | --- | --- |
|
|
94
|
+
| `accessible_app` | Win32, WinForms, WPF, WinUI, Explorer, Office, Qt 6 | `find_elements` / `element_text` to read, `element_action` to act; screenshots only to check visuals |
|
|
95
|
+
| `chromium_app` | Electron and other Chromium-based apps | the accessibility tools first; `mode="foreground"` for coordinate clicks and typing |
|
|
96
|
+
| `sparse_tree` | apps exposing only a few elements | try `find_elements` once, otherwise screenshots |
|
|
97
|
+
| `game` / `no_tree` | games, GPU-rendered or custom-drawn apps, Qt 5 without accessibility | screenshot → click/key/type_text/drag → screenshot; `mode="foreground"` when posted input is ignored |
|
|
98
|
+
| `user_browser` | the user's own Edge/Chrome/Firefox with their tabs and logins | `element_text` (page text), `find_elements`, `element_action`, or screenshot + foreground clicks. Never attach Playwright to it |
|
|
99
|
+
| `session_browser` | ok-use's own Playwright browser | Playwright scripts (`playwright_env`) |
|
|
100
|
+
| `elevated` | an admin app while the server isn't elevated | run `ok-use setup` |
|
|
101
|
+
|
|
102
|
+
Why the accessibility tools come first: a filtered `find_elements` result costs tens of tokens and a
|
|
103
|
+
whole window's tree a few hundred, where a screenshot costs about 1,500-2,500. They also work while the
|
|
104
|
+
window is covered, and `element_action` needs no coordinates. Reading is fully in the background.
|
|
105
|
+
Windows brings a window to the front while `element_action` runs, so ok-use puts the previous
|
|
106
|
+
foreground window back afterwards (`restore_focus`, on by default). The cursor and keyboard are never
|
|
107
|
+
used.
|
|
108
|
+
|
|
109
|
+
Web tasks that don't need the user's own browser go to ok-use's Playwright browser (see
|
|
110
|
+
[Browser automation](#browser-automation-playwright)). Attaching Playwright to the user's running browser
|
|
111
|
+
is the last resort: it needs the browser restarted with a remote-debugging port, and the user has to
|
|
112
|
+
approve the connection each time.
|
|
113
|
+
|
|
114
|
+
## Tools
|
|
115
|
+
|
|
116
|
+
| Group | Tools |
|
|
117
|
+
| --- | --- |
|
|
118
|
+
| Choose | `inspect_window` (the kind of app and the plan for it) |
|
|
119
|
+
| Accessibility | `find_elements`, `element_action` (invoke, toggle, select, expand, collapse, set_value, scroll_into_view, focus), `element_text` |
|
|
120
|
+
| Observe | `screenshot`, `zoom`, `list_windows`, `list_controls`, `list_monitors`, `cursor_position`, `get_status` |
|
|
121
|
+
| Mouse | `click`, `double_click`, `mouse_move`, `mouse_down`, `mouse_up`, `drag`, `scroll` |
|
|
122
|
+
| Keyboard | `type_text`, `key`, `set_text` |
|
|
123
|
+
| Windows | `window_action` (focus, minimize, maximize, restore, show_noactivate, close, move, resize, topmost, …) |
|
|
124
|
+
| System | `clipboard_read`, `clipboard_write`, `run_command`, `launch`, `list_processes`, `kill_process`, `wait` |
|
|
125
|
+
| Browser | `playwright_env` (interpreter, browsers and running sessions for Playwright scripts; see below) |
|
|
126
|
+
|
|
127
|
+
**Targets and coordinates.** Without `window`, actions use the screen and real input (`SendInput`), and
|
|
128
|
+
`x, y` are pixels of the latest screen screenshot (scaled to `max_size`, default 1568 on the long edge).
|
|
129
|
+
With `window` (an hwnd, a title substring, `pid:1234` or `process:notepad.exe`), the screenshot is that
|
|
130
|
+
window's client area and coordinates are relative to it. DPI-unaware windows are handled in their own
|
|
131
|
+
logical pixels.
|
|
132
|
+
|
|
133
|
+
**Background mode** (the default when `window` is given) captures with `PrintWindow` (the window may be
|
|
134
|
+
covered) and posts mouse/keyboard messages to the control under the point, so the user's cursor, focus
|
|
135
|
+
and keyboard are untouched. It works for classic Win32, WinForms, WPF and many other apps. Games and
|
|
136
|
+
some Chromium/Electron content read raw input and ignore posted messages; use `mode="foreground"` for
|
|
137
|
+
those. Modifier chords (ctrl+s) are reliable only in foreground mode. Minimized windows cannot be captured.
|
|
138
|
+
|
|
139
|
+
**Admin level.** Windows blocks input from a normal process into an elevated one (UIPI). `list_windows`
|
|
140
|
+
marks those windows `controllable: false`. After `ok-use setup`, the stdio bridge runs every tool in the
|
|
141
|
+
elevated server, so the agent can drive elevated apps, and `run_command`, `launch` and `kill_process`
|
|
142
|
+
run as administrator. `get_status` reports `elevated`. Agents that share the elevated server also share
|
|
143
|
+
its screenshot coordinate frames. UAC prompts on the secure desktop can't be automated.
|
|
144
|
+
|
|
145
|
+
## Browser automation (Playwright)
|
|
146
|
+
|
|
147
|
+
For web tasks that don't need the user's own browser, the preferred way is a **Playwright for Python
|
|
148
|
+
script** that the agent writes and runs itself with ok-use's Python, not the screen tools and not a
|
|
149
|
+
browser MCP. (For the user's own browser, see [Choosing a method](#choosing-a-method).) Playwright is installed with
|
|
150
|
+
ok-use. Scripts don't launch a fresh browser each time: they connect over CDP to a **persistent browser
|
|
151
|
+
session** that stays open between scripts, so tabs, page state, cookies and logins carry over.
|
|
152
|
+
|
|
153
|
+
```python
|
|
154
|
+
from ok_use.browser import session
|
|
155
|
+
|
|
156
|
+
with session() as s: # reuses the running "default" browser, or starts it
|
|
157
|
+
page = s.page # an open tab; s.find_page("github") / s.new_page(url) for others
|
|
158
|
+
page.goto("https://example.com")
|
|
159
|
+
print(page.title())
|
|
160
|
+
# leaving the block only disconnects; the browser keeps running for the next script
|
|
161
|
+
```
|
|
162
|
+
|
|
163
|
+
```powershell
|
|
164
|
+
.\.venv\Scripts\python.exe script.py
|
|
165
|
+
.\.venv\Scripts\python.exe -m ok_use browser start [--name work] [--channel auto|msedge|chrome|chromium] [--headless] [--url URL]
|
|
166
|
+
.\.venv\Scripts\python.exe -m ok_use browser status # running sessions and their CDP URLs
|
|
167
|
+
.\.venv\Scripts\python.exe -m ok_use browser stop [--name work]
|
|
168
|
+
.\.venv\Scripts\python.exe -m ok_use browser delete --name work # stop and remove the profile
|
|
169
|
+
.\.venv\Scripts\python.exe -m ok_use browser env # what the playwright_env tool returns
|
|
170
|
+
```
|
|
171
|
+
|
|
172
|
+
- **Sessions:** each `--name` has its own profile in `%LOCALAPPDATA%\ok-use\browsers\<name>` and its
|
|
173
|
+
own debugging port on 127.0.0.1. `channel="auto"` uses installed Edge, else Chrome, else Playwright's
|
|
174
|
+
bundled Chromium (`python -m playwright install chromium`).
|
|
175
|
+
- **An already-open browser (last resort):** `session(cdp_url="http://127.0.0.1:9222")` attaches to any
|
|
176
|
+
Chromium browser started with `--remote-debugging-port`. For the user's everyday browser, that means
|
|
177
|
+
restarting it and the user approving the connection each time, so agents should use the accessibility
|
|
178
|
+
tools on that window instead. Chrome and Edge refuse a debugging port on the user's
|
|
179
|
+
default profile, so use a session (or a dedicated `--user-data-dir`) for logins you want to keep.
|
|
180
|
+
- **Don't call `browser.close()`** in a script: it would close the shared browser. Use `browser stop`.
|
|
181
|
+
- **Privileges:** a session browser runs with the privileges of whatever started it. Start it from the
|
|
182
|
+
agent's normal shell, not from an elevated one.
|
|
183
|
+
- **Mixing with ok-use tools:** the session browser is an ordinary window, so the window tools can
|
|
184
|
+
handle what Playwright can't reach (permission prompts, native file dialogs).
|
|
185
|
+
|
|
186
|
+
## Layout
|
|
187
|
+
|
|
188
|
+
| File | Contents |
|
|
189
|
+
| --- | --- |
|
|
190
|
+
| `ok_use/win32.py` | ctypes layer: DPI awareness, windows, capture, `SendInput`, posted messages, elevation |
|
|
191
|
+
| `ok_use/control.py` | `Desktop`: targets, coordinate frames, background/foreground actions |
|
|
192
|
+
| `ok_use/server.py` | MCP tools, HTTP transport (stateless, idle exit), CLI |
|
|
193
|
+
| `ok_use/bridge.py` | stdio entry point: relays to the elevated server, starting it through the task |
|
|
194
|
+
| `ok_use/task.py` | the on-demand scheduled task that runs the server elevated |
|
|
195
|
+
| `ok_use/install.py` | `setup` / `uninstall` / `status`: the task and the Claude Code / Codex config |
|
|
196
|
+
| `ok_use/http.py` | Bearer-token middleware and loopback socket binding |
|
|
197
|
+
| `ok_use/uia.py` | UI Automation: `find_elements`, `element_action`, `element_text` on a dedicated COM thread |
|
|
198
|
+
| `ok_use/advisor.py` | `inspect_window`: classifies a window and returns the plan for it |
|
|
199
|
+
| `ok_use/browser.py` | Playwright sessions: persistent CDP browsers, `session()`, `ok-use browser` CLI |
|
ok_use-0.1.0/README.md
ADDED
|
@@ -0,0 +1,177 @@
|
|
|
1
|
+
# ok-use
|
|
2
|
+
|
|
3
|
+
An MCP server that gives a coding agent (Claude Code, Codex, …) computer use on Windows. It replaces
|
|
4
|
+
the built-in computer-use tool with one that works on **any app**, without per-app permission tiers.
|
|
5
|
+
The workflow is the same (screenshot → act → screenshot), and it adds per-window **background** control
|
|
6
|
+
(the user keeps their mouse and keyboard) and an **elevated (admin)** mode.
|
|
7
|
+
|
|
8
|
+
## Install (instructions for coding agents)
|
|
9
|
+
|
|
10
|
+
If a user asks you to install this repository, run these two commands in PowerShell, then tell the
|
|
11
|
+
user to restart the agent (or start a new session):
|
|
12
|
+
|
|
13
|
+
```powershell
|
|
14
|
+
uv tool install --force git+https://github.com/ok-oldking/ok-use
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```powershell
|
|
18
|
+
ok-use setup
|
|
19
|
+
```
|
|
20
|
+
|
|
21
|
+
`ok-use setup` opens **one UAC prompt**. Tell the user to approve it; you can't click it yourself.
|
|
22
|
+
If `uv` is missing, install it first with
|
|
23
|
+
`powershell -ExecutionPolicy Bypass -c "irm https://astral.sh/uv/install.ps1 | iex"`. If `ok-use` is not
|
|
24
|
+
found right after installing, run it as `& "$env:USERPROFILE\.local\bin\ok-use.exe" setup`.
|
|
25
|
+
|
|
26
|
+
What setup does:
|
|
27
|
+
|
|
28
|
+
1. Registers the scheduled task `OK Use MCP`, which can start the server as administrator later
|
|
29
|
+
without another UAC prompt. This is the step that needs the UAC approval.
|
|
30
|
+
2. Adds the `ok-use` stdio server to Claude Code (`~/.claude.json`, user scope) and to Codex
|
|
31
|
+
(`~/.codex/config.toml`), for each one it finds.
|
|
32
|
+
3. Denies Claude Code's built-in computer use (`mcp__computer-use` in `~/.claude/settings.json`), so the
|
|
33
|
+
agent uses ok-use in its place.
|
|
34
|
+
|
|
35
|
+
After that, the agent starts `ok-use` on demand like any stdio MCP server. The stdio process is a small
|
|
36
|
+
bridge: it starts the elevated server through the task, relays the agent's messages to it over
|
|
37
|
+
loopback HTTP with a bearer token, and starts it again if it has exited. The elevated server exits
|
|
38
|
+
after 30 minutes without requests.
|
|
39
|
+
|
|
40
|
+
| Command | |
|
|
41
|
+
| --- | --- |
|
|
42
|
+
| `ok-use status` | what is installed and running |
|
|
43
|
+
| `ok-use setup --no-admin` | skip the task (no UAC prompt): ok-use runs with the agent's own privileges |
|
|
44
|
+
| `ok-use setup --agent claude` | configure only this agent (`claude`, `codex`; repeatable) |
|
|
45
|
+
| `ok-use setup --keep-builtin` | leave the built-in computer use enabled |
|
|
46
|
+
| `ok-use setup --at-logon` | also start the elevated server at every logon |
|
|
47
|
+
| `ok-use uninstall` | remove the task and the agent config, then run `uv tool uninstall ok-use` |
|
|
48
|
+
| `uv tool upgrade ok-use` | update; re-run `ok-use setup` if the install path changed |
|
|
49
|
+
|
|
50
|
+
For other MCP clients, `ok-use config` prints the stdio entry.
|
|
51
|
+
|
|
52
|
+
## Development
|
|
53
|
+
|
|
54
|
+
```powershell
|
|
55
|
+
uv venv --python 3.12; uv pip install -e .
|
|
56
|
+
.\.venv\Scripts\python.exe -m ok_use --local # stdio in this process (the agent's privileges)
|
|
57
|
+
.\.venv\Scripts\python.exe -m ok_use --http # HTTP on 127.0.0.1:8791 + bearer token
|
|
58
|
+
.\.venv\Scripts\python.exe -m ok_use --elevate # HTTP, relaunched as administrator (UAC)
|
|
59
|
+
```
|
|
60
|
+
|
|
61
|
+
The HTTP token is generated once and kept in `%APPDATA%\ok-use\settings.json` (or pass `--token`, or
|
|
62
|
+
set `OKUSE_TOKEN`). A running HTTP server writes its URL and token to `%APPDATA%\ok-use\server.json`.
|
|
63
|
+
The server started by the task logs to `%APPDATA%\ok-use\server.log`.
|
|
64
|
+
|
|
65
|
+
## Choosing a method
|
|
66
|
+
|
|
67
|
+
The server's instructions tell the agent to call `inspect_window` once per new app. It reports what kind of
|
|
68
|
+
app the window is and the tools to use for it:
|
|
69
|
+
|
|
70
|
+
| Kind | Typical apps | Method |
|
|
71
|
+
| --- | --- | --- |
|
|
72
|
+
| `accessible_app` | Win32, WinForms, WPF, WinUI, Explorer, Office, Qt 6 | `find_elements` / `element_text` to read, `element_action` to act; screenshots only to check visuals |
|
|
73
|
+
| `chromium_app` | Electron and other Chromium-based apps | the accessibility tools first; `mode="foreground"` for coordinate clicks and typing |
|
|
74
|
+
| `sparse_tree` | apps exposing only a few elements | try `find_elements` once, otherwise screenshots |
|
|
75
|
+
| `game` / `no_tree` | games, GPU-rendered or custom-drawn apps, Qt 5 without accessibility | screenshot → click/key/type_text/drag → screenshot; `mode="foreground"` when posted input is ignored |
|
|
76
|
+
| `user_browser` | the user's own Edge/Chrome/Firefox with their tabs and logins | `element_text` (page text), `find_elements`, `element_action`, or screenshot + foreground clicks. Never attach Playwright to it |
|
|
77
|
+
| `session_browser` | ok-use's own Playwright browser | Playwright scripts (`playwright_env`) |
|
|
78
|
+
| `elevated` | an admin app while the server isn't elevated | run `ok-use setup` |
|
|
79
|
+
|
|
80
|
+
Why the accessibility tools come first: a filtered `find_elements` result costs tens of tokens and a
|
|
81
|
+
whole window's tree a few hundred, where a screenshot costs about 1,500-2,500. They also work while the
|
|
82
|
+
window is covered, and `element_action` needs no coordinates. Reading is fully in the background.
|
|
83
|
+
Windows brings a window to the front while `element_action` runs, so ok-use puts the previous
|
|
84
|
+
foreground window back afterwards (`restore_focus`, on by default). The cursor and keyboard are never
|
|
85
|
+
used.
|
|
86
|
+
|
|
87
|
+
Web tasks that don't need the user's own browser go to ok-use's Playwright browser (see
|
|
88
|
+
[Browser automation](#browser-automation-playwright)). Attaching Playwright to the user's running browser
|
|
89
|
+
is the last resort: it needs the browser restarted with a remote-debugging port, and the user has to
|
|
90
|
+
approve the connection each time.
|
|
91
|
+
|
|
92
|
+
## Tools
|
|
93
|
+
|
|
94
|
+
| Group | Tools |
|
|
95
|
+
| --- | --- |
|
|
96
|
+
| Choose | `inspect_window` (the kind of app and the plan for it) |
|
|
97
|
+
| Accessibility | `find_elements`, `element_action` (invoke, toggle, select, expand, collapse, set_value, scroll_into_view, focus), `element_text` |
|
|
98
|
+
| Observe | `screenshot`, `zoom`, `list_windows`, `list_controls`, `list_monitors`, `cursor_position`, `get_status` |
|
|
99
|
+
| Mouse | `click`, `double_click`, `mouse_move`, `mouse_down`, `mouse_up`, `drag`, `scroll` |
|
|
100
|
+
| Keyboard | `type_text`, `key`, `set_text` |
|
|
101
|
+
| Windows | `window_action` (focus, minimize, maximize, restore, show_noactivate, close, move, resize, topmost, …) |
|
|
102
|
+
| System | `clipboard_read`, `clipboard_write`, `run_command`, `launch`, `list_processes`, `kill_process`, `wait` |
|
|
103
|
+
| Browser | `playwright_env` (interpreter, browsers and running sessions for Playwright scripts; see below) |
|
|
104
|
+
|
|
105
|
+
**Targets and coordinates.** Without `window`, actions use the screen and real input (`SendInput`), and
|
|
106
|
+
`x, y` are pixels of the latest screen screenshot (scaled to `max_size`, default 1568 on the long edge).
|
|
107
|
+
With `window` (an hwnd, a title substring, `pid:1234` or `process:notepad.exe`), the screenshot is that
|
|
108
|
+
window's client area and coordinates are relative to it. DPI-unaware windows are handled in their own
|
|
109
|
+
logical pixels.
|
|
110
|
+
|
|
111
|
+
**Background mode** (the default when `window` is given) captures with `PrintWindow` (the window may be
|
|
112
|
+
covered) and posts mouse/keyboard messages to the control under the point, so the user's cursor, focus
|
|
113
|
+
and keyboard are untouched. It works for classic Win32, WinForms, WPF and many other apps. Games and
|
|
114
|
+
some Chromium/Electron content read raw input and ignore posted messages; use `mode="foreground"` for
|
|
115
|
+
those. Modifier chords (ctrl+s) are reliable only in foreground mode. Minimized windows cannot be captured.
|
|
116
|
+
|
|
117
|
+
**Admin level.** Windows blocks input from a normal process into an elevated one (UIPI). `list_windows`
|
|
118
|
+
marks those windows `controllable: false`. After `ok-use setup`, the stdio bridge runs every tool in the
|
|
119
|
+
elevated server, so the agent can drive elevated apps, and `run_command`, `launch` and `kill_process`
|
|
120
|
+
run as administrator. `get_status` reports `elevated`. Agents that share the elevated server also share
|
|
121
|
+
its screenshot coordinate frames. UAC prompts on the secure desktop can't be automated.
|
|
122
|
+
|
|
123
|
+
## Browser automation (Playwright)
|
|
124
|
+
|
|
125
|
+
For web tasks that don't need the user's own browser, the preferred way is a **Playwright for Python
|
|
126
|
+
script** that the agent writes and runs itself with ok-use's Python, not the screen tools and not a
|
|
127
|
+
browser MCP. (For the user's own browser, see [Choosing a method](#choosing-a-method).) Playwright is installed with
|
|
128
|
+
ok-use. Scripts don't launch a fresh browser each time: they connect over CDP to a **persistent browser
|
|
129
|
+
session** that stays open between scripts, so tabs, page state, cookies and logins carry over.
|
|
130
|
+
|
|
131
|
+
```python
|
|
132
|
+
from ok_use.browser import session
|
|
133
|
+
|
|
134
|
+
with session() as s: # reuses the running "default" browser, or starts it
|
|
135
|
+
page = s.page # an open tab; s.find_page("github") / s.new_page(url) for others
|
|
136
|
+
page.goto("https://example.com")
|
|
137
|
+
print(page.title())
|
|
138
|
+
# leaving the block only disconnects; the browser keeps running for the next script
|
|
139
|
+
```
|
|
140
|
+
|
|
141
|
+
```powershell
|
|
142
|
+
.\.venv\Scripts\python.exe script.py
|
|
143
|
+
.\.venv\Scripts\python.exe -m ok_use browser start [--name work] [--channel auto|msedge|chrome|chromium] [--headless] [--url URL]
|
|
144
|
+
.\.venv\Scripts\python.exe -m ok_use browser status # running sessions and their CDP URLs
|
|
145
|
+
.\.venv\Scripts\python.exe -m ok_use browser stop [--name work]
|
|
146
|
+
.\.venv\Scripts\python.exe -m ok_use browser delete --name work # stop and remove the profile
|
|
147
|
+
.\.venv\Scripts\python.exe -m ok_use browser env # what the playwright_env tool returns
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
- **Sessions:** each `--name` has its own profile in `%LOCALAPPDATA%\ok-use\browsers\<name>` and its
|
|
151
|
+
own debugging port on 127.0.0.1. `channel="auto"` uses installed Edge, else Chrome, else Playwright's
|
|
152
|
+
bundled Chromium (`python -m playwright install chromium`).
|
|
153
|
+
- **An already-open browser (last resort):** `session(cdp_url="http://127.0.0.1:9222")` attaches to any
|
|
154
|
+
Chromium browser started with `--remote-debugging-port`. For the user's everyday browser, that means
|
|
155
|
+
restarting it and the user approving the connection each time, so agents should use the accessibility
|
|
156
|
+
tools on that window instead. Chrome and Edge refuse a debugging port on the user's
|
|
157
|
+
default profile, so use a session (or a dedicated `--user-data-dir`) for logins you want to keep.
|
|
158
|
+
- **Don't call `browser.close()`** in a script: it would close the shared browser. Use `browser stop`.
|
|
159
|
+
- **Privileges:** a session browser runs with the privileges of whatever started it. Start it from the
|
|
160
|
+
agent's normal shell, not from an elevated one.
|
|
161
|
+
- **Mixing with ok-use tools:** the session browser is an ordinary window, so the window tools can
|
|
162
|
+
handle what Playwright can't reach (permission prompts, native file dialogs).
|
|
163
|
+
|
|
164
|
+
## Layout
|
|
165
|
+
|
|
166
|
+
| File | Contents |
|
|
167
|
+
| --- | --- |
|
|
168
|
+
| `ok_use/win32.py` | ctypes layer: DPI awareness, windows, capture, `SendInput`, posted messages, elevation |
|
|
169
|
+
| `ok_use/control.py` | `Desktop`: targets, coordinate frames, background/foreground actions |
|
|
170
|
+
| `ok_use/server.py` | MCP tools, HTTP transport (stateless, idle exit), CLI |
|
|
171
|
+
| `ok_use/bridge.py` | stdio entry point: relays to the elevated server, starting it through the task |
|
|
172
|
+
| `ok_use/task.py` | the on-demand scheduled task that runs the server elevated |
|
|
173
|
+
| `ok_use/install.py` | `setup` / `uninstall` / `status`: the task and the Claude Code / Codex config |
|
|
174
|
+
| `ok_use/http.py` | Bearer-token middleware and loopback socket binding |
|
|
175
|
+
| `ok_use/uia.py` | UI Automation: `find_elements`, `element_action`, `element_text` on a dedicated COM thread |
|
|
176
|
+
| `ok_use/advisor.py` | `inspect_window`: classifies a window and returns the plan for it |
|
|
177
|
+
| `ok_use/browser.py` | Playwright sessions: persistent CDP browsers, `session()`, `ok-use browser` CLI |
|
|
@@ -0,0 +1,112 @@
|
|
|
1
|
+
"""inspect_window: what kind of app a window is, and which ok-use tools to use for it.
|
|
2
|
+
|
|
3
|
+
Agents call it once per new app instead of guessing; it costs a few hundred tokens and saves screenshots
|
|
4
|
+
(1,500-2,500 tokens each) wherever the accessibility tree can do the job.
|
|
5
|
+
"""
|
|
6
|
+
from __future__ import annotations
|
|
7
|
+
|
|
8
|
+
from . import win32 as w
|
|
9
|
+
|
|
10
|
+
BROWSERS = {'chrome.exe', 'msedge.exe', 'firefox.exe', 'brave.exe', 'opera.exe', 'vivaldi.exe', 'arc.exe',
|
|
11
|
+
'chromium.exe', 'iexplore.exe', 'thorium.exe', 'waterfox.exe', 'librewolf.exe', 'zen.exe'}
|
|
12
|
+
GAME_CLASSES = ('unitywndclass', 'unrealwindow', 'sdl_app', 'glfw', 'waapplication window', 'valve001',
|
|
13
|
+
'cryengine', 'launchunrealuesandbox', 'godot', 'gamewindow', 'd3d', 'dx11', 'ogl', 'opengl',
|
|
14
|
+
'riotwindowclass', 'unityeditor')
|
|
15
|
+
|
|
16
|
+
PLAN = {
|
|
17
|
+
'accessible_app': [
|
|
18
|
+
'Read with find_elements (filter by name/role) and element_text: text instead of images, works while '
|
|
19
|
+
'the window is covered.',
|
|
20
|
+
'Act with element_action (invoke, toggle, select, expand, set_value): no coordinates, no mouse. Windows '
|
|
21
|
+
'brings the window forward during the action; ok-use puts the previous window back.',
|
|
22
|
+
'Use screenshot only to check layout or visuals, or when an element is missing or an action fails; '
|
|
23
|
+
'then click/type_text with window=... (background mode first, mode="foreground" if ignored).',
|
|
24
|
+
],
|
|
25
|
+
'no_tree': [
|
|
26
|
+
'This app exposes no accessibility tree (custom-drawn, GPU-rendered, or a Qt 5 app without '
|
|
27
|
+
'accessibility): use screenshot (window=..., small max_size to save tokens) and zoom for detail.',
|
|
28
|
+
'Act with click/key/type_text/drag/scroll with window=...: background mode first, mode="foreground" '
|
|
29
|
+
'if an action has no visible effect.',
|
|
30
|
+
],
|
|
31
|
+
'sparse_tree': [
|
|
32
|
+
'The accessibility tree is thin: try find_elements once for the controls you need; if they are not '
|
|
33
|
+
'there, use screenshot + click/key/type_text with window=....',
|
|
34
|
+
'Background mode (the default with window=...) first; if an action has no visible effect, retry with '
|
|
35
|
+
'mode="foreground".',
|
|
36
|
+
],
|
|
37
|
+
'game': [
|
|
38
|
+
'No accessibility tree: use screenshot (window=..., small max_size to save tokens) and zoom for detail.',
|
|
39
|
+
'Act with click/key/type_text/drag/scroll. Many games read the live mouse/keyboard state and ignore '
|
|
40
|
+
'posted (background) input: use mode="foreground" when background input has no effect. drag already '
|
|
41
|
+
'uses real input.',
|
|
42
|
+
'Keys and clicks with real input stay down 0.05 s so games polling each frame see them; use key(hold=...) '
|
|
43
|
+
'for longer presses (movement).',
|
|
44
|
+
],
|
|
45
|
+
'user_browser': [
|
|
46
|
+
"This is the user's own browser (their tabs and logins). Do not restart it or ask for a remote-debugging "
|
|
47
|
+
'connection: attaching Playwright needs the browser restarted with a debugging port and the user '
|
|
48
|
+
'approving it each time.',
|
|
49
|
+
'Read the page with element_text(window=...) (the page text, in the background) or find_elements '
|
|
50
|
+
'(links, buttons, fields with their rects).',
|
|
51
|
+
'Act with element_action (invoke links/buttons, set_value on fields) or screenshot + click/type_text. '
|
|
52
|
+
'Background posted input often fails in Chromium pages; use mode="foreground" for clicks and typing.',
|
|
53
|
+
"For web work that does not need the user's tabs or logins, use ok-use's own Playwright browser "
|
|
54
|
+
'instead (playwright_env): no prompts, full DOM control.',
|
|
55
|
+
],
|
|
56
|
+
'session_browser': [
|
|
57
|
+
"ok-use's own Playwright browser session: drive it with Playwright scripts (playwright_env), not with "
|
|
58
|
+
'the window tools.',
|
|
59
|
+
'Use the window tools only for what Playwright cannot reach: permission prompts, native file dialogs.',
|
|
60
|
+
],
|
|
61
|
+
'chromium_app': [
|
|
62
|
+
'An Electron/Chromium app: its accessibility tree usually describes the UI well. Use find_elements, '
|
|
63
|
+
'element_text and element_action first.',
|
|
64
|
+
'For clicks and typing by coordinates use mode="foreground": Chromium content often ignores posted '
|
|
65
|
+
'background input.',
|
|
66
|
+
],
|
|
67
|
+
'elevated': [
|
|
68
|
+
'The window belongs to an elevated (admin) process and this server is not elevated: input and UI '
|
|
69
|
+
'Automation are blocked. Run ok-use setup so the server runs elevated.',
|
|
70
|
+
],
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
|
|
74
|
+
def classify(desk, uia, window) -> dict:
|
|
75
|
+
hwnd = desk.resolve(window)
|
|
76
|
+
if not hwnd:
|
|
77
|
+
raise ValueError('inspect_window needs a window')
|
|
78
|
+
info = desk.describe(hwnd)
|
|
79
|
+
cls, proc = info['class'].lower(), (info['process'] or '').lower()
|
|
80
|
+
out = {'hwnd': hwnd, 'title': info['title'], 'process': info['process'], 'class': info['class'],
|
|
81
|
+
'elevated': info['elevated'], 'controllable': info['controllable'], 'minimized': info['minimized']}
|
|
82
|
+
if not info['controllable']:
|
|
83
|
+
out.update(kind='elevated', plan=PLAN['elevated'])
|
|
84
|
+
return out
|
|
85
|
+
tree = uia.tree_summary(hwnd)
|
|
86
|
+
out['accessibility'] = tree
|
|
87
|
+
sessions = _session_pids()
|
|
88
|
+
if proc in BROWSERS:
|
|
89
|
+
kind = 'session_browser' if info['pid'] in sessions else 'user_browser'
|
|
90
|
+
elif any(g in cls for g in GAME_CLASSES):
|
|
91
|
+
kind = 'game'
|
|
92
|
+
elif tree['named'] <= 3 and tree['interactive'] <= 1:
|
|
93
|
+
kind = 'no_tree'
|
|
94
|
+
elif cls.startswith('chrome_widgetwin'):
|
|
95
|
+
kind = 'chromium_app'
|
|
96
|
+
elif tree['interactive'] < 3 or tree['named'] < 8:
|
|
97
|
+
kind = 'sparse_tree'
|
|
98
|
+
else:
|
|
99
|
+
kind = 'accessible_app'
|
|
100
|
+
out['kind'] = kind
|
|
101
|
+
out['plan'] = PLAN[kind]
|
|
102
|
+
if info['minimized']:
|
|
103
|
+
out['note'] = 'Minimized: screenshots fail; window_action(action="show_noactivate") first.'
|
|
104
|
+
return out
|
|
105
|
+
|
|
106
|
+
|
|
107
|
+
def _session_pids() -> set[int]:
|
|
108
|
+
try:
|
|
109
|
+
from . import browser
|
|
110
|
+
return {int(s['pid']) for s in browser.list_sessions() if s.get('pid')}
|
|
111
|
+
except Exception: # noqa: BLE001
|
|
112
|
+
return set()
|
|
@@ -0,0 +1,156 @@
|
|
|
1
|
+
"""stdio <-> elevated HTTP bridge.
|
|
2
|
+
|
|
3
|
+
The agent launches `ok-use` over stdio as with any MCP server. When the scheduled task is installed and
|
|
4
|
+
this process is not elevated, the bridge starts the elevated HTTP server through the task (no UAC
|
|
5
|
+
prompt), then relays each JSON-RPC message to it with the bearer token. The server is stateless, so if
|
|
6
|
+
it has exited (idle timeout) or crashed, the bridge starts it again and resends the message.
|
|
7
|
+
"""
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import json
|
|
11
|
+
import socket
|
|
12
|
+
import sys
|
|
13
|
+
import threading
|
|
14
|
+
import time
|
|
15
|
+
import urllib.error
|
|
16
|
+
import urllib.request
|
|
17
|
+
from urllib.parse import urlsplit
|
|
18
|
+
|
|
19
|
+
START_TIMEOUT = 30.0
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _log(*parts):
|
|
23
|
+
print('[ok-use bridge]', *parts, file=sys.stderr, flush=True)
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def live_server() -> dict | None:
|
|
27
|
+
"""The connection record of a running server, if its process and port are alive."""
|
|
28
|
+
from .server import _state_path
|
|
29
|
+
try:
|
|
30
|
+
info = json.loads(_state_path().read_text(encoding='utf-8'))
|
|
31
|
+
import psutil
|
|
32
|
+
if not psutil.pid_exists(int(info['pid'])):
|
|
33
|
+
return None
|
|
34
|
+
parts = urlsplit(info['url'])
|
|
35
|
+
with socket.create_connection((parts.hostname, parts.port), timeout=1):
|
|
36
|
+
return info
|
|
37
|
+
except (OSError, ValueError, KeyError, TypeError):
|
|
38
|
+
return None
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def start_server(timeout: float = START_TIMEOUT) -> dict:
|
|
42
|
+
"""Start the elevated server through the scheduled task and wait for it to listen."""
|
|
43
|
+
from . import task
|
|
44
|
+
info = live_server()
|
|
45
|
+
if info and info.get('elevated'):
|
|
46
|
+
return info
|
|
47
|
+
task.run()
|
|
48
|
+
deadline = time.monotonic() + timeout
|
|
49
|
+
while time.monotonic() < deadline:
|
|
50
|
+
info = live_server()
|
|
51
|
+
if info and info.get('elevated'):
|
|
52
|
+
return info
|
|
53
|
+
time.sleep(0.2)
|
|
54
|
+
raise RuntimeError(f'the elevated server did not start within {timeout:.0f}s '
|
|
55
|
+
'(see %APPDATA%\\ok-use\\server.log)')
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
class Bridge:
|
|
59
|
+
def __init__(self, info: dict):
|
|
60
|
+
self.info = info
|
|
61
|
+
self.lock = threading.Lock()
|
|
62
|
+
self.out_lock = threading.Lock()
|
|
63
|
+
self.protocol: str | None = None
|
|
64
|
+
|
|
65
|
+
def _server(self, stale: dict | None = None) -> dict:
|
|
66
|
+
with self.lock:
|
|
67
|
+
if stale is not None and self.info is stale:
|
|
68
|
+
_log('server is gone, restarting it')
|
|
69
|
+
self.info = start_server()
|
|
70
|
+
return self.info
|
|
71
|
+
|
|
72
|
+
def write(self, msg):
|
|
73
|
+
data = json.dumps(msg, ensure_ascii=False, separators=(',', ':')).encode('utf-8') + b'\n'
|
|
74
|
+
with self.out_lock:
|
|
75
|
+
sys.stdout.buffer.write(data)
|
|
76
|
+
sys.stdout.buffer.flush()
|
|
77
|
+
|
|
78
|
+
def error(self, msg: dict, text: str):
|
|
79
|
+
if isinstance(msg, dict) and 'id' in msg and 'method' in msg:
|
|
80
|
+
self.write({'jsonrpc': '2.0', 'id': msg['id'], 'error': {'code': -32603, 'message': text}})
|
|
81
|
+
|
|
82
|
+
def _post(self, info: dict, body: bytes):
|
|
83
|
+
headers = {'Content-Type': 'application/json', 'Accept': 'application/json, text/event-stream',
|
|
84
|
+
'Authorization': f'Bearer {info["token"]}'}
|
|
85
|
+
if self.protocol:
|
|
86
|
+
headers['MCP-Protocol-Version'] = self.protocol
|
|
87
|
+
req = urllib.request.Request(info['url'], data=body, headers=headers, method='POST')
|
|
88
|
+
with urllib.request.urlopen(req, timeout=None) as resp:
|
|
89
|
+
return resp.headers.get('Content-Type', ''), resp.read()
|
|
90
|
+
|
|
91
|
+
def forward(self, msg: dict, body: bytes):
|
|
92
|
+
try:
|
|
93
|
+
info = self._server()
|
|
94
|
+
try:
|
|
95
|
+
ctype, data = self._post(info, body)
|
|
96
|
+
except urllib.error.URLError as e:
|
|
97
|
+
# Only a refused connection is safe to resend: the server never saw the message.
|
|
98
|
+
if isinstance(e, urllib.error.HTTPError) or not isinstance(e.reason, ConnectionRefusedError):
|
|
99
|
+
raise
|
|
100
|
+
ctype, data = self._post(self._server(stale=info), body)
|
|
101
|
+
except urllib.error.HTTPError as e:
|
|
102
|
+
detail = e.read().decode('utf-8', 'replace')[:500]
|
|
103
|
+
try:
|
|
104
|
+
self.write(json.loads(detail)) # a JSON-RPC error from the server
|
|
105
|
+
except ValueError:
|
|
106
|
+
self.error(msg, f'ok-use server returned HTTP {e.code}: {detail}')
|
|
107
|
+
return
|
|
108
|
+
except Exception as e: # noqa: BLE001
|
|
109
|
+
_log(f'{type(e).__name__}: {e}')
|
|
110
|
+
self.error(msg, f'ok-use bridge: {type(e).__name__}: {e}')
|
|
111
|
+
return
|
|
112
|
+
for reply in self._messages(ctype, data):
|
|
113
|
+
if isinstance(reply, dict) and msg.get('method') == 'initialize':
|
|
114
|
+
self.protocol = (reply.get('result') or {}).get('protocolVersion') or self.protocol
|
|
115
|
+
self.write(reply)
|
|
116
|
+
|
|
117
|
+
@staticmethod
|
|
118
|
+
def _messages(ctype: str, data: bytes):
|
|
119
|
+
if not data.strip():
|
|
120
|
+
return []
|
|
121
|
+
if 'text/event-stream' in ctype:
|
|
122
|
+
out = []
|
|
123
|
+
for event in data.decode('utf-8').replace('\r\n', '\n').split('\n\n'):
|
|
124
|
+
payload = '\n'.join(l[5:].lstrip() for l in event.split('\n') if l.startswith('data:'))
|
|
125
|
+
if payload:
|
|
126
|
+
out.append(json.loads(payload))
|
|
127
|
+
return out
|
|
128
|
+
return [json.loads(data)]
|
|
129
|
+
|
|
130
|
+
def serve(self):
|
|
131
|
+
for line in sys.stdin.buffer:
|
|
132
|
+
line = line.strip()
|
|
133
|
+
if not line:
|
|
134
|
+
continue
|
|
135
|
+
try:
|
|
136
|
+
msg = json.loads(line)
|
|
137
|
+
except ValueError:
|
|
138
|
+
self.write({'jsonrpc': '2.0', 'id': None, 'error': {'code': -32700, 'message': 'Parse error'}})
|
|
139
|
+
continue
|
|
140
|
+
threading.Thread(target=self.forward, args=(msg, line), daemon=True).start()
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def run_stdio(local: bool = False):
|
|
144
|
+
"""The stdio entry point: bridge to the elevated server when possible, otherwise serve in-process."""
|
|
145
|
+
from . import task, win32
|
|
146
|
+
if not local and not win32.is_admin() and task.exists():
|
|
147
|
+
try:
|
|
148
|
+
info = start_server()
|
|
149
|
+
except Exception as e: # noqa: BLE001
|
|
150
|
+
_log(f'could not start the elevated server ({e}); running without admin rights')
|
|
151
|
+
else:
|
|
152
|
+
_log(f'relaying to the elevated server at {info["url"]}')
|
|
153
|
+
Bridge(info).serve()
|
|
154
|
+
return
|
|
155
|
+
from .server import build_server
|
|
156
|
+
build_server().run('stdio')
|