@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.
@@ -1,3 +1,4 @@
1
+ import { randomUUID } from 'node:crypto'
1
2
  import type {
2
3
  ComputerUseAction,
3
4
  ComputerUseCapabilities,
@@ -7,14 +8,19 @@ import type {
7
8
  FocusWindowResult,
8
9
  ScreenshotResult,
9
10
  UiActResult,
11
+ UiElement,
10
12
  UiElementAction,
11
13
  UiSnapshot,
12
14
  WindowInfo,
15
+ WindowInputAction,
16
+ WindowScreenshotResult,
13
17
  } from '@namzu/sdk'
14
18
  import type { Adapter } from '../types.js'
15
19
  import {
20
+ type McpProcessCallOptions,
16
21
  McpStdioClient,
17
22
  type McpStdioClientOptions,
23
+ type McpToolCaller,
18
24
  McpToolError,
19
25
  type McpToolResult,
20
26
  } from './client.js'
@@ -26,10 +32,9 @@ import { type UiRefFacts, toUiTree } from './ui-tree.js'
26
32
  * `cua-driver.exe mcp` process for the adapter's lifetime, spoken to as an
27
33
  * MCP server over its standard streams.
28
34
  *
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.
35
+ * Display input uses `desktop` scope. A capture explicitly addressed to a
36
+ * window enables `window` scope, whose pixels are relative to that PNG and
37
+ * whose actions carry the captured PID and HWND.
33
38
  *
34
39
  * What the adapter adds on top:
35
40
  * - the animated agent cursor is switched off for its session: with it, a
@@ -41,8 +46,8 @@ import { type UiRefFacts, toUiTree } from './ui-tree.js'
41
46
  * - the window list drops cua-driver's own overlay, the shell's desktop and
42
47
  * 1-pixel windows, and orders it front to back;
43
48
  * - 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
49
+ * with adapter-owned refs; `uiAct` translates them to driver element tokens:
50
+ * UIA Invoke for a button, ValuePattern for a field, falling back
46
51
  * to typing into a field that is empty and has no settable value (classic
47
52
  * Notepad's editor is one).
48
53
  */
@@ -72,14 +77,58 @@ const MAX_SCROLL_TICKS = 50
72
77
  /** A drag glides through intermediate moves; many targets ignore one that teleports. */
73
78
  const DRAG = { durationMs: 250, steps: 12 } as const
74
79
 
80
+ async function disableAgentCursor(call: McpToolCaller): Promise<void> {
81
+ // Best effort: a build without the tool still works, only slower.
82
+ await call('set_agent_cursor_enabled', { enabled: false }).catch(() => undefined)
83
+ }
84
+
85
+ interface UiRefEntry extends UiRefFacts {
86
+ readonly token: string
87
+ readonly pid: number
88
+ readonly generation: number
89
+ readonly processStarts: number
90
+ }
91
+
92
+ interface WindowCaptureFrame {
93
+ readonly id: string
94
+ readonly window: WindowInfo
95
+ readonly width: number
96
+ readonly height: number
97
+ readonly processStarts: number
98
+ readonly generation: number
99
+ }
100
+
101
+ /** Replace process-local driver tokens before any UI tree leaves this adapter. */
102
+ function withOpaqueRefs(element: UiElement, refFor: (token: string) => string): UiElement {
103
+ return Object.freeze({
104
+ ...element,
105
+ ref: element.ref ? refFor(element.ref) : '',
106
+ ...(element.children
107
+ ? {
108
+ children: Object.freeze(element.children.map((child) => withOpaqueRefs(child, refFor))),
109
+ }
110
+ : {}),
111
+ })
112
+ }
113
+
75
114
  export class CuaDriverAdapter implements Adapter {
76
115
  readonly capabilities: ComputerUseCapabilities
77
116
  readonly backend: string
78
117
  private readonly client: McpStdioClient
79
118
  /** Window id → owning pid, from the latest list; `bring_to_front` needs both. */
80
119
  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 }>()
120
+ /** cua-driver's screenshot resize registry is per PID, so only this capture may drive input. */
121
+ private windowFrame: WindowCaptureFrame | undefined
122
+ /** Capture and scoped input must not race over cua-driver's per-PID resize ratio. */
123
+ private windowOperation: Promise<void> = Promise.resolve()
124
+ /** Only refs from the latest snapshot may address driver tokens. */
125
+ private uiRefs = new Map<string, UiRefEntry>()
126
+ private readonly uiRefNamespace = randomUUID()
127
+ private nextSnapshot = 0
128
+ /** A successful revival invalidates refusals from the previous lifecycle episode. */
129
+ private sessionGeneration = 0
130
+ /** Share one revival among calls refused by the same expired implicit session. */
131
+ private sessionRevival: Promise<void> | undefined
83
132
 
84
133
  constructor(options: CuaDriverAdapterOptions) {
85
134
  this.backend = `cua-driver${options.version ? ` ${options.version}` : ''}`
@@ -92,10 +141,7 @@ export class CuaDriverAdapter implements Adapter {
92
141
  requestTimeoutMs: options.requestTimeoutMs ?? 15_000,
93
142
  startTimeoutMs: options.startTimeoutMs ?? 30_000,
94
143
  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
- },
144
+ afterStart: disableAgentCursor,
99
145
  })
100
146
  this.capabilities = Object.freeze({
101
147
  displayServer: 'win32',
@@ -118,6 +164,8 @@ export class CuaDriverAdapter implements Adapter {
118
164
  mouseClickButtons: Object.freeze(['left' as const, 'right' as const, 'middle' as const]),
119
165
  mouseDragButtons: Object.freeze(['left' as const, 'right' as const, 'middle' as const]),
120
166
  windows: true,
167
+ windowCapture: true,
168
+ windowScroll: false,
121
169
  // No display-relative region capture in cua-driver (its zoom is
122
170
  // per-window and pads the region); the tool crops a full capture.
123
171
  regionCapture: false,
@@ -131,7 +179,7 @@ export class CuaDriverAdapter implements Adapter {
131
179
  }
132
180
 
133
181
  async getDisplayGeometry(): Promise<DisplayGeometry> {
134
- const size = structured(await this.client.callTool('get_screen_size'), 'get_screen_size')
182
+ const size = structured(await this.callTool('get_screen_size'), 'get_screen_size')
135
183
  return {
136
184
  width: requireNumber(size, 'width', 'get_screen_size'),
137
185
  height: requireNumber(size, 'height', 'get_screen_size'),
@@ -144,10 +192,7 @@ export class CuaDriverAdapter implements Adapter {
144
192
  case 'screenshot':
145
193
  return { type: 'screenshot', result: await this.capture() }
146
194
  case 'cursor_position': {
147
- const point = structured(
148
- await this.client.callTool('get_cursor_position'),
149
- 'get_cursor_position',
150
- )
195
+ const point = structured(await this.callTool('get_cursor_position'), 'get_cursor_position')
151
196
  return {
152
197
  type: 'cursor_position',
153
198
  point: {
@@ -157,7 +202,7 @@ export class CuaDriverAdapter implements Adapter {
157
202
  }
158
203
  }
159
204
  case 'mouse_move':
160
- await this.client.callTool('move_cursor', {
205
+ await this.callTool('move_cursor', {
161
206
  scope: 'desktop',
162
207
  x: action.to.x,
163
208
  y: action.to.y,
@@ -200,17 +245,26 @@ export class CuaDriverAdapter implements Adapter {
200
245
  }
201
246
  case 'type_text':
202
247
  if (action.text.length > 0) {
203
- await this.client.callTool('type_text', { scope: 'desktop', text: action.text })
248
+ await this.callTool('type_text', {
249
+ scope: 'desktop',
250
+ text: action.text,
251
+ })
204
252
  }
205
253
  return { type: 'ok' }
206
254
  case 'key': {
207
255
  const plan = translateKeyForCuaDriver(action.keys)
208
256
  if (plan.tool === 'type_text') {
209
- await this.client.callTool('type_text', { scope: 'desktop', text: plan.text })
257
+ await this.callTool('type_text', {
258
+ scope: 'desktop',
259
+ text: plan.text,
260
+ })
210
261
  } else if (plan.tool === 'press_key') {
211
- await this.client.callTool('press_key', { scope: 'desktop', key: plan.key })
262
+ await this.callTool('press_key', { scope: 'desktop', key: plan.key })
212
263
  } else {
213
- await this.client.callTool('hotkey', { scope: 'desktop', keys: [...plan.keys] })
264
+ await this.callTool('hotkey', {
265
+ scope: 'desktop',
266
+ keys: [...plan.keys],
267
+ })
214
268
  }
215
269
  return { type: 'ok' }
216
270
  }
@@ -219,7 +273,7 @@ export class CuaDriverAdapter implements Adapter {
219
273
 
220
274
  async listWindows(): Promise<readonly WindowInfo[]> {
221
275
  const listed = structured(
222
- await this.client.callTool('list_windows', {}, LIST_TIMEOUT_MS),
276
+ await this.callTool('list_windows', {}, LIST_TIMEOUT_MS),
223
277
  'list_windows',
224
278
  )
225
279
  const windows = toWindowInfos(listed.windows)
@@ -243,7 +297,7 @@ export class CuaDriverAdapter implements Adapter {
243
297
  // cua-driver restores a minimized window, uses the AttachThreadInput
244
298
  // route past Windows' foreground lock, and reads the foreground back.
245
299
  const result = structured(
246
- await this.client.callTool('bring_to_front', { pid, window_id: hwnd }),
300
+ await this.callTool('bring_to_front', { pid, window_id: hwnd }),
247
301
  'bring_to_front',
248
302
  )
249
303
  const now = parseWindowId(result.now_fg_hwnd)
@@ -251,14 +305,210 @@ export class CuaDriverAdapter implements Adapter {
251
305
  return { ok: focusedId === windowIdOf(hwnd), focusedId }
252
306
  }
253
307
 
308
+ async captureWindow(id: string): Promise<WindowScreenshotResult> {
309
+ return this.serializeWindowOperation(() => this.captureWindowInternal(id))
310
+ }
311
+
312
+ private async captureWindowInternal(id: string): Promise<WindowScreenshotResult> {
313
+ const target = await this.resolveWindow(id)
314
+ // A failed or overlapping capture invalidates the old resize ratio even
315
+ // if the driver returned no image. Never let it address a later action.
316
+ this.windowFrame = undefined
317
+ let captureStarts = 0
318
+ let captureGeneration = this.sessionGeneration
319
+ const result = await this.callTool(
320
+ 'get_window_state',
321
+ {
322
+ pid: target.pid,
323
+ window_id: target.hwnd,
324
+ include_accessibility_tree: false,
325
+ include_screenshot: true,
326
+ },
327
+ CAPTURE_TIMEOUT_MS,
328
+ undefined,
329
+ (starts) => {
330
+ captureStarts = starts
331
+ captureGeneration = this.sessionGeneration
332
+ },
333
+ )
334
+ const facts = structured(result, 'get_window_state')
335
+ if (facts.pid !== target.pid || parseWindowId(facts.window_id) !== target.hwnd)
336
+ throw new Error(
337
+ 'cua-driver: the window capture identity did not match the requested PID and HWND.',
338
+ )
339
+ const image = result.content.find(
340
+ (part): part is { type: 'image'; data: string; mimeType: string } =>
341
+ part.type === 'image' && typeof (part as { data?: unknown }).data === 'string',
342
+ )
343
+ if (!image || image.mimeType !== 'image/png')
344
+ throw new Error(
345
+ `cua-driver: window ${id} returned no PNG${typeof facts.screenshot_error === 'string' ? `: ${facts.screenshot_error}` : ''}.`,
346
+ )
347
+ const data = Buffer.from(image.data, 'base64')
348
+ const { width, height } = decodePngDims(data)
349
+ if (
350
+ width < 1 ||
351
+ height < 1 ||
352
+ facts.screenshot_width !== width ||
353
+ facts.screenshot_height !== height
354
+ )
355
+ throw new Error('cua-driver: window PNG dimensions did not match its capture metadata.')
356
+ const bounds = windowBounds(facts.window_bounds)
357
+ if (!bounds) throw new Error('cua-driver: window capture returned no valid window bounds.')
358
+ const windows = await this.listWindows()
359
+ if (
360
+ captureStarts === 0 ||
361
+ this.client.starts !== captureStarts ||
362
+ this.sessionGeneration !== captureGeneration
363
+ )
364
+ throw new Error(
365
+ 'cua-driver: the driver session changed after the window capture; take a new screenshot.',
366
+ )
367
+ const listed = windows.find((window) => window.id === windowIdOf(target.hwnd))
368
+ if (
369
+ !listed ||
370
+ listed.pid !== target.pid ||
371
+ listed.minimized ||
372
+ !sameBounds(listed.bounds, bounds)
373
+ )
374
+ throw new Error(
375
+ `cua-driver: window ${id} moved, closed or was minimized during capture; take a new screenshot.`,
376
+ )
377
+ const frame: WindowCaptureFrame = {
378
+ id: randomUUID(),
379
+ window: listed,
380
+ width,
381
+ height,
382
+ processStarts: captureStarts,
383
+ generation: captureGeneration,
384
+ }
385
+ this.windowFrame = frame
386
+ const coverage = facts.capture_coverage
387
+ const browserChrome =
388
+ typeof coverage === 'object' && coverage !== null && 'browser_chrome' in coverage
389
+ ? coverage.browser_chrome
390
+ : undefined
391
+ const captureCoverage =
392
+ typeof browserChrome === 'object' &&
393
+ browserChrome !== null &&
394
+ 'status' in browserChrome &&
395
+ typeof browserChrome.status === 'string'
396
+ ? browserChrome.status
397
+ : undefined
398
+ return {
399
+ data,
400
+ mimeType: 'image/png',
401
+ width,
402
+ height,
403
+ window: listed,
404
+ captureId: frame.id,
405
+ ...(captureCoverage ? { captureCoverage } : {}),
406
+ }
407
+ }
408
+
409
+ async executeWindow(captureId: string, action: WindowInputAction): Promise<void> {
410
+ return this.serializeWindowOperation(() => this.executeWindowInternal(captureId, action))
411
+ }
412
+
413
+ private async executeWindowInternal(captureId: string, action: WindowInputAction): Promise<void> {
414
+ const frame = this.windowFrame
415
+ if (!frame || frame.id !== captureId)
416
+ throw new Error(
417
+ 'computer-use: this window screenshot is stale; capture the window again before acting.',
418
+ )
419
+ const point = (value: { x: number; y: number }): void => {
420
+ if (
421
+ !Number.isInteger(value.x) ||
422
+ !Number.isInteger(value.y) ||
423
+ value.x < 0 ||
424
+ value.y < 0 ||
425
+ value.x >= frame.width ||
426
+ value.y >= frame.height
427
+ )
428
+ throw new Error('computer-use: window action coordinates are outside the captured PNG.')
429
+ }
430
+ if (action.type === 'mouse_click' || action.type === 'scroll') point(action.at)
431
+ if (action.type === 'mouse_drag') {
432
+ point(action.from)
433
+ point(action.to)
434
+ }
435
+ const target = {
436
+ scope: 'window',
437
+ pid: frame.window.pid,
438
+ window_id: parseWindowId(frame.window.id),
439
+ } as const
440
+ const call = async (name: string, args: Record<string, unknown>) => {
441
+ const windows = await this.listWindows()
442
+ const current = windows.find((window) => window.id === frame.window.id)
443
+ if (
444
+ !current ||
445
+ current.pid !== frame.window.pid ||
446
+ current.minimized ||
447
+ !sameBounds(current.bounds, frame.window.bounds) ||
448
+ this.windowFrame !== frame ||
449
+ this.sessionGeneration !== frame.generation ||
450
+ this.client.starts !== frame.processStarts
451
+ )
452
+ throw new Error(
453
+ 'computer-use: the captured window changed or its driver restarted; take a new window screenshot.',
454
+ )
455
+ await this.callTool(name, { ...target, ...args }, undefined, undefined, undefined, frame)
456
+ }
457
+ switch (action.type) {
458
+ case 'mouse_click':
459
+ try {
460
+ await call('click', { x: action.at.x, y: action.at.y, button: action.button })
461
+ } catch (error) {
462
+ if (!isDeliveredPointerAction(error)) throw windowPointerRefusal(error)
463
+ }
464
+ return
465
+ case 'mouse_drag':
466
+ try {
467
+ await call('drag', {
468
+ from_x: action.from.x,
469
+ from_y: action.from.y,
470
+ to_x: action.to.x,
471
+ to_y: action.to.y,
472
+ button: action.button,
473
+ duration_ms: DRAG.durationMs,
474
+ steps: DRAG.steps,
475
+ })
476
+ } catch (error) {
477
+ throw windowPointerRefusal(error)
478
+ }
479
+ return
480
+ case 'scroll':
481
+ throw new Error(
482
+ '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.',
483
+ )
484
+ case 'type_text':
485
+ if (action.text.length > 0)
486
+ await call('type_text', {
487
+ text: action.text,
488
+ ...(action.delivery_mode ? { delivery_mode: action.delivery_mode } : {}),
489
+ })
490
+ return
491
+ case 'key': {
492
+ const plan = translateKeyForCuaDriver(action.keys)
493
+ const delivery = action.delivery_mode ? { delivery_mode: action.delivery_mode } : {}
494
+ if (plan.tool === 'type_text') await call('type_text', { text: plan.text, ...delivery })
495
+ else if (plan.tool === 'press_key') await call('press_key', { key: plan.key, ...delivery })
496
+ else await call('hotkey', { keys: [...plan.keys], ...delivery })
497
+ return
498
+ }
499
+ }
500
+ }
501
+
254
502
  /**
255
503
  * One window's controls. Without an id, the window in front — which,
256
504
  * for an agent run from a terminal, is usually that terminal.
257
505
  */
258
506
  async uiSnapshot(windowId?: string): Promise<UiSnapshot> {
259
507
  const target = await this.resolveWindow(windowId)
508
+ let processStarts = 0
509
+ let snapshotGeneration = this.sessionGeneration
260
510
  const state = structured(
261
- await this.client.callTool(
511
+ await this.callTool(
262
512
  'get_window_state',
263
513
  {
264
514
  pid: target.pid,
@@ -267,15 +517,32 @@ export class CuaDriverAdapter implements Adapter {
267
517
  max_elements: UI_MAX_ELEMENTS,
268
518
  },
269
519
  UI_TREE_TIMEOUT_MS,
520
+ undefined,
521
+ (starts) => {
522
+ processStarts = starts
523
+ snapshotGeneration = this.sessionGeneration
524
+ },
270
525
  ),
271
526
  'get_window_state',
272
527
  )
528
+ if (snapshotGeneration !== this.sessionGeneration || processStarts === 0)
529
+ throw new McpToolError('get_window_state', 'stale UI snapshot; take a new one')
273
530
  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
- )
531
+ const snapshot = ++this.nextSnapshot
532
+ const refs = new Map<string, UiRefEntry>()
533
+ let ordinal = 0
534
+ const root = withOpaqueRefs(tree.root, (token) => {
535
+ const ref = `cua-ui:${this.uiRefNamespace}:${snapshot}:${++ordinal}`
536
+ refs.set(ref, {
537
+ ...tree.refs.get(token),
538
+ token,
539
+ pid: target.pid,
540
+ generation: snapshotGeneration,
541
+ processStarts,
542
+ })
543
+ return ref
544
+ })
545
+ this.uiRefs = refs
279
546
  const title = typeof state.window_title === 'string' ? state.window_title : undefined
280
547
  const app =
281
548
  typeof state.app_name === 'string' ? state.app_name.replace(/\.exe$/i, '') : undefined
@@ -283,7 +550,7 @@ export class CuaDriverAdapter implements Adapter {
283
550
  windowId: windowIdOf(target.hwnd),
284
551
  ...(title !== undefined ? { title } : {}),
285
552
  ...(app !== undefined ? { app } : {}),
286
- root: tree.root,
553
+ root,
287
554
  ...(state.truncated === true ? { truncated: true } : {}),
288
555
  }
289
556
  }
@@ -295,7 +562,8 @@ export class CuaDriverAdapter implements Adapter {
295
562
  ok: false,
296
563
  detail: `${ref} is not a control of the latest UI snapshot; take a new one.`,
297
564
  }
298
- const { pid } = facts
565
+ const { pid, token } = facts
566
+ const uiRef = { ref, facts }
299
567
  try {
300
568
  switch (action) {
301
569
  case 'invoke':
@@ -306,12 +574,19 @@ export class CuaDriverAdapter implements Adapter {
306
574
  // cua-driver's click on an element token performs the control's
307
575
  // own pattern in the background (Invoke, or a posted click at its
308
576
  // centre), with no pointer move and no change of foreground.
309
- return actResult(await this.client.callTool('click', { pid, element_token: ref }))
577
+ return actResult(
578
+ await this.callTool('click', { pid, element_token: token }, undefined, uiRef),
579
+ )
310
580
  case 'set_value': {
311
581
  const text = value ?? ''
312
582
  try {
313
583
  return actResult(
314
- await this.client.callTool('set_value', { pid, element_token: ref, value: text }),
584
+ await this.callTool(
585
+ 'set_value',
586
+ { pid, element_token: token, value: text },
587
+ undefined,
588
+ uiRef,
589
+ ),
315
590
  )
316
591
  } catch (error) {
317
592
  if (
@@ -328,10 +603,18 @@ export class CuaDriverAdapter implements Adapter {
328
603
  'this field cannot be set directly and already holds text; click it, select its text (CTRL+A) and type the new text instead',
329
604
  }
330
605
  const typed = actResult(
331
- await this.client.callTool('type_text', { pid, element_token: ref, text }),
606
+ await this.callTool(
607
+ 'type_text',
608
+ { pid, element_token: token, text },
609
+ undefined,
610
+ uiRef,
611
+ ),
332
612
  )
333
613
  return typed.ok
334
- ? { ok: true, detail: 'typed into the empty field, which has no settable value' }
614
+ ? {
615
+ ok: true,
616
+ detail: 'typed into the empty field, which has no settable value',
617
+ }
335
618
  : typed
336
619
  }
337
620
  }
@@ -352,6 +635,89 @@ export class CuaDriverAdapter implements Adapter {
352
635
  await this.client.dispose()
353
636
  }
354
637
 
638
+ private async serializeWindowOperation<T>(operation: () => Promise<T>): Promise<T> {
639
+ const previous = this.windowOperation
640
+ let release: () => void = () => undefined
641
+ this.windowOperation = new Promise<void>((resolve) => {
642
+ release = resolve
643
+ })
644
+ await previous
645
+ try {
646
+ return await operation()
647
+ } finally {
648
+ release()
649
+ }
650
+ }
651
+
652
+ /**
653
+ * cua-driver refuses an expired implicit session before dispatch, with a
654
+ * structured `session_ended` code. Only that exact refusal is safe to replay.
655
+ * A lost response or transport failure still has an unknown action outcome.
656
+ */
657
+ private async callTool(
658
+ name: string,
659
+ args: Record<string, unknown> = {},
660
+ timeoutMs?: number,
661
+ uiRef?: { readonly ref: string; readonly facts: UiRefEntry },
662
+ onProcess?: McpProcessCallOptions['onProcess'],
663
+ windowFrame?: WindowCaptureFrame,
664
+ ): Promise<McpToolResult> {
665
+ await this.sessionRevival
666
+ if (
667
+ windowFrame &&
668
+ (this.windowFrame !== windowFrame ||
669
+ windowFrame.generation !== this.sessionGeneration ||
670
+ windowFrame.processStarts !== this.client.starts)
671
+ )
672
+ throw new McpToolError(name, 'stale window screenshot; capture the window again')
673
+ if (
674
+ uiRef &&
675
+ (this.uiRefs.get(uiRef.ref) !== uiRef.facts ||
676
+ uiRef.facts.generation !== this.sessionGeneration)
677
+ )
678
+ throw new McpToolError(name, 'stale UI snapshot; take a new one')
679
+ const generation = this.sessionGeneration
680
+ try {
681
+ return await this.client.callTool(name, args, timeoutMs, {
682
+ ...(uiRef || windowFrame
683
+ ? { expectedStarts: uiRef?.facts.processStarts ?? windowFrame?.processStarts }
684
+ : {}),
685
+ ...(onProcess ? { onProcess } : {}),
686
+ })
687
+ } catch (error) {
688
+ if (!isEndedSessionRefusal(error)) throw error
689
+ // The refusal proves the old session's element tokens are invalid,
690
+ // even if start_session fails and there is no successful revival.
691
+ if (this.sessionGeneration === generation) this.uiRefs.clear()
692
+ this.windowFrame = undefined
693
+ await this.reviveSession(generation)
694
+ // Element tokens belong to the old snapshot. A new lifecycle session
695
+ // needs a new tree before a control can be addressed again.
696
+ if (uiRef) throw new McpToolError(name, 'stale UI snapshot; take a new one')
697
+ if (windowFrame)
698
+ throw new McpToolError(name, 'stale window screenshot; capture the window again')
699
+ // One retry only. A second refusal or an unacknowledged action is
700
+ // returned to the host without any further automatic replay.
701
+ return this.client.callTool(name, args, timeoutMs, { onProcess })
702
+ }
703
+ }
704
+
705
+ private async reviveSession(generation: number): Promise<void> {
706
+ if (this.sessionGeneration !== generation) return
707
+ if (!this.sessionRevival) {
708
+ this.sessionRevival = (async () => {
709
+ await this.client.callTool('start_session')
710
+ await disableAgentCursor((name, args) => this.client.callTool(name, args))
711
+ this.uiRefs.clear()
712
+ this.windowFrame = undefined
713
+ this.sessionGeneration++
714
+ })().finally(() => {
715
+ this.sessionRevival = undefined
716
+ })
717
+ }
718
+ await this.sessionRevival
719
+ }
720
+
355
721
  /** A window id (or the window in front) → its handle and owning process. */
356
722
  private async resolveWindow(
357
723
  windowId: string | undefined,
@@ -377,7 +743,7 @@ export class CuaDriverAdapter implements Adapter {
377
743
 
378
744
  private async pointer(tool: string, args: Record<string, unknown>): Promise<void> {
379
745
  try {
380
- await this.client.callTool(tool, args)
746
+ await this.callTool(tool, args)
381
747
  } catch (error) {
382
748
  if (isDeliveredPointerAction(error)) return
383
749
  throw error
@@ -385,7 +751,7 @@ export class CuaDriverAdapter implements Adapter {
385
751
  }
386
752
 
387
753
  private async capture(): Promise<ScreenshotResult> {
388
- const result = await this.client.callTool('get_desktop_state', {}, CAPTURE_TIMEOUT_MS)
754
+ const result = await this.callTool('get_desktop_state', {}, CAPTURE_TIMEOUT_MS)
389
755
  const image = result.content.find(
390
756
  (part): part is { type: 'image'; data: string; mimeType: string } =>
391
757
  part.type === 'image' && typeof (part as { data?: unknown }).data === 'string',
@@ -416,6 +782,19 @@ export class CuaDriverAdapter implements Adapter {
416
782
  }
417
783
  }
418
784
 
785
+ /** This cua-driver refusal is emitted before a tool reaches desktop dispatch. */
786
+ function isEndedSessionRefusal(error: unknown): error is McpToolError {
787
+ if (!(error instanceof McpToolError) || error.structuredContent?.status !== 'refused')
788
+ return false
789
+ const refusal = error.structuredContent.refusal
790
+ return (
791
+ typeof refusal === 'object' &&
792
+ refusal !== null &&
793
+ 'code' in refusal &&
794
+ refusal.code === 'session_ended'
795
+ )
796
+ }
797
+
419
798
  /**
420
799
  * cua-driver activates the window under a desktop click, clicks, and then
421
800
  * checks that the window — or another of its process — is still in front. A
@@ -435,6 +814,20 @@ export function isDeliveredPointerAction(error: unknown): boolean {
435
814
  )
436
815
  }
437
816
 
817
+ /** The pinned driver suggests foreground pointer input even when it cannot bind the OS hit test to our HWND. */
818
+ function windowPointerRefusal(error: unknown): unknown {
819
+ const code = error instanceof McpToolError ? error.structuredContent?.code : undefined
820
+ if (
821
+ code === 'background_unavailable' ||
822
+ code === 'background_occluded' ||
823
+ code === 'background_uipi_blocked'
824
+ )
825
+ return new Error(
826
+ '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.',
827
+ )
828
+ return error
829
+ }
830
+
438
831
  /**
439
832
  * cua-driver's action result → the host's. `confirmed`, `partial` and
440
833
  * `unverifiable` count as done: a background UIA Invoke is `unverifiable` by
@@ -445,7 +838,10 @@ export function actResult(result: McpToolResult): UiActResult {
445
838
  const facts = result.structuredContent ?? {}
446
839
  switch (facts.effect) {
447
840
  case 'suspected_noop':
448
- return { ok: false, detail: 'the control did not change; the action may not have reached it' }
841
+ return {
842
+ ok: false,
843
+ detail: 'the control did not change; the action may not have reached it',
844
+ }
449
845
  case 'refused': {
450
846
  const refusal = facts.refusal as { message?: unknown } | undefined
451
847
  return {
@@ -488,7 +884,12 @@ interface CuaWindow {
488
884
  readonly pid?: unknown
489
885
  readonly app_name?: unknown
490
886
  readonly title?: unknown
491
- readonly bounds?: { x?: unknown; y?: unknown; width?: unknown; height?: unknown }
887
+ readonly bounds?: {
888
+ x?: unknown
889
+ y?: unknown
890
+ width?: unknown
891
+ height?: unknown
892
+ }
492
893
  readonly minimized?: unknown
493
894
  readonly is_on_screen?: unknown
494
895
  readonly z_index?: unknown
@@ -563,6 +964,27 @@ function optionalNumber(source: Record<string, unknown>, key: string): number |
563
964
  return typeof value === 'number' && Number.isFinite(value) ? value : undefined
564
965
  }
565
966
 
967
+ function windowBounds(value: unknown): WindowInfo['bounds'] | undefined {
968
+ if (typeof value !== 'object' || value === null) return undefined
969
+ const facts = value as Record<string, unknown>
970
+ const { x, y, width, height } = facts
971
+ if (
972
+ typeof x !== 'number' ||
973
+ typeof y !== 'number' ||
974
+ typeof width !== 'number' ||
975
+ typeof height !== 'number' ||
976
+ ![x, y, width, height].every(Number.isFinite) ||
977
+ width <= 0 ||
978
+ height <= 0
979
+ )
980
+ return undefined
981
+ return { x, y, width, height }
982
+ }
983
+
984
+ function sameBounds(a: WindowInfo['bounds'], b: WindowInfo['bounds']): boolean {
985
+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height
986
+ }
987
+
566
988
  function decodePngDims(buffer: Buffer): { width: number; height: number } {
567
989
  if (buffer.length < 24 || buffer.readUInt32BE(12) !== 0x49484452) {
568
990
  throw new Error('cua-driver: the screenshot is not a PNG.')