@namzu/computer-use 1.4.3 → 2.0.0
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.
- package/CHANGELOG.md +36 -0
- package/README.md +96 -5
- package/dist/SubprocessComputerUseHost.d.ts +45 -5
- package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
- package/dist/SubprocessComputerUseHost.js +94 -8
- package/dist/SubprocessComputerUseHost.js.map +1 -1
- package/dist/adapters/cua-driver/adapter.d.ts +100 -0
- package/dist/adapters/cua-driver/adapter.d.ts.map +1 -0
- package/dist/adapters/cua-driver/adapter.js +459 -0
- package/dist/adapters/cua-driver/adapter.js.map +1 -0
- package/dist/adapters/cua-driver/client.d.ts +108 -0
- package/dist/adapters/cua-driver/client.d.ts.map +1 -0
- package/dist/adapters/cua-driver/client.js +316 -0
- package/dist/adapters/cua-driver/client.js.map +1 -0
- package/dist/adapters/cua-driver/keys.d.ts +24 -0
- package/dist/adapters/cua-driver/keys.d.ts.map +1 -0
- package/dist/adapters/cua-driver/keys.js +106 -0
- package/dist/adapters/cua-driver/keys.js.map +1 -0
- package/dist/adapters/cua-driver/provision.d.ts +80 -0
- package/dist/adapters/cua-driver/provision.d.ts.map +1 -0
- package/dist/adapters/cua-driver/provision.js +147 -0
- package/dist/adapters/cua-driver/provision.js.map +1 -0
- package/dist/adapters/cua-driver/ui-tree.d.ts +42 -0
- package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -0
- package/dist/adapters/cua-driver/ui-tree.js +187 -0
- package/dist/adapters/cua-driver/ui-tree.js.map +1 -0
- package/dist/adapters/cua-driver/zip.d.ts +6 -0
- package/dist/adapters/cua-driver/zip.d.ts.map +1 -0
- package/dist/adapters/cua-driver/zip.js +86 -0
- package/dist/adapters/cua-driver/zip.js.map +1 -0
- package/dist/adapters/darwin.d.ts +23 -0
- package/dist/adapters/darwin.d.ts.map +1 -1
- package/dist/adapters/darwin.js +96 -31
- package/dist/adapters/darwin.js.map +1 -1
- package/dist/adapters/linux-wayland.d.ts.map +1 -1
- package/dist/adapters/linux-wayland.js +12 -0
- package/dist/adapters/linux-wayland.js.map +1 -1
- package/dist/adapters/linux-x11.d.ts.map +1 -1
- package/dist/adapters/linux-x11.js +12 -0
- package/dist/adapters/linux-x11.js.map +1 -1
- package/dist/adapters/types.d.ts +23 -5
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/adapters/types.js.map +1 -1
- package/dist/adapters/win32-powershell.d.ts +41 -0
- package/dist/adapters/win32-powershell.d.ts.map +1 -0
- package/dist/adapters/win32-powershell.js +407 -0
- package/dist/adapters/win32-powershell.js.map +1 -0
- package/dist/adapters/win32.d.ts +39 -11
- package/dist/adapters/win32.d.ts.map +1 -1
- package/dist/adapters/win32.js +72 -311
- package/dist/adapters/win32.js.map +1 -1
- package/dist/adapters/wsl.d.ts +46 -0
- package/dist/adapters/wsl.d.ts.map +1 -0
- package/dist/adapters/wsl.js +130 -0
- package/dist/adapters/wsl.js.map +1 -0
- package/dist/index.d.ts +2 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +2 -2
- package/src/SubprocessComputerUseHost.ts +115 -8
- package/src/adapters/cua-driver/adapter.ts +571 -0
- package/src/adapters/cua-driver/client.ts +451 -0
- package/src/adapters/cua-driver/keys.ts +111 -0
- package/src/adapters/cua-driver/provision.ts +208 -0
- package/src/adapters/cua-driver/ui-tree.ts +234 -0
- package/src/adapters/cua-driver/zip.ts +90 -0
- package/src/adapters/darwin.ts +124 -38
- package/src/adapters/linux-wayland.ts +13 -0
- package/src/adapters/linux-x11.ts +13 -0
- package/src/adapters/types.ts +29 -4
- package/src/adapters/win32-powershell.ts +482 -0
- package/src/adapters/win32.ts +112 -356
- package/src/adapters/wsl.ts +150 -0
- package/src/index.ts +5 -1
|
@@ -0,0 +1,571 @@
|
|
|
1
|
+
import type {
|
|
2
|
+
ComputerUseAction,
|
|
3
|
+
ComputerUseCapabilities,
|
|
4
|
+
ComputerUseResult,
|
|
5
|
+
DisplayGeometry,
|
|
6
|
+
DisplayInfo,
|
|
7
|
+
FocusWindowResult,
|
|
8
|
+
ScreenshotResult,
|
|
9
|
+
UiActResult,
|
|
10
|
+
UiElementAction,
|
|
11
|
+
UiSnapshot,
|
|
12
|
+
WindowInfo,
|
|
13
|
+
} from '@namzu/sdk'
|
|
14
|
+
import type { Adapter } from '../types.js'
|
|
15
|
+
import {
|
|
16
|
+
McpStdioClient,
|
|
17
|
+
type McpStdioClientOptions,
|
|
18
|
+
McpToolError,
|
|
19
|
+
type McpToolResult,
|
|
20
|
+
} from './client.js'
|
|
21
|
+
import { translateKeyForCuaDriver } from './keys.js'
|
|
22
|
+
import { type UiRefFacts, toUiTree } from './ui-tree.js'
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* The Windows desktop through cua-driver (github.com/trycua/cua, MIT): one
|
|
26
|
+
* `cua-driver.exe mcp` process for the adapter's lifetime, spoken to as an
|
|
27
|
+
* MCP server over its standard streams.
|
|
28
|
+
*
|
|
29
|
+
* Every input goes to cua-driver's `desktop` scope: real `SendInput` at
|
|
30
|
+
* screen coordinates, which is this package's contract. Its default
|
|
31
|
+
* `window` scope posts messages to a process in the background instead, a
|
|
32
|
+
* different model this adapter does not expose.
|
|
33
|
+
*
|
|
34
|
+
* What the adapter adds on top:
|
|
35
|
+
* - the animated agent cursor is switched off for its session: with it, a
|
|
36
|
+
* click took 0.9–3.8 s (the cursor glides to the target) instead of about
|
|
37
|
+
* 0.12 s, and a full-screen overlay window joined the window list;
|
|
38
|
+
* - a single printable key is typed as text (see `./keys.ts`);
|
|
39
|
+
* - a pointer action whose only failure is cua-driver's after-the-fact
|
|
40
|
+
* foreground check is reported as done (see {@link isDeliveredPointerAction});
|
|
41
|
+
* - the window list drops cua-driver's own overlay, the shell's desktop and
|
|
42
|
+
* 1-pixel windows, and orders it front to back;
|
|
43
|
+
* - a window's UI Automation tree (`get_window_state`) becomes a `UiSnapshot`
|
|
44
|
+
* whose refs are cua-driver's element tokens, and `uiAct` drives a control
|
|
45
|
+
* by token: UIA Invoke for a button, ValuePattern for a field, falling back
|
|
46
|
+
* to typing into a field that is empty and has no settable value (classic
|
|
47
|
+
* Notepad's editor is one).
|
|
48
|
+
*/
|
|
49
|
+
|
|
50
|
+
export interface CuaDriverAdapterOptions {
|
|
51
|
+
/** `cua-driver.exe`, as this process starts it (a Linux path under WSL). */
|
|
52
|
+
readonly executable: string
|
|
53
|
+
/** The environment for it; see `cuaDriverEnvironment` in `../win32.ts`. */
|
|
54
|
+
readonly env: NodeJS.ProcessEnv
|
|
55
|
+
readonly cwd?: string
|
|
56
|
+
/** For the backend label; the pinned version when it is the pinned build. */
|
|
57
|
+
readonly version?: string
|
|
58
|
+
/** For tests. */
|
|
59
|
+
readonly spawnProcess?: McpStdioClientOptions['spawnProcess']
|
|
60
|
+
readonly requestTimeoutMs?: number
|
|
61
|
+
readonly startTimeoutMs?: number
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const CAPTURE_TIMEOUT_MS = 30_000
|
|
65
|
+
const LIST_TIMEOUT_MS = 20_000
|
|
66
|
+
/** A browser window's tree takes 2–3 s; a huge one is cut by `UI_MAX_ELEMENTS` first. */
|
|
67
|
+
const UI_TREE_TIMEOUT_MS = 30_000
|
|
68
|
+
/** The most controls one snapshot walks. The SDK shows the model at most ~14 000 characters of it. */
|
|
69
|
+
const UI_MAX_ELEMENTS = 1_500
|
|
70
|
+
/** cua-driver refuses more than 50 ticks in one scroll call. */
|
|
71
|
+
const MAX_SCROLL_TICKS = 50
|
|
72
|
+
/** A drag glides through intermediate moves; many targets ignore one that teleports. */
|
|
73
|
+
const DRAG = { durationMs: 250, steps: 12 } as const
|
|
74
|
+
|
|
75
|
+
export class CuaDriverAdapter implements Adapter {
|
|
76
|
+
readonly capabilities: ComputerUseCapabilities
|
|
77
|
+
readonly backend: string
|
|
78
|
+
private readonly client: McpStdioClient
|
|
79
|
+
/** Window id → owning pid, from the latest list; `bring_to_front` needs both. */
|
|
80
|
+
private readonly windowPids = new Map<string, number>()
|
|
81
|
+
/** The refs of the latest UI snapshot: element token → its window's pid and what it held. */
|
|
82
|
+
private uiRefs = new Map<string, UiRefFacts & { readonly pid: number }>()
|
|
83
|
+
|
|
84
|
+
constructor(options: CuaDriverAdapterOptions) {
|
|
85
|
+
this.backend = `cua-driver${options.version ? ` ${options.version}` : ''}`
|
|
86
|
+
this.client = new McpStdioClient({
|
|
87
|
+
command: options.executable,
|
|
88
|
+
args: ['mcp'],
|
|
89
|
+
env: options.env,
|
|
90
|
+
cwd: options.cwd,
|
|
91
|
+
clientName: 'namzu-computer-use',
|
|
92
|
+
requestTimeoutMs: options.requestTimeoutMs ?? 15_000,
|
|
93
|
+
startTimeoutMs: options.startTimeoutMs ?? 30_000,
|
|
94
|
+
spawnProcess: options.spawnProcess,
|
|
95
|
+
afterStart: async (call) => {
|
|
96
|
+
// Best effort: a build without the tool still works, only slower.
|
|
97
|
+
await call('set_agent_cursor_enabled', { enabled: false }).catch(() => undefined)
|
|
98
|
+
},
|
|
99
|
+
})
|
|
100
|
+
this.capabilities = Object.freeze({
|
|
101
|
+
displayServer: 'win32',
|
|
102
|
+
screenshot: true,
|
|
103
|
+
mouse: true,
|
|
104
|
+
keyboard: true,
|
|
105
|
+
cursorPosition: true,
|
|
106
|
+
// cua-driver has clipboard tools; this adapter offers no clipboard action.
|
|
107
|
+
clipboard: false,
|
|
108
|
+
supportedActions: Object.freeze([
|
|
109
|
+
'screenshot' as const,
|
|
110
|
+
'cursor_position' as const,
|
|
111
|
+
'mouse_move' as const,
|
|
112
|
+
'mouse_click' as const,
|
|
113
|
+
'mouse_drag' as const,
|
|
114
|
+
'scroll' as const,
|
|
115
|
+
'type_text' as const,
|
|
116
|
+
'key' as const,
|
|
117
|
+
]),
|
|
118
|
+
mouseClickButtons: Object.freeze(['left' as const, 'right' as const, 'middle' as const]),
|
|
119
|
+
mouseDragButtons: Object.freeze(['left' as const, 'right' as const, 'middle' as const]),
|
|
120
|
+
windows: true,
|
|
121
|
+
// No display-relative region capture in cua-driver (its zoom is
|
|
122
|
+
// per-window and pads the region); the tool crops a full capture.
|
|
123
|
+
regionCapture: false,
|
|
124
|
+
uiTree: true,
|
|
125
|
+
})
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
/** How many driver processes this adapter has started (a restart after a crash counts). */
|
|
129
|
+
get processStarts(): number {
|
|
130
|
+
return this.client.starts
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
async getDisplayGeometry(): Promise<DisplayGeometry> {
|
|
134
|
+
const size = structured(await this.client.callTool('get_screen_size'), 'get_screen_size')
|
|
135
|
+
return {
|
|
136
|
+
width: requireNumber(size, 'width', 'get_screen_size'),
|
|
137
|
+
height: requireNumber(size, 'height', 'get_screen_size'),
|
|
138
|
+
scaleFactor: optionalNumber(size, 'scale_factor') ?? 1,
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
async execute(action: ComputerUseAction): Promise<ComputerUseResult> {
|
|
143
|
+
switch (action.type) {
|
|
144
|
+
case 'screenshot':
|
|
145
|
+
return { type: 'screenshot', result: await this.capture() }
|
|
146
|
+
case 'cursor_position': {
|
|
147
|
+
const point = structured(
|
|
148
|
+
await this.client.callTool('get_cursor_position'),
|
|
149
|
+
'get_cursor_position',
|
|
150
|
+
)
|
|
151
|
+
return {
|
|
152
|
+
type: 'cursor_position',
|
|
153
|
+
point: {
|
|
154
|
+
x: requireNumber(point, 'x', 'get_cursor_position'),
|
|
155
|
+
y: requireNumber(point, 'y', 'get_cursor_position'),
|
|
156
|
+
},
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
case 'mouse_move':
|
|
160
|
+
await this.client.callTool('move_cursor', {
|
|
161
|
+
scope: 'desktop',
|
|
162
|
+
x: action.to.x,
|
|
163
|
+
y: action.to.y,
|
|
164
|
+
})
|
|
165
|
+
return { type: 'ok' }
|
|
166
|
+
case 'mouse_click':
|
|
167
|
+
await this.pointer('click', {
|
|
168
|
+
scope: 'desktop',
|
|
169
|
+
x: action.at.x,
|
|
170
|
+
y: action.at.y,
|
|
171
|
+
button: action.button,
|
|
172
|
+
})
|
|
173
|
+
return { type: 'ok' }
|
|
174
|
+
case 'mouse_drag':
|
|
175
|
+
await this.pointer('drag', {
|
|
176
|
+
scope: 'desktop',
|
|
177
|
+
from_x: action.from.x,
|
|
178
|
+
from_y: action.from.y,
|
|
179
|
+
to_x: action.to.x,
|
|
180
|
+
to_y: action.to.y,
|
|
181
|
+
button: action.button,
|
|
182
|
+
duration_ms: DRAG.durationMs,
|
|
183
|
+
steps: DRAG.steps,
|
|
184
|
+
})
|
|
185
|
+
return { type: 'ok' }
|
|
186
|
+
case 'scroll': {
|
|
187
|
+
let remaining = Math.max(1, Math.trunc(action.amount))
|
|
188
|
+
while (remaining > 0) {
|
|
189
|
+
const ticks = Math.min(remaining, MAX_SCROLL_TICKS)
|
|
190
|
+
await this.pointer('scroll', {
|
|
191
|
+
scope: 'desktop',
|
|
192
|
+
x: action.at.x,
|
|
193
|
+
y: action.at.y,
|
|
194
|
+
direction: action.direction,
|
|
195
|
+
amount: ticks,
|
|
196
|
+
})
|
|
197
|
+
remaining -= ticks
|
|
198
|
+
}
|
|
199
|
+
return { type: 'ok' }
|
|
200
|
+
}
|
|
201
|
+
case 'type_text':
|
|
202
|
+
if (action.text.length > 0) {
|
|
203
|
+
await this.client.callTool('type_text', { scope: 'desktop', text: action.text })
|
|
204
|
+
}
|
|
205
|
+
return { type: 'ok' }
|
|
206
|
+
case 'key': {
|
|
207
|
+
const plan = translateKeyForCuaDriver(action.keys)
|
|
208
|
+
if (plan.tool === 'type_text') {
|
|
209
|
+
await this.client.callTool('type_text', { scope: 'desktop', text: plan.text })
|
|
210
|
+
} else if (plan.tool === 'press_key') {
|
|
211
|
+
await this.client.callTool('press_key', { scope: 'desktop', key: plan.key })
|
|
212
|
+
} else {
|
|
213
|
+
await this.client.callTool('hotkey', { scope: 'desktop', keys: [...plan.keys] })
|
|
214
|
+
}
|
|
215
|
+
return { type: 'ok' }
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
async listWindows(): Promise<readonly WindowInfo[]> {
|
|
221
|
+
const listed = structured(
|
|
222
|
+
await this.client.callTool('list_windows', {}, LIST_TIMEOUT_MS),
|
|
223
|
+
'list_windows',
|
|
224
|
+
)
|
|
225
|
+
const windows = toWindowInfos(listed.windows)
|
|
226
|
+
this.windowPids.clear()
|
|
227
|
+
for (const window of windows) this.windowPids.set(window.id, window.pid)
|
|
228
|
+
return windows
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
async focusWindow(id: string): Promise<FocusWindowResult> {
|
|
232
|
+
const hwnd = parseWindowId(id)
|
|
233
|
+
if (hwnd === undefined)
|
|
234
|
+
throw new Error(`computer-use: "${id}" is not a window id from list_windows.`)
|
|
235
|
+
let pid = this.windowPids.get(windowIdOf(hwnd))
|
|
236
|
+
if (pid === undefined) {
|
|
237
|
+
await this.listWindows()
|
|
238
|
+
pid = this.windowPids.get(windowIdOf(hwnd))
|
|
239
|
+
}
|
|
240
|
+
if (pid === undefined) {
|
|
241
|
+
throw new Error(`computer-use: no window ${id} is open now. List the windows again.`)
|
|
242
|
+
}
|
|
243
|
+
// cua-driver restores a minimized window, uses the AttachThreadInput
|
|
244
|
+
// route past Windows' foreground lock, and reads the foreground back.
|
|
245
|
+
const result = structured(
|
|
246
|
+
await this.client.callTool('bring_to_front', { pid, window_id: hwnd }),
|
|
247
|
+
'bring_to_front',
|
|
248
|
+
)
|
|
249
|
+
const now = parseWindowId(result.now_fg_hwnd)
|
|
250
|
+
const focusedId = now === undefined ? null : windowIdOf(now)
|
|
251
|
+
return { ok: focusedId === windowIdOf(hwnd), focusedId }
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
/**
|
|
255
|
+
* One window's controls. Without an id, the window in front — which,
|
|
256
|
+
* for an agent run from a terminal, is usually that terminal.
|
|
257
|
+
*/
|
|
258
|
+
async uiSnapshot(windowId?: string): Promise<UiSnapshot> {
|
|
259
|
+
const target = await this.resolveWindow(windowId)
|
|
260
|
+
const state = structured(
|
|
261
|
+
await this.client.callTool(
|
|
262
|
+
'get_window_state',
|
|
263
|
+
{
|
|
264
|
+
pid: target.pid,
|
|
265
|
+
window_id: target.hwnd,
|
|
266
|
+
include_screenshot: false,
|
|
267
|
+
max_elements: UI_MAX_ELEMENTS,
|
|
268
|
+
},
|
|
269
|
+
UI_TREE_TIMEOUT_MS,
|
|
270
|
+
),
|
|
271
|
+
'get_window_state',
|
|
272
|
+
)
|
|
273
|
+
const tree = toUiTree(state)
|
|
274
|
+
// A token names its snapshot, and cua-driver refuses a stale one, so
|
|
275
|
+
// only the latest snapshot's refs are kept.
|
|
276
|
+
this.uiRefs = new Map(
|
|
277
|
+
[...tree.refs].map(([ref, facts]) => [ref, { ...facts, pid: target.pid }]),
|
|
278
|
+
)
|
|
279
|
+
const title = typeof state.window_title === 'string' ? state.window_title : undefined
|
|
280
|
+
const app =
|
|
281
|
+
typeof state.app_name === 'string' ? state.app_name.replace(/\.exe$/i, '') : undefined
|
|
282
|
+
return {
|
|
283
|
+
windowId: windowIdOf(target.hwnd),
|
|
284
|
+
...(title !== undefined ? { title } : {}),
|
|
285
|
+
...(app !== undefined ? { app } : {}),
|
|
286
|
+
root: tree.root,
|
|
287
|
+
...(state.truncated === true ? { truncated: true } : {}),
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async uiAct(ref: string, action: UiElementAction, value?: string): Promise<UiActResult> {
|
|
292
|
+
const facts = this.uiRefs.get(ref)
|
|
293
|
+
if (!facts)
|
|
294
|
+
return {
|
|
295
|
+
ok: false,
|
|
296
|
+
detail: `${ref} is not a control of the latest UI snapshot; take a new one.`,
|
|
297
|
+
}
|
|
298
|
+
const { pid } = facts
|
|
299
|
+
try {
|
|
300
|
+
switch (action) {
|
|
301
|
+
case 'invoke':
|
|
302
|
+
case 'toggle':
|
|
303
|
+
case 'select':
|
|
304
|
+
case 'expand':
|
|
305
|
+
case 'collapse':
|
|
306
|
+
// cua-driver's click on an element token performs the control's
|
|
307
|
+
// own pattern in the background (Invoke, or a posted click at its
|
|
308
|
+
// centre), with no pointer move and no change of foreground.
|
|
309
|
+
return actResult(await this.client.callTool('click', { pid, element_token: ref }))
|
|
310
|
+
case 'set_value': {
|
|
311
|
+
const text = value ?? ''
|
|
312
|
+
try {
|
|
313
|
+
return actResult(
|
|
314
|
+
await this.client.callTool('set_value', { pid, element_token: ref, value: text }),
|
|
315
|
+
)
|
|
316
|
+
} catch (error) {
|
|
317
|
+
if (
|
|
318
|
+
!(error instanceof McpToolError) ||
|
|
319
|
+
!/does not implement ValuePattern/i.test(error.message)
|
|
320
|
+
)
|
|
321
|
+
throw error
|
|
322
|
+
// A classic Win32 edit reports no ValuePattern. Typing into it
|
|
323
|
+
// equals setting it only while it is empty.
|
|
324
|
+
if (facts.value !== undefined && facts.value.length > 0)
|
|
325
|
+
return {
|
|
326
|
+
ok: false,
|
|
327
|
+
detail:
|
|
328
|
+
'this field cannot be set directly and already holds text; click it, select its text (CTRL+A) and type the new text instead',
|
|
329
|
+
}
|
|
330
|
+
const typed = actResult(
|
|
331
|
+
await this.client.callTool('type_text', { pid, element_token: ref, text }),
|
|
332
|
+
)
|
|
333
|
+
return typed.ok
|
|
334
|
+
? { ok: true, detail: 'typed into the empty field, which has no settable value' }
|
|
335
|
+
: typed
|
|
336
|
+
}
|
|
337
|
+
}
|
|
338
|
+
case 'focus':
|
|
339
|
+
case 'scroll_into_view':
|
|
340
|
+
return {
|
|
341
|
+
ok: false,
|
|
342
|
+
detail: `this host cannot ${action === 'focus' ? 'focus' : 'scroll to'} a control by itself; invoke it or click it instead`,
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
} catch (error) {
|
|
346
|
+
if (error instanceof McpToolError) return { ok: false, detail: toolRefusal(error) }
|
|
347
|
+
throw error
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
async dispose(): Promise<void> {
|
|
352
|
+
await this.client.dispose()
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** A window id (or the window in front) → its handle and owning process. */
|
|
356
|
+
private async resolveWindow(
|
|
357
|
+
windowId: string | undefined,
|
|
358
|
+
): Promise<{ hwnd: number; pid: number }> {
|
|
359
|
+
if (windowId === undefined) {
|
|
360
|
+
const front = (await this.listWindows()).find((window) => window.focused)
|
|
361
|
+
if (!front)
|
|
362
|
+
throw new Error('computer-use: no window is in front; pass a window id from list_windows.')
|
|
363
|
+
return { hwnd: parseWindowId(front.id) as number, pid: front.pid }
|
|
364
|
+
}
|
|
365
|
+
const hwnd = parseWindowId(windowId)
|
|
366
|
+
if (hwnd === undefined)
|
|
367
|
+
throw new Error(`computer-use: "${windowId}" is not a window id from list_windows.`)
|
|
368
|
+
let pid = this.windowPids.get(windowIdOf(hwnd))
|
|
369
|
+
if (pid === undefined) {
|
|
370
|
+
await this.listWindows()
|
|
371
|
+
pid = this.windowPids.get(windowIdOf(hwnd))
|
|
372
|
+
}
|
|
373
|
+
if (pid === undefined)
|
|
374
|
+
throw new Error(`computer-use: no window ${windowId} is open now. List the windows again.`)
|
|
375
|
+
return { hwnd, pid }
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
private async pointer(tool: string, args: Record<string, unknown>): Promise<void> {
|
|
379
|
+
try {
|
|
380
|
+
await this.client.callTool(tool, args)
|
|
381
|
+
} catch (error) {
|
|
382
|
+
if (isDeliveredPointerAction(error)) return
|
|
383
|
+
throw error
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
private async capture(): Promise<ScreenshotResult> {
|
|
388
|
+
const result = await this.client.callTool('get_desktop_state', {}, CAPTURE_TIMEOUT_MS)
|
|
389
|
+
const image = result.content.find(
|
|
390
|
+
(part): part is { type: 'image'; data: string; mimeType: string } =>
|
|
391
|
+
part.type === 'image' && typeof (part as { data?: unknown }).data === 'string',
|
|
392
|
+
)
|
|
393
|
+
if (!image) throw new Error('cua-driver: get_desktop_state returned no image.')
|
|
394
|
+
const data = Buffer.from(image.data, 'base64')
|
|
395
|
+
const { width, height } = decodePngDims(data)
|
|
396
|
+
const facts = result.structuredContent ?? {}
|
|
397
|
+
const screenWidth = optionalNumber(facts, 'screen_width') ?? width
|
|
398
|
+
const screenHeight = optionalNumber(facts, 'screen_height') ?? height
|
|
399
|
+
if (width !== screenWidth || height !== screenHeight) {
|
|
400
|
+
// The host contract is physical pixels; a scaled capture would put
|
|
401
|
+
// every click somewhere else.
|
|
402
|
+
throw new Error(
|
|
403
|
+
`cua-driver: the capture is ${width}x${height} but the display is ${screenWidth}x${screenHeight}; refusing a scaled screenshot.`,
|
|
404
|
+
)
|
|
405
|
+
}
|
|
406
|
+
const display: DisplayInfo = {
|
|
407
|
+
id: typeof facts.display === 'string' ? facts.display : 'primary',
|
|
408
|
+
x: 0,
|
|
409
|
+
y: 0,
|
|
410
|
+
width: screenWidth,
|
|
411
|
+
height: screenHeight,
|
|
412
|
+
scaleFactor: optionalNumber(facts, 'scale_factor') ?? 1,
|
|
413
|
+
primary: true,
|
|
414
|
+
}
|
|
415
|
+
return { data, mimeType: 'image/png', width, height, display }
|
|
416
|
+
}
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
/**
|
|
420
|
+
* cua-driver activates the window under a desktop click, clicks, and then
|
|
421
|
+
* checks that the window — or another of its process — is still in front. A
|
|
422
|
+
* click that closes its own window (a dialog's "Don't Save", a close button)
|
|
423
|
+
* or starts another program leaves someone else in front, and the check
|
|
424
|
+
* fails although the click happened: "…was not foreground after the click".
|
|
425
|
+
* Reporting that as a failure would invite the model to click again, so it
|
|
426
|
+
* counts as done. The refusals that come before any input say "no input was
|
|
427
|
+
* sent" / "no mouse input was sent" and stay failures.
|
|
428
|
+
*/
|
|
429
|
+
export function isDeliveredPointerAction(error: unknown): boolean {
|
|
430
|
+
return (
|
|
431
|
+
error instanceof McpToolError &&
|
|
432
|
+
/foreground_unavailable/.test(error.message) &&
|
|
433
|
+
/not foreground after the/.test(error.message) &&
|
|
434
|
+
!/no (mouse )?input was sent/.test(error.message)
|
|
435
|
+
)
|
|
436
|
+
}
|
|
437
|
+
|
|
438
|
+
/**
|
|
439
|
+
* cua-driver's action result → the host's. `confirmed`, `partial` and
|
|
440
|
+
* `unverifiable` count as done: a background UIA Invoke is `unverifiable` by
|
|
441
|
+
* design (the control does not report back), and the screenshot the tool
|
|
442
|
+
* takes afterwards is where the model sees the effect.
|
|
443
|
+
*/
|
|
444
|
+
export function actResult(result: McpToolResult): UiActResult {
|
|
445
|
+
const facts = result.structuredContent ?? {}
|
|
446
|
+
switch (facts.effect) {
|
|
447
|
+
case 'suspected_noop':
|
|
448
|
+
return { ok: false, detail: 'the control did not change; the action may not have reached it' }
|
|
449
|
+
case 'refused': {
|
|
450
|
+
const refusal = facts.refusal as { message?: unknown } | undefined
|
|
451
|
+
return {
|
|
452
|
+
ok: false,
|
|
453
|
+
detail:
|
|
454
|
+
typeof refusal?.message === 'string' ? refusal.message : 'cua-driver refused the action',
|
|
455
|
+
}
|
|
456
|
+
}
|
|
457
|
+
default:
|
|
458
|
+
return { ok: true }
|
|
459
|
+
}
|
|
460
|
+
}
|
|
461
|
+
|
|
462
|
+
/** Why a tool call failed, in words that tell the model what to do next. */
|
|
463
|
+
function toolRefusal(error: McpToolError): string {
|
|
464
|
+
if (/stale/i.test(error.message))
|
|
465
|
+
return 'that control is from an older UI snapshot; take a new one'
|
|
466
|
+
return error.message.length > 300 ? `${error.message.slice(0, 299)}…` : error.message
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** `0x…` hex, the form `bring_to_front` reports and `WindowInfo.id` carries. */
|
|
470
|
+
export function windowIdOf(hwnd: number): string {
|
|
471
|
+
return `0x${hwnd.toString(16)}`
|
|
472
|
+
}
|
|
473
|
+
|
|
474
|
+
export function parseWindowId(value: unknown): number | undefined {
|
|
475
|
+
if (typeof value === 'number') return Number.isSafeInteger(value) && value > 0 ? value : undefined
|
|
476
|
+
if (typeof value !== 'string') return undefined
|
|
477
|
+
const text = value.trim().toLowerCase()
|
|
478
|
+
const parsed = /^0x[0-9a-f]+$/.test(text)
|
|
479
|
+
? Number.parseInt(text.slice(2), 16)
|
|
480
|
+
: /^\d+$/.test(text)
|
|
481
|
+
? Number.parseInt(text, 10)
|
|
482
|
+
: Number.NaN
|
|
483
|
+
return Number.isSafeInteger(parsed) && parsed > 0 ? parsed : undefined
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
interface CuaWindow {
|
|
487
|
+
readonly window_id?: unknown
|
|
488
|
+
readonly pid?: unknown
|
|
489
|
+
readonly app_name?: unknown
|
|
490
|
+
readonly title?: unknown
|
|
491
|
+
readonly bounds?: { x?: unknown; y?: unknown; width?: unknown; height?: unknown }
|
|
492
|
+
readonly minimized?: unknown
|
|
493
|
+
readonly is_on_screen?: unknown
|
|
494
|
+
readonly z_index?: unknown
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
/**
|
|
498
|
+
* cua-driver's `list_windows` records → the host's `WindowInfo`, front to back.
|
|
499
|
+
*
|
|
500
|
+
* Dropped: untitled windows, cua-driver's own (its cursor overlay covers the
|
|
501
|
+
* whole screen), the shell's `Program Manager` desktop, and windows a pixel
|
|
502
|
+
* wide or tall. `focused` is the front-most window that is not minimized —
|
|
503
|
+
* cua-driver does not report the foreground window itself, and the
|
|
504
|
+
* foreground window is the front of the non-topmost z-order.
|
|
505
|
+
*/
|
|
506
|
+
export function toWindowInfos(raw: unknown): WindowInfo[] {
|
|
507
|
+
if (!Array.isArray(raw)) return []
|
|
508
|
+
const kept: { info: Omit<WindowInfo, 'focused'>; z: number }[] = []
|
|
509
|
+
for (const entry of raw as CuaWindow[]) {
|
|
510
|
+
const hwnd = parseWindowId(entry.window_id)
|
|
511
|
+
const title = typeof entry.title === 'string' ? entry.title : ''
|
|
512
|
+
const app = typeof entry.app_name === 'string' ? entry.app_name : ''
|
|
513
|
+
const pid = typeof entry.pid === 'number' ? entry.pid : undefined
|
|
514
|
+
const bounds = entry.bounds
|
|
515
|
+
if (hwnd === undefined || pid === undefined || !bounds) continue
|
|
516
|
+
if (title.trim().length === 0) continue
|
|
517
|
+
if (app.toLowerCase() === 'cua-driver.exe') continue
|
|
518
|
+
if (app.toLowerCase() === 'explorer.exe' && title === 'Program Manager') continue
|
|
519
|
+
const width = typeof bounds.width === 'number' ? bounds.width : 0
|
|
520
|
+
const height = typeof bounds.height === 'number' ? bounds.height : 0
|
|
521
|
+
if (width <= 1 || height <= 1) continue
|
|
522
|
+
kept.push({
|
|
523
|
+
info: {
|
|
524
|
+
id: windowIdOf(hwnd),
|
|
525
|
+
title,
|
|
526
|
+
app: app.replace(/\.exe$/i, ''),
|
|
527
|
+
pid,
|
|
528
|
+
bounds: {
|
|
529
|
+
x: typeof bounds.x === 'number' ? bounds.x : 0,
|
|
530
|
+
y: typeof bounds.y === 'number' ? bounds.y : 0,
|
|
531
|
+
width,
|
|
532
|
+
height,
|
|
533
|
+
},
|
|
534
|
+
minimized: entry.minimized === true,
|
|
535
|
+
},
|
|
536
|
+
z: typeof entry.z_index === 'number' ? entry.z_index : Number.NEGATIVE_INFINITY,
|
|
537
|
+
})
|
|
538
|
+
}
|
|
539
|
+
// Stable: records without a z-index keep cua-driver's order, after the rest.
|
|
540
|
+
const ordered = kept
|
|
541
|
+
.map((entry, index) => ({ ...entry, index }))
|
|
542
|
+
.sort((a, b) => (b.z === a.z ? a.index - b.index : b.z - a.z))
|
|
543
|
+
const front = ordered.find((entry) => !entry.info.minimized && Number.isFinite(entry.z))
|
|
544
|
+
return ordered.map((entry) => ({ ...entry.info, focused: entry === front }))
|
|
545
|
+
}
|
|
546
|
+
|
|
547
|
+
function structured(result: McpToolResult, tool: string): Record<string, unknown> {
|
|
548
|
+
if (!result.structuredContent)
|
|
549
|
+
throw new Error(`cua-driver: ${tool} returned no structured result.`)
|
|
550
|
+
return result.structuredContent
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
function requireNumber(source: Record<string, unknown>, key: string, tool: string): number {
|
|
554
|
+
const value = source[key]
|
|
555
|
+
if (typeof value !== 'number' || !Number.isFinite(value)) {
|
|
556
|
+
throw new Error(`cua-driver: ${tool} did not report ${key}.`)
|
|
557
|
+
}
|
|
558
|
+
return value
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
function optionalNumber(source: Record<string, unknown>, key: string): number | undefined {
|
|
562
|
+
const value = source[key]
|
|
563
|
+
return typeof value === 'number' && Number.isFinite(value) ? value : undefined
|
|
564
|
+
}
|
|
565
|
+
|
|
566
|
+
function decodePngDims(buffer: Buffer): { width: number; height: number } {
|
|
567
|
+
if (buffer.length < 24 || buffer.readUInt32BE(12) !== 0x49484452) {
|
|
568
|
+
throw new Error('cua-driver: the screenshot is not a PNG.')
|
|
569
|
+
}
|
|
570
|
+
return { width: buffer.readUInt32BE(16), height: buffer.readUInt32BE(20) }
|
|
571
|
+
}
|