@namzu/computer-use 2.0.2 → 3.1.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 +12 -0
- package/README.md +47 -6
- package/dist/SubprocessComputerUseHost.d.ts +4 -1
- package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
- package/dist/SubprocessComputerUseHost.js +20 -0
- package/dist/SubprocessComputerUseHost.js.map +1 -1
- package/dist/adapters/cua-driver/adapter.d.ts +29 -8
- package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
- package/dist/adapters/cua-driver/adapter.js +364 -28
- package/dist/adapters/cua-driver/adapter.js.map +1 -1
- package/dist/adapters/cua-driver/client.d.ts +8 -2
- package/dist/adapters/cua-driver/client.d.ts.map +1 -1
- package/dist/adapters/cua-driver/client.js +18 -5
- package/dist/adapters/cua-driver/client.js.map +1 -1
- package/dist/adapters/types.d.ts +5 -1
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/adapters/types.js.map +1 -1
- package/package.json +2 -2
- package/src/SubprocessComputerUseHost.ts +21 -0
- package/src/adapters/cua-driver/adapter.ts +462 -40
- package/src/adapters/cua-driver/client.ts +26 -4
- package/src/adapters/types.ts +6 -0
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { randomUUID } from 'node:crypto';
|
|
1
2
|
import { McpStdioClient, McpToolError, } from './client.js';
|
|
2
3
|
import { translateKeyForCuaDriver } from './keys.js';
|
|
3
4
|
import { toUiTree } from './ui-tree.js';
|
|
@@ -11,14 +12,40 @@ const UI_MAX_ELEMENTS = 1_500;
|
|
|
11
12
|
const MAX_SCROLL_TICKS = 50;
|
|
12
13
|
/** A drag glides through intermediate moves; many targets ignore one that teleports. */
|
|
13
14
|
const DRAG = { durationMs: 250, steps: 12 };
|
|
15
|
+
async function disableAgentCursor(call) {
|
|
16
|
+
// Best effort: a build without the tool still works, only slower.
|
|
17
|
+
await call('set_agent_cursor_enabled', { enabled: false }).catch(() => undefined);
|
|
18
|
+
}
|
|
19
|
+
/** Replace process-local driver tokens before any UI tree leaves this adapter. */
|
|
20
|
+
function withOpaqueRefs(element, refFor) {
|
|
21
|
+
return Object.freeze({
|
|
22
|
+
...element,
|
|
23
|
+
ref: element.ref ? refFor(element.ref) : '',
|
|
24
|
+
...(element.children
|
|
25
|
+
? {
|
|
26
|
+
children: Object.freeze(element.children.map((child) => withOpaqueRefs(child, refFor))),
|
|
27
|
+
}
|
|
28
|
+
: {}),
|
|
29
|
+
});
|
|
30
|
+
}
|
|
14
31
|
export class CuaDriverAdapter {
|
|
15
32
|
capabilities;
|
|
16
33
|
backend;
|
|
17
34
|
client;
|
|
18
35
|
/** Window id → owning pid, from the latest list; `bring_to_front` needs both. */
|
|
19
36
|
windowPids = new Map();
|
|
20
|
-
/**
|
|
37
|
+
/** cua-driver's screenshot resize registry is per PID, so only this capture may drive input. */
|
|
38
|
+
windowFrame;
|
|
39
|
+
/** Capture and scoped input must not race over cua-driver's per-PID resize ratio. */
|
|
40
|
+
windowOperation = Promise.resolve();
|
|
41
|
+
/** Only refs from the latest snapshot may address driver tokens. */
|
|
21
42
|
uiRefs = new Map();
|
|
43
|
+
uiRefNamespace = randomUUID();
|
|
44
|
+
nextSnapshot = 0;
|
|
45
|
+
/** A successful revival invalidates refusals from the previous lifecycle episode. */
|
|
46
|
+
sessionGeneration = 0;
|
|
47
|
+
/** Share one revival among calls refused by the same expired implicit session. */
|
|
48
|
+
sessionRevival;
|
|
22
49
|
constructor(options) {
|
|
23
50
|
this.backend = `cua-driver${options.version ? ` ${options.version}` : ''}`;
|
|
24
51
|
this.client = new McpStdioClient({
|
|
@@ -30,10 +57,7 @@ export class CuaDriverAdapter {
|
|
|
30
57
|
requestTimeoutMs: options.requestTimeoutMs ?? 15_000,
|
|
31
58
|
startTimeoutMs: options.startTimeoutMs ?? 30_000,
|
|
32
59
|
spawnProcess: options.spawnProcess,
|
|
33
|
-
afterStart:
|
|
34
|
-
// Best effort: a build without the tool still works, only slower.
|
|
35
|
-
await call('set_agent_cursor_enabled', { enabled: false }).catch(() => undefined);
|
|
36
|
-
},
|
|
60
|
+
afterStart: disableAgentCursor,
|
|
37
61
|
});
|
|
38
62
|
this.capabilities = Object.freeze({
|
|
39
63
|
displayServer: 'win32',
|
|
@@ -56,6 +80,8 @@ export class CuaDriverAdapter {
|
|
|
56
80
|
mouseClickButtons: Object.freeze(['left', 'right', 'middle']),
|
|
57
81
|
mouseDragButtons: Object.freeze(['left', 'right', 'middle']),
|
|
58
82
|
windows: true,
|
|
83
|
+
windowCapture: true,
|
|
84
|
+
windowScroll: false,
|
|
59
85
|
// No display-relative region capture in cua-driver (its zoom is
|
|
60
86
|
// per-window and pads the region); the tool crops a full capture.
|
|
61
87
|
regionCapture: false,
|
|
@@ -67,7 +93,7 @@ export class CuaDriverAdapter {
|
|
|
67
93
|
return this.client.starts;
|
|
68
94
|
}
|
|
69
95
|
async getDisplayGeometry() {
|
|
70
|
-
const size = structured(await this.
|
|
96
|
+
const size = structured(await this.callTool('get_screen_size'), 'get_screen_size');
|
|
71
97
|
return {
|
|
72
98
|
width: requireNumber(size, 'width', 'get_screen_size'),
|
|
73
99
|
height: requireNumber(size, 'height', 'get_screen_size'),
|
|
@@ -79,7 +105,7 @@ export class CuaDriverAdapter {
|
|
|
79
105
|
case 'screenshot':
|
|
80
106
|
return { type: 'screenshot', result: await this.capture() };
|
|
81
107
|
case 'cursor_position': {
|
|
82
|
-
const point = structured(await this.
|
|
108
|
+
const point = structured(await this.callTool('get_cursor_position'), 'get_cursor_position');
|
|
83
109
|
return {
|
|
84
110
|
type: 'cursor_position',
|
|
85
111
|
point: {
|
|
@@ -89,7 +115,7 @@ export class CuaDriverAdapter {
|
|
|
89
115
|
};
|
|
90
116
|
}
|
|
91
117
|
case 'mouse_move':
|
|
92
|
-
await this.
|
|
118
|
+
await this.callTool('move_cursor', {
|
|
93
119
|
scope: 'desktop',
|
|
94
120
|
x: action.to.x,
|
|
95
121
|
y: action.to.y,
|
|
@@ -132,26 +158,35 @@ export class CuaDriverAdapter {
|
|
|
132
158
|
}
|
|
133
159
|
case 'type_text':
|
|
134
160
|
if (action.text.length > 0) {
|
|
135
|
-
await this.
|
|
161
|
+
await this.callTool('type_text', {
|
|
162
|
+
scope: 'desktop',
|
|
163
|
+
text: action.text,
|
|
164
|
+
});
|
|
136
165
|
}
|
|
137
166
|
return { type: 'ok' };
|
|
138
167
|
case 'key': {
|
|
139
168
|
const plan = translateKeyForCuaDriver(action.keys);
|
|
140
169
|
if (plan.tool === 'type_text') {
|
|
141
|
-
await this.
|
|
170
|
+
await this.callTool('type_text', {
|
|
171
|
+
scope: 'desktop',
|
|
172
|
+
text: plan.text,
|
|
173
|
+
});
|
|
142
174
|
}
|
|
143
175
|
else if (plan.tool === 'press_key') {
|
|
144
|
-
await this.
|
|
176
|
+
await this.callTool('press_key', { scope: 'desktop', key: plan.key });
|
|
145
177
|
}
|
|
146
178
|
else {
|
|
147
|
-
await this.
|
|
179
|
+
await this.callTool('hotkey', {
|
|
180
|
+
scope: 'desktop',
|
|
181
|
+
keys: [...plan.keys],
|
|
182
|
+
});
|
|
148
183
|
}
|
|
149
184
|
return { type: 'ok' };
|
|
150
185
|
}
|
|
151
186
|
}
|
|
152
187
|
}
|
|
153
188
|
async listWindows() {
|
|
154
|
-
const listed = structured(await this.
|
|
189
|
+
const listed = structured(await this.callTool('list_windows', {}, LIST_TIMEOUT_MS), 'list_windows');
|
|
155
190
|
const windows = toWindowInfos(listed.windows);
|
|
156
191
|
this.windowPids.clear();
|
|
157
192
|
for (const window of windows)
|
|
@@ -172,34 +207,216 @@ export class CuaDriverAdapter {
|
|
|
172
207
|
}
|
|
173
208
|
// cua-driver restores a minimized window, uses the AttachThreadInput
|
|
174
209
|
// route past Windows' foreground lock, and reads the foreground back.
|
|
175
|
-
const result = structured(await this.
|
|
210
|
+
const result = structured(await this.callTool('bring_to_front', { pid, window_id: hwnd }), 'bring_to_front');
|
|
176
211
|
const now = parseWindowId(result.now_fg_hwnd);
|
|
177
212
|
const focusedId = now === undefined ? null : windowIdOf(now);
|
|
178
213
|
return { ok: focusedId === windowIdOf(hwnd), focusedId };
|
|
179
214
|
}
|
|
215
|
+
async captureWindow(id) {
|
|
216
|
+
return this.serializeWindowOperation(() => this.captureWindowInternal(id));
|
|
217
|
+
}
|
|
218
|
+
async captureWindowInternal(id) {
|
|
219
|
+
const target = await this.resolveWindow(id);
|
|
220
|
+
// A failed or overlapping capture invalidates the old resize ratio even
|
|
221
|
+
// if the driver returned no image. Never let it address a later action.
|
|
222
|
+
this.windowFrame = undefined;
|
|
223
|
+
let captureStarts = 0;
|
|
224
|
+
let captureGeneration = this.sessionGeneration;
|
|
225
|
+
const result = await this.callTool('get_window_state', {
|
|
226
|
+
pid: target.pid,
|
|
227
|
+
window_id: target.hwnd,
|
|
228
|
+
include_accessibility_tree: false,
|
|
229
|
+
include_screenshot: true,
|
|
230
|
+
}, CAPTURE_TIMEOUT_MS, undefined, (starts) => {
|
|
231
|
+
captureStarts = starts;
|
|
232
|
+
captureGeneration = this.sessionGeneration;
|
|
233
|
+
});
|
|
234
|
+
const facts = structured(result, 'get_window_state');
|
|
235
|
+
if (facts.pid !== target.pid || parseWindowId(facts.window_id) !== target.hwnd)
|
|
236
|
+
throw new Error('cua-driver: the window capture identity did not match the requested PID and HWND.');
|
|
237
|
+
const image = result.content.find((part) => part.type === 'image' && typeof part.data === 'string');
|
|
238
|
+
if (!image || image.mimeType !== 'image/png')
|
|
239
|
+
throw new Error(`cua-driver: window ${id} returned no PNG${typeof facts.screenshot_error === 'string' ? `: ${facts.screenshot_error}` : ''}.`);
|
|
240
|
+
const data = Buffer.from(image.data, 'base64');
|
|
241
|
+
const { width, height } = decodePngDims(data);
|
|
242
|
+
if (width < 1 ||
|
|
243
|
+
height < 1 ||
|
|
244
|
+
facts.screenshot_width !== width ||
|
|
245
|
+
facts.screenshot_height !== height)
|
|
246
|
+
throw new Error('cua-driver: window PNG dimensions did not match its capture metadata.');
|
|
247
|
+
const bounds = windowBounds(facts.window_bounds);
|
|
248
|
+
if (!bounds)
|
|
249
|
+
throw new Error('cua-driver: window capture returned no valid window bounds.');
|
|
250
|
+
const windows = await this.listWindows();
|
|
251
|
+
if (captureStarts === 0 ||
|
|
252
|
+
this.client.starts !== captureStarts ||
|
|
253
|
+
this.sessionGeneration !== captureGeneration)
|
|
254
|
+
throw new Error('cua-driver: the driver session changed after the window capture; take a new screenshot.');
|
|
255
|
+
const listed = windows.find((window) => window.id === windowIdOf(target.hwnd));
|
|
256
|
+
if (!listed ||
|
|
257
|
+
listed.pid !== target.pid ||
|
|
258
|
+
listed.minimized ||
|
|
259
|
+
!sameBounds(listed.bounds, bounds))
|
|
260
|
+
throw new Error(`cua-driver: window ${id} moved, closed or was minimized during capture; take a new screenshot.`);
|
|
261
|
+
const frame = {
|
|
262
|
+
id: randomUUID(),
|
|
263
|
+
window: listed,
|
|
264
|
+
width,
|
|
265
|
+
height,
|
|
266
|
+
processStarts: captureStarts,
|
|
267
|
+
generation: captureGeneration,
|
|
268
|
+
};
|
|
269
|
+
this.windowFrame = frame;
|
|
270
|
+
const coverage = facts.capture_coverage;
|
|
271
|
+
const browserChrome = typeof coverage === 'object' && coverage !== null && 'browser_chrome' in coverage
|
|
272
|
+
? coverage.browser_chrome
|
|
273
|
+
: undefined;
|
|
274
|
+
const captureCoverage = typeof browserChrome === 'object' &&
|
|
275
|
+
browserChrome !== null &&
|
|
276
|
+
'status' in browserChrome &&
|
|
277
|
+
typeof browserChrome.status === 'string'
|
|
278
|
+
? browserChrome.status
|
|
279
|
+
: undefined;
|
|
280
|
+
return {
|
|
281
|
+
data,
|
|
282
|
+
mimeType: 'image/png',
|
|
283
|
+
width,
|
|
284
|
+
height,
|
|
285
|
+
window: listed,
|
|
286
|
+
captureId: frame.id,
|
|
287
|
+
...(captureCoverage ? { captureCoverage } : {}),
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
async executeWindow(captureId, action) {
|
|
291
|
+
return this.serializeWindowOperation(() => this.executeWindowInternal(captureId, action));
|
|
292
|
+
}
|
|
293
|
+
async executeWindowInternal(captureId, action) {
|
|
294
|
+
const frame = this.windowFrame;
|
|
295
|
+
if (!frame || frame.id !== captureId)
|
|
296
|
+
throw new Error('computer-use: this window screenshot is stale; capture the window again before acting.');
|
|
297
|
+
const point = (value) => {
|
|
298
|
+
if (!Number.isInteger(value.x) ||
|
|
299
|
+
!Number.isInteger(value.y) ||
|
|
300
|
+
value.x < 0 ||
|
|
301
|
+
value.y < 0 ||
|
|
302
|
+
value.x >= frame.width ||
|
|
303
|
+
value.y >= frame.height)
|
|
304
|
+
throw new Error('computer-use: window action coordinates are outside the captured PNG.');
|
|
305
|
+
};
|
|
306
|
+
if (action.type === 'mouse_click' || action.type === 'scroll')
|
|
307
|
+
point(action.at);
|
|
308
|
+
if (action.type === 'mouse_drag') {
|
|
309
|
+
point(action.from);
|
|
310
|
+
point(action.to);
|
|
311
|
+
}
|
|
312
|
+
const target = {
|
|
313
|
+
scope: 'window',
|
|
314
|
+
pid: frame.window.pid,
|
|
315
|
+
window_id: parseWindowId(frame.window.id),
|
|
316
|
+
};
|
|
317
|
+
const call = async (name, args) => {
|
|
318
|
+
const windows = await this.listWindows();
|
|
319
|
+
const current = windows.find((window) => window.id === frame.window.id);
|
|
320
|
+
if (!current ||
|
|
321
|
+
current.pid !== frame.window.pid ||
|
|
322
|
+
current.minimized ||
|
|
323
|
+
!sameBounds(current.bounds, frame.window.bounds) ||
|
|
324
|
+
this.windowFrame !== frame ||
|
|
325
|
+
this.sessionGeneration !== frame.generation ||
|
|
326
|
+
this.client.starts !== frame.processStarts)
|
|
327
|
+
throw new Error('computer-use: the captured window changed or its driver restarted; take a new window screenshot.');
|
|
328
|
+
await this.callTool(name, { ...target, ...args }, undefined, undefined, undefined, frame);
|
|
329
|
+
};
|
|
330
|
+
switch (action.type) {
|
|
331
|
+
case 'mouse_click':
|
|
332
|
+
try {
|
|
333
|
+
await call('click', { x: action.at.x, y: action.at.y, button: action.button });
|
|
334
|
+
}
|
|
335
|
+
catch (error) {
|
|
336
|
+
if (!isDeliveredPointerAction(error))
|
|
337
|
+
throw windowPointerRefusal(error);
|
|
338
|
+
}
|
|
339
|
+
return;
|
|
340
|
+
case 'mouse_drag':
|
|
341
|
+
try {
|
|
342
|
+
await call('drag', {
|
|
343
|
+
from_x: action.from.x,
|
|
344
|
+
from_y: action.from.y,
|
|
345
|
+
to_x: action.to.x,
|
|
346
|
+
to_y: action.to.y,
|
|
347
|
+
button: action.button,
|
|
348
|
+
duration_ms: DRAG.durationMs,
|
|
349
|
+
steps: DRAG.steps,
|
|
350
|
+
});
|
|
351
|
+
}
|
|
352
|
+
catch (error) {
|
|
353
|
+
throw windowPointerRefusal(error);
|
|
354
|
+
}
|
|
355
|
+
return;
|
|
356
|
+
case 'scroll':
|
|
357
|
+
throw new Error('computer-use: window pixel scrolling is unavailable on this Windows driver; use foreground PAGE_DOWN or ARROW_DOWN in this window, or take a deliberate display screenshot before display scrolling.');
|
|
358
|
+
case 'type_text':
|
|
359
|
+
if (action.text.length > 0)
|
|
360
|
+
await call('type_text', {
|
|
361
|
+
text: action.text,
|
|
362
|
+
...(action.delivery_mode ? { delivery_mode: action.delivery_mode } : {}),
|
|
363
|
+
});
|
|
364
|
+
return;
|
|
365
|
+
case 'key': {
|
|
366
|
+
const plan = translateKeyForCuaDriver(action.keys);
|
|
367
|
+
const delivery = action.delivery_mode ? { delivery_mode: action.delivery_mode } : {};
|
|
368
|
+
if (plan.tool === 'type_text')
|
|
369
|
+
await call('type_text', { text: plan.text, ...delivery });
|
|
370
|
+
else if (plan.tool === 'press_key')
|
|
371
|
+
await call('press_key', { key: plan.key, ...delivery });
|
|
372
|
+
else
|
|
373
|
+
await call('hotkey', { keys: [...plan.keys], ...delivery });
|
|
374
|
+
return;
|
|
375
|
+
}
|
|
376
|
+
}
|
|
377
|
+
}
|
|
180
378
|
/**
|
|
181
379
|
* One window's controls. Without an id, the window in front — which,
|
|
182
380
|
* for an agent run from a terminal, is usually that terminal.
|
|
183
381
|
*/
|
|
184
382
|
async uiSnapshot(windowId) {
|
|
185
383
|
const target = await this.resolveWindow(windowId);
|
|
186
|
-
|
|
384
|
+
let processStarts = 0;
|
|
385
|
+
let snapshotGeneration = this.sessionGeneration;
|
|
386
|
+
const state = structured(await this.callTool('get_window_state', {
|
|
187
387
|
pid: target.pid,
|
|
188
388
|
window_id: target.hwnd,
|
|
189
389
|
include_screenshot: false,
|
|
190
390
|
max_elements: UI_MAX_ELEMENTS,
|
|
191
|
-
}, UI_TREE_TIMEOUT_MS
|
|
391
|
+
}, UI_TREE_TIMEOUT_MS, undefined, (starts) => {
|
|
392
|
+
processStarts = starts;
|
|
393
|
+
snapshotGeneration = this.sessionGeneration;
|
|
394
|
+
}), 'get_window_state');
|
|
395
|
+
if (snapshotGeneration !== this.sessionGeneration || processStarts === 0)
|
|
396
|
+
throw new McpToolError('get_window_state', 'stale UI snapshot; take a new one');
|
|
192
397
|
const tree = toUiTree(state);
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
398
|
+
const snapshot = ++this.nextSnapshot;
|
|
399
|
+
const refs = new Map();
|
|
400
|
+
let ordinal = 0;
|
|
401
|
+
const root = withOpaqueRefs(tree.root, (token) => {
|
|
402
|
+
const ref = `cua-ui:${this.uiRefNamespace}:${snapshot}:${++ordinal}`;
|
|
403
|
+
refs.set(ref, {
|
|
404
|
+
...tree.refs.get(token),
|
|
405
|
+
token,
|
|
406
|
+
pid: target.pid,
|
|
407
|
+
generation: snapshotGeneration,
|
|
408
|
+
processStarts,
|
|
409
|
+
});
|
|
410
|
+
return ref;
|
|
411
|
+
});
|
|
412
|
+
this.uiRefs = refs;
|
|
196
413
|
const title = typeof state.window_title === 'string' ? state.window_title : undefined;
|
|
197
414
|
const app = typeof state.app_name === 'string' ? state.app_name.replace(/\.exe$/i, '') : undefined;
|
|
198
415
|
return {
|
|
199
416
|
windowId: windowIdOf(target.hwnd),
|
|
200
417
|
...(title !== undefined ? { title } : {}),
|
|
201
418
|
...(app !== undefined ? { app } : {}),
|
|
202
|
-
root
|
|
419
|
+
root,
|
|
203
420
|
...(state.truncated === true ? { truncated: true } : {}),
|
|
204
421
|
};
|
|
205
422
|
}
|
|
@@ -210,7 +427,8 @@ export class CuaDriverAdapter {
|
|
|
210
427
|
ok: false,
|
|
211
428
|
detail: `${ref} is not a control of the latest UI snapshot; take a new one.`,
|
|
212
429
|
};
|
|
213
|
-
const { pid } = facts;
|
|
430
|
+
const { pid, token } = facts;
|
|
431
|
+
const uiRef = { ref, facts };
|
|
214
432
|
try {
|
|
215
433
|
switch (action) {
|
|
216
434
|
case 'invoke':
|
|
@@ -221,11 +439,11 @@ export class CuaDriverAdapter {
|
|
|
221
439
|
// cua-driver's click on an element token performs the control's
|
|
222
440
|
// own pattern in the background (Invoke, or a posted click at its
|
|
223
441
|
// centre), with no pointer move and no change of foreground.
|
|
224
|
-
return actResult(await this.
|
|
442
|
+
return actResult(await this.callTool('click', { pid, element_token: token }, undefined, uiRef));
|
|
225
443
|
case 'set_value': {
|
|
226
444
|
const text = value ?? '';
|
|
227
445
|
try {
|
|
228
|
-
return actResult(await this.
|
|
446
|
+
return actResult(await this.callTool('set_value', { pid, element_token: token, value: text }, undefined, uiRef));
|
|
229
447
|
}
|
|
230
448
|
catch (error) {
|
|
231
449
|
if (!(error instanceof McpToolError) ||
|
|
@@ -238,9 +456,12 @@ export class CuaDriverAdapter {
|
|
|
238
456
|
ok: false,
|
|
239
457
|
detail: 'this field cannot be set directly and already holds text; click it, select its text (CTRL+A) and type the new text instead',
|
|
240
458
|
};
|
|
241
|
-
const typed = actResult(await this.
|
|
459
|
+
const typed = actResult(await this.callTool('type_text', { pid, element_token: token, text }, undefined, uiRef));
|
|
242
460
|
return typed.ok
|
|
243
|
-
? {
|
|
461
|
+
? {
|
|
462
|
+
ok: true,
|
|
463
|
+
detail: 'typed into the empty field, which has no settable value',
|
|
464
|
+
}
|
|
244
465
|
: typed;
|
|
245
466
|
}
|
|
246
467
|
}
|
|
@@ -261,6 +482,81 @@ export class CuaDriverAdapter {
|
|
|
261
482
|
async dispose() {
|
|
262
483
|
await this.client.dispose();
|
|
263
484
|
}
|
|
485
|
+
async serializeWindowOperation(operation) {
|
|
486
|
+
const previous = this.windowOperation;
|
|
487
|
+
let release = () => undefined;
|
|
488
|
+
this.windowOperation = new Promise((resolve) => {
|
|
489
|
+
release = resolve;
|
|
490
|
+
});
|
|
491
|
+
await previous;
|
|
492
|
+
try {
|
|
493
|
+
return await operation();
|
|
494
|
+
}
|
|
495
|
+
finally {
|
|
496
|
+
release();
|
|
497
|
+
}
|
|
498
|
+
}
|
|
499
|
+
/**
|
|
500
|
+
* cua-driver refuses an expired implicit session before dispatch, with a
|
|
501
|
+
* structured `session_ended` code. Only that exact refusal is safe to replay.
|
|
502
|
+
* A lost response or transport failure still has an unknown action outcome.
|
|
503
|
+
*/
|
|
504
|
+
async callTool(name, args = {}, timeoutMs, uiRef, onProcess, windowFrame) {
|
|
505
|
+
await this.sessionRevival;
|
|
506
|
+
if (windowFrame &&
|
|
507
|
+
(this.windowFrame !== windowFrame ||
|
|
508
|
+
windowFrame.generation !== this.sessionGeneration ||
|
|
509
|
+
windowFrame.processStarts !== this.client.starts))
|
|
510
|
+
throw new McpToolError(name, 'stale window screenshot; capture the window again');
|
|
511
|
+
if (uiRef &&
|
|
512
|
+
(this.uiRefs.get(uiRef.ref) !== uiRef.facts ||
|
|
513
|
+
uiRef.facts.generation !== this.sessionGeneration))
|
|
514
|
+
throw new McpToolError(name, 'stale UI snapshot; take a new one');
|
|
515
|
+
const generation = this.sessionGeneration;
|
|
516
|
+
try {
|
|
517
|
+
return await this.client.callTool(name, args, timeoutMs, {
|
|
518
|
+
...(uiRef || windowFrame
|
|
519
|
+
? { expectedStarts: uiRef?.facts.processStarts ?? windowFrame?.processStarts }
|
|
520
|
+
: {}),
|
|
521
|
+
...(onProcess ? { onProcess } : {}),
|
|
522
|
+
});
|
|
523
|
+
}
|
|
524
|
+
catch (error) {
|
|
525
|
+
if (!isEndedSessionRefusal(error))
|
|
526
|
+
throw error;
|
|
527
|
+
// The refusal proves the old session's element tokens are invalid,
|
|
528
|
+
// even if start_session fails and there is no successful revival.
|
|
529
|
+
if (this.sessionGeneration === generation)
|
|
530
|
+
this.uiRefs.clear();
|
|
531
|
+
this.windowFrame = undefined;
|
|
532
|
+
await this.reviveSession(generation);
|
|
533
|
+
// Element tokens belong to the old snapshot. A new lifecycle session
|
|
534
|
+
// needs a new tree before a control can be addressed again.
|
|
535
|
+
if (uiRef)
|
|
536
|
+
throw new McpToolError(name, 'stale UI snapshot; take a new one');
|
|
537
|
+
if (windowFrame)
|
|
538
|
+
throw new McpToolError(name, 'stale window screenshot; capture the window again');
|
|
539
|
+
// One retry only. A second refusal or an unacknowledged action is
|
|
540
|
+
// returned to the host without any further automatic replay.
|
|
541
|
+
return this.client.callTool(name, args, timeoutMs, { onProcess });
|
|
542
|
+
}
|
|
543
|
+
}
|
|
544
|
+
async reviveSession(generation) {
|
|
545
|
+
if (this.sessionGeneration !== generation)
|
|
546
|
+
return;
|
|
547
|
+
if (!this.sessionRevival) {
|
|
548
|
+
this.sessionRevival = (async () => {
|
|
549
|
+
await this.client.callTool('start_session');
|
|
550
|
+
await disableAgentCursor((name, args) => this.client.callTool(name, args));
|
|
551
|
+
this.uiRefs.clear();
|
|
552
|
+
this.windowFrame = undefined;
|
|
553
|
+
this.sessionGeneration++;
|
|
554
|
+
})().finally(() => {
|
|
555
|
+
this.sessionRevival = undefined;
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
await this.sessionRevival;
|
|
559
|
+
}
|
|
264
560
|
/** A window id (or the window in front) → its handle and owning process. */
|
|
265
561
|
async resolveWindow(windowId) {
|
|
266
562
|
if (windowId === undefined) {
|
|
@@ -283,7 +579,7 @@ export class CuaDriverAdapter {
|
|
|
283
579
|
}
|
|
284
580
|
async pointer(tool, args) {
|
|
285
581
|
try {
|
|
286
|
-
await this.
|
|
582
|
+
await this.callTool(tool, args);
|
|
287
583
|
}
|
|
288
584
|
catch (error) {
|
|
289
585
|
if (isDeliveredPointerAction(error))
|
|
@@ -292,7 +588,7 @@ export class CuaDriverAdapter {
|
|
|
292
588
|
}
|
|
293
589
|
}
|
|
294
590
|
async capture() {
|
|
295
|
-
const result = await this.
|
|
591
|
+
const result = await this.callTool('get_desktop_state', {}, CAPTURE_TIMEOUT_MS);
|
|
296
592
|
const image = result.content.find((part) => part.type === 'image' && typeof part.data === 'string');
|
|
297
593
|
if (!image)
|
|
298
594
|
throw new Error('cua-driver: get_desktop_state returned no image.');
|
|
@@ -318,6 +614,16 @@ export class CuaDriverAdapter {
|
|
|
318
614
|
return { data, mimeType: 'image/png', width, height, display };
|
|
319
615
|
}
|
|
320
616
|
}
|
|
617
|
+
/** This cua-driver refusal is emitted before a tool reaches desktop dispatch. */
|
|
618
|
+
function isEndedSessionRefusal(error) {
|
|
619
|
+
if (!(error instanceof McpToolError) || error.structuredContent?.status !== 'refused')
|
|
620
|
+
return false;
|
|
621
|
+
const refusal = error.structuredContent.refusal;
|
|
622
|
+
return (typeof refusal === 'object' &&
|
|
623
|
+
refusal !== null &&
|
|
624
|
+
'code' in refusal &&
|
|
625
|
+
refusal.code === 'session_ended');
|
|
626
|
+
}
|
|
321
627
|
/**
|
|
322
628
|
* cua-driver activates the window under a desktop click, clicks, and then
|
|
323
629
|
* checks that the window — or another of its process — is still in front. A
|
|
@@ -334,6 +640,15 @@ export function isDeliveredPointerAction(error) {
|
|
|
334
640
|
/not foreground after the/.test(error.message) &&
|
|
335
641
|
!/no (mouse )?input was sent/.test(error.message));
|
|
336
642
|
}
|
|
643
|
+
/** The pinned driver suggests foreground pointer input even when it cannot bind the OS hit test to our HWND. */
|
|
644
|
+
function windowPointerRefusal(error) {
|
|
645
|
+
const code = error instanceof McpToolError ? error.structuredContent?.code : undefined;
|
|
646
|
+
if (code === 'background_unavailable' ||
|
|
647
|
+
code === 'background_occluded' ||
|
|
648
|
+
code === 'background_uipi_blocked')
|
|
649
|
+
return new Error('computer-use: this window pointer action could not be delivered safely in background. No window-scoped foreground pointer retry is available; inspect a fresh window screenshot, use a control ref if available, or deliberately capture the display before display input.');
|
|
650
|
+
return error;
|
|
651
|
+
}
|
|
337
652
|
/**
|
|
338
653
|
* cua-driver's action result → the host's. `confirmed`, `partial` and
|
|
339
654
|
* `unverifiable` count as done: a background UIA Invoke is `unverifiable` by
|
|
@@ -344,7 +659,10 @@ export function actResult(result) {
|
|
|
344
659
|
const facts = result.structuredContent ?? {};
|
|
345
660
|
switch (facts.effect) {
|
|
346
661
|
case 'suspected_noop':
|
|
347
|
-
return {
|
|
662
|
+
return {
|
|
663
|
+
ok: false,
|
|
664
|
+
detail: 'the control did not change; the action may not have reached it',
|
|
665
|
+
};
|
|
348
666
|
case 'refused': {
|
|
349
667
|
const refusal = facts.refusal;
|
|
350
668
|
return {
|
|
@@ -450,6 +768,24 @@ function optionalNumber(source, key) {
|
|
|
450
768
|
const value = source[key];
|
|
451
769
|
return typeof value === 'number' && Number.isFinite(value) ? value : undefined;
|
|
452
770
|
}
|
|
771
|
+
function windowBounds(value) {
|
|
772
|
+
if (typeof value !== 'object' || value === null)
|
|
773
|
+
return undefined;
|
|
774
|
+
const facts = value;
|
|
775
|
+
const { x, y, width, height } = facts;
|
|
776
|
+
if (typeof x !== 'number' ||
|
|
777
|
+
typeof y !== 'number' ||
|
|
778
|
+
typeof width !== 'number' ||
|
|
779
|
+
typeof height !== 'number' ||
|
|
780
|
+
![x, y, width, height].every(Number.isFinite) ||
|
|
781
|
+
width <= 0 ||
|
|
782
|
+
height <= 0)
|
|
783
|
+
return undefined;
|
|
784
|
+
return { x, y, width, height };
|
|
785
|
+
}
|
|
786
|
+
function sameBounds(a, b) {
|
|
787
|
+
return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
|
|
788
|
+
}
|
|
453
789
|
function decodePngDims(buffer) {
|
|
454
790
|
if (buffer.length < 24 || buffer.readUInt32BE(12) !== 0x49484452) {
|
|
455
791
|
throw new Error('cua-driver: the screenshot is not a PNG.');
|