@namzu/computer-use 3.1.0 → 4.0.1

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.
Files changed (125) hide show
  1. package/CHANGELOG.md +64 -1
  2. package/README.md +3 -3
  3. package/dist/SubprocessComputerUseHost.d.ts +58 -10
  4. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  5. package/dist/SubprocessComputerUseHost.js +214 -47
  6. package/dist/SubprocessComputerUseHost.js.map +1 -1
  7. package/dist/adapters/cua-driver/adapter.d.ts +171 -10
  8. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  9. package/dist/adapters/cua-driver/adapter.js +1479 -161
  10. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  11. package/dist/adapters/cua-driver/client.d.ts +16 -0
  12. package/dist/adapters/cua-driver/client.d.ts.map +1 -1
  13. package/dist/adapters/cua-driver/client.js +54 -5
  14. package/dist/adapters/cua-driver/client.js.map +1 -1
  15. package/dist/adapters/cua-driver/escalation.d.ts +67 -0
  16. package/dist/adapters/cua-driver/escalation.d.ts.map +1 -0
  17. package/dist/adapters/cua-driver/escalation.js +82 -0
  18. package/dist/adapters/cua-driver/escalation.js.map +1 -0
  19. package/dist/adapters/cua-driver/keys.d.ts +5 -0
  20. package/dist/adapters/cua-driver/keys.d.ts.map +1 -1
  21. package/dist/adapters/cua-driver/keys.js +23 -0
  22. package/dist/adapters/cua-driver/keys.js.map +1 -1
  23. package/dist/adapters/cua-driver/observe.d.ts +99 -0
  24. package/dist/adapters/cua-driver/observe.d.ts.map +1 -0
  25. package/dist/adapters/cua-driver/observe.js +227 -0
  26. package/dist/adapters/cua-driver/observe.js.map +1 -0
  27. package/dist/adapters/cua-driver/provision.d.ts +13 -13
  28. package/dist/adapters/cua-driver/provision.js +13 -13
  29. package/dist/adapters/cua-driver/ui-tree.d.ts +75 -2
  30. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  31. package/dist/adapters/cua-driver/ui-tree.js +142 -14
  32. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  33. package/dist/adapters/types.d.ts +4 -4
  34. package/dist/adapters/types.d.ts.map +1 -1
  35. package/dist/adapters/types.js.map +1 -1
  36. package/dist/adapters/win32.d.ts +10 -0
  37. package/dist/adapters/win32.d.ts.map +1 -1
  38. package/dist/adapters/win32.js +12 -2
  39. package/dist/adapters/win32.js.map +1 -1
  40. package/dist/errors.d.ts +19 -0
  41. package/dist/errors.d.ts.map +1 -1
  42. package/dist/errors.js +26 -0
  43. package/dist/errors.js.map +1 -1
  44. package/dist/foreground/guard.d.ts +31 -0
  45. package/dist/foreground/guard.d.ts.map +1 -0
  46. package/dist/foreground/guard.js +156 -0
  47. package/dist/foreground/guard.js.map +1 -0
  48. package/dist/foreground/index.d.ts +11 -0
  49. package/dist/foreground/index.d.ts.map +1 -0
  50. package/dist/foreground/index.js +7 -0
  51. package/dist/foreground/index.js.map +1 -0
  52. package/dist/foreground/ladder.d.ts +143 -0
  53. package/dist/foreground/ladder.d.ts.map +1 -0
  54. package/dist/foreground/ladder.js +505 -0
  55. package/dist/foreground/ladder.js.map +1 -0
  56. package/dist/foreground/lease.d.ts +69 -0
  57. package/dist/foreground/lease.d.ts.map +1 -0
  58. package/dist/foreground/lease.js +182 -0
  59. package/dist/foreground/lease.js.map +1 -0
  60. package/dist/foreground/types.d.ts +287 -0
  61. package/dist/foreground/types.d.ts.map +1 -0
  62. package/dist/foreground/types.js +32 -0
  63. package/dist/foreground/types.js.map +1 -0
  64. package/dist/foreground/windows-helper-script.d.ts +19 -0
  65. package/dist/foreground/windows-helper-script.d.ts.map +1 -0
  66. package/dist/foreground/windows-helper-script.js +472 -0
  67. package/dist/foreground/windows-helper-script.js.map +1 -0
  68. package/dist/foreground/windows-monitor.d.ts +75 -0
  69. package/dist/foreground/windows-monitor.d.ts.map +1 -0
  70. package/dist/foreground/windows-monitor.js +216 -0
  71. package/dist/foreground/windows-monitor.js.map +1 -0
  72. package/dist/foreground/windows.d.ts +21 -0
  73. package/dist/foreground/windows.d.ts.map +1 -0
  74. package/dist/foreground/windows.js +54 -0
  75. package/dist/foreground/windows.js.map +1 -0
  76. package/dist/index.d.ts +6 -1
  77. package/dist/index.d.ts.map +1 -1
  78. package/dist/index.js +3 -1
  79. package/dist/index.js.map +1 -1
  80. package/dist/presence/helper-script.d.ts +39 -0
  81. package/dist/presence/helper-script.d.ts.map +1 -0
  82. package/dist/presence/helper-script.js +320 -0
  83. package/dist/presence/helper-script.js.map +1 -0
  84. package/dist/presence/index.d.ts +6 -0
  85. package/dist/presence/index.d.ts.map +1 -0
  86. package/dist/presence/index.js +4 -0
  87. package/dist/presence/index.js.map +1 -0
  88. package/dist/presence/presence.d.ts +70 -0
  89. package/dist/presence/presence.d.ts.map +1 -0
  90. package/dist/presence/presence.js +147 -0
  91. package/dist/presence/presence.js.map +1 -0
  92. package/dist/presence/windows.d.ts +19 -0
  93. package/dist/presence/windows.d.ts.map +1 -0
  94. package/dist/presence/windows.js +39 -0
  95. package/dist/presence/windows.js.map +1 -0
  96. package/dist/util/call-scope.d.ts +34 -0
  97. package/dist/util/call-scope.d.ts.map +1 -0
  98. package/dist/util/call-scope.js +58 -0
  99. package/dist/util/call-scope.js.map +1 -0
  100. package/package.json +2 -2
  101. package/src/SubprocessComputerUseHost.ts +288 -46
  102. package/src/adapters/cua-driver/adapter.ts +1754 -175
  103. package/src/adapters/cua-driver/client.ts +59 -2
  104. package/src/adapters/cua-driver/escalation.ts +137 -0
  105. package/src/adapters/cua-driver/keys.ts +20 -0
  106. package/src/adapters/cua-driver/observe.ts +310 -0
  107. package/src/adapters/cua-driver/provision.ts +13 -13
  108. package/src/adapters/cua-driver/ui-tree.ts +219 -15
  109. package/src/adapters/types.ts +8 -3
  110. package/src/adapters/win32.ts +26 -3
  111. package/src/errors.ts +32 -0
  112. package/src/foreground/guard.ts +182 -0
  113. package/src/foreground/index.ts +45 -0
  114. package/src/foreground/ladder.ts +616 -0
  115. package/src/foreground/lease.ts +232 -0
  116. package/src/foreground/types.ts +318 -0
  117. package/src/foreground/windows-helper-script.ts +471 -0
  118. package/src/foreground/windows-monitor.ts +288 -0
  119. package/src/foreground/windows.ts +73 -0
  120. package/src/index.ts +15 -1
  121. package/src/presence/helper-script.ts +323 -0
  122. package/src/presence/index.ts +17 -0
  123. package/src/presence/presence.ts +195 -0
  124. package/src/presence/windows.ts +54 -0
  125. package/src/util/call-scope.ts +73 -0
@@ -1,5 +1,7 @@
1
1
  import { randomUUID } from 'node:crypto'
2
2
  import type {
3
+ ActionDelivery,
4
+ ActionRetrySafety,
3
5
  ComputerUseAction,
4
6
  ComputerUseCapabilities,
5
7
  ComputerUseResult,
@@ -7,14 +9,22 @@ import type {
7
9
  DisplayInfo,
8
10
  FocusWindowResult,
9
11
  ScreenshotResult,
12
+ UiActFailureCode,
10
13
  UiActResult,
11
14
  UiElement,
12
15
  UiElementAction,
13
16
  UiSnapshot,
17
+ UiSnapshotOptions,
14
18
  WindowInfo,
15
19
  WindowInputAction,
20
+ WindowInputResult,
16
21
  WindowScreenshotResult,
17
22
  } from '@namzu/sdk'
23
+ import { droppedInputNote, foregroundNote, interferenceNote } from '../../foreground/guard.js'
24
+ import type { ForegroundLadder, LadderRequest } from '../../foreground/ladder.js'
25
+ import { BurstInterrupted, type ForegroundSubject } from '../../foreground/types.js'
26
+ import type { Presence } from '../../presence/presence.js'
27
+ import { CallAbortedError, currentCallSignal, markSent } from '../../util/call-scope.js'
18
28
  import type { Adapter } from '../types.js'
19
29
  import {
20
30
  type McpProcessCallOptions,
@@ -24,8 +34,32 @@ import {
24
34
  McpToolError,
25
35
  type McpToolResult,
26
36
  } from './client.js'
27
- import { translateKeyForCuaDriver } from './keys.js'
28
- import { type UiRefFacts, toUiTree } from './ui-tree.js'
37
+ import {
38
+ type AttemptSummary,
39
+ type EditStill,
40
+ canBeJudgedByStillness,
41
+ escalationDetail,
42
+ judgeStillness,
43
+ shouldRetryOnScreen,
44
+ } from './escalation.js'
45
+ import { menuAcceleratorOf, translateKeyForCuaDriver } from './keys.js'
46
+ import {
47
+ type Observation,
48
+ type ObservedVerdict,
49
+ judgeEdit,
50
+ judgeEditBetween,
51
+ judgeObserved,
52
+ observationOf,
53
+ sameObservation,
54
+ } from './observe.js'
55
+ import {
56
+ type ParsedUiTree,
57
+ type UiEvidence,
58
+ type UiNode,
59
+ type UiRefFacts,
60
+ locate,
61
+ toUiTree,
62
+ } from './ui-tree.js'
29
63
 
30
64
  /**
31
65
  * The Windows desktop through cua-driver (github.com/trycua/cua, MIT): one
@@ -60,6 +94,21 @@ export interface CuaDriverAdapterOptions {
60
94
  readonly cwd?: string
61
95
  /** For the backend label; the pinned version when it is the pinned build. */
62
96
  readonly version?: string
97
+ /**
98
+ * Where a window action that cannot be delivered in the background is
99
+ * retried in the foreground: through the idle gate, the screen lease and a
100
+ * restore. Absent, such an action is reported as not delivered.
101
+ */
102
+ readonly foreground?: ForegroundLadder
103
+ /**
104
+ * The agent cursor and window border shown while a window is operated.
105
+ * Absent, nothing is drawn.
106
+ */
107
+ readonly presence?: Presence
108
+ /** For tests: the clock the freshness of a read is judged by. */
109
+ readonly now?: () => number
110
+ /** For tests: how the adapter waits for a window to show an input's effect. */
111
+ readonly settle?: (ms: number) => Promise<void>
63
112
  /** For tests. */
64
113
  readonly spawnProcess?: McpStdioClientOptions['spawnProcess']
65
114
  readonly requestTimeoutMs?: number
@@ -70,23 +119,101 @@ const CAPTURE_TIMEOUT_MS = 30_000
70
119
  const LIST_TIMEOUT_MS = 20_000
71
120
  /** A browser window's tree takes 2–3 s; a huge one is cut by `UI_MAX_ELEMENTS` first. */
72
121
  const UI_TREE_TIMEOUT_MS = 30_000
73
- /** The most controls one snapshot walks. The SDK shows the model at most ~14 000 characters of it. */
74
- const UI_MAX_ELEMENTS = 1_500
122
+ /** The most nodes one read walks. The model is shown an outline of a large one, never all of it. */
123
+ const UI_MAX_ELEMENTS = 5_000
124
+ /**
125
+ * The driver cuts a walk at its cap without saying so (the answer carries no
126
+ * flag), so a walk this close to the cap is treated as cut.
127
+ */
128
+ const UI_WALK_CUT_AT = Math.floor(UI_MAX_ELEMENTS * 0.95)
129
+ /** A window with more shown controls than this is returned as an outline. */
130
+ const OUTLINE_THRESHOLD = 220
131
+ /** The most controls an outline shows; the rest are counted, not listed. */
132
+ const OUTLINE_BUDGET = 150
133
+ /** The most children of one element an outline lists; a long list is opened as a region. */
134
+ const OUTLINE_PER_PARENT = 12
135
+ /** The children of a region opened by itself that one page lists. */
136
+ const OUTLINE_PAGE = 60
137
+ /** A browser tree this small is the window frame alone: the page has not been built yet. */
138
+ const SPARSE_TREE = 12
139
+ /** Controls that offer a choice among options, which the keyboard can make when the driver cannot. */
140
+ const CHOICE_ROLES = /^(ComboBox|List|ListBox)$/i
141
+ /** Waits (ms) before each read that looks for an input's effect: at once, then a little later. */
142
+ const OBSERVE_WAITS_MS = [0, 80, 200, 450] as const
143
+
144
+ /** How one attempt at a window input was routed, filled in as it runs. */
145
+ interface InputRoute {
146
+ /** Send it on the screen (through the foreground ladder) whatever the action asked. */
147
+ foreground: boolean
148
+ /** The attempt used the screen. */
149
+ onScreen: boolean
150
+ /** The ladder did not run the attempt: why (nothing was sent). */
151
+ blocked?: string
152
+ /** A person used the keyboard or mouse during the burst: what the window shows proves nothing. */
153
+ interfered?: boolean
154
+ /** What reading the window showed when the driver could not confirm the input. */
155
+ outcome?: 'no_effect' | 'unexplained'
156
+ }
157
+ /** How many times a burst that a person's input stopped before anything was sent waits for the next pause and goes again. */
158
+ const PAUSE_RETRIES = 3
159
+ const BROWSER_APP = /chrome|msedge|edge|brave|vivaldi|opera|firefox|chromium/i
160
+ /**
161
+ * A ref read longer ago than this is checked against a new read before it
162
+ * is acted on. Within it, the driver's own handle check (it refuses a handle
163
+ * a newer read of the window replaced) guards the write.
164
+ */
165
+ /** Driver tools that only read; every other tool may change the desktop. */
166
+ const READ_ONLY_TOOL = /^(get_|list_|start_session|set_agent_cursor|check_|describe)/
167
+
168
+ /** Whether a driver tool call can change the desktop (so a lost one is an unknown outcome). */
169
+ export function changesDesktop(tool: string): boolean {
170
+ return !READ_ONLY_TOOL.test(tool)
171
+ }
172
+
173
+ const IDENTITY_FRESH_MS = 3_000
174
+ /** Refs the adapter keeps; the model is shown far fewer. */
175
+ const MAX_REFS = 4_000
176
+ /** The most refs one read creates; a quarter of the budget, so one read cannot evict the rest. */
177
+ const NEW_REFS_PER_READ = 1_000
75
178
  /** cua-driver refuses more than 50 ticks in one scroll call. */
76
179
  const MAX_SCROLL_TICKS = 50
77
180
  /** A drag glides through intermediate moves; many targets ignore one that teleports. */
78
181
  const DRAG = { durationMs: 250, steps: 12 } as const
79
182
 
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)
183
+ /**
184
+ * Switches the driver's own animated cursor off for the session (Namzu draws
185
+ * its own, and two cursors are never shown). The driver keeps an empty,
186
+ * fully transparent, click-through overlay window either way; with the cursor off it draws nothing into it. Returns whether
187
+ * the driver confirmed it: a build without the tool still works, only slower,
188
+ * and then Namzu shows no cursor of its own (see `tryPresence`).
189
+ */
190
+ async function disableAgentCursor(call: McpToolCaller): Promise<boolean> {
191
+ try {
192
+ const result = await call('set_agent_cursor_enabled', { enabled: false })
193
+ return result.structuredContent?.enabled === false
194
+ } catch {
195
+ return false
196
+ }
83
197
  }
84
198
 
85
199
  interface UiRefEntry extends UiRefFacts {
86
200
  readonly token: string
87
201
  readonly pid: number
202
+ readonly hwnd: number
88
203
  readonly generation: number
89
204
  readonly processStarts: number
205
+ /** The adapter's number for the read of the window this handle came from. */
206
+ readonly readSeq: number
207
+ readonly readAt: number
208
+ /** A container the model can open with a root snapshot; it has no driver handle. */
209
+ readonly region: boolean
210
+ /** Where the control was when it was read, in virtual-desktop pixels; shows where the agent cursor goes. */
211
+ readonly bounds?: {
212
+ readonly x: number
213
+ readonly y: number
214
+ readonly width: number
215
+ readonly height: number
216
+ }
90
217
  }
91
218
 
92
219
  interface WindowCaptureFrame {
@@ -98,33 +225,177 @@ interface WindowCaptureFrame {
98
225
  readonly generation: number
99
226
  }
100
227
 
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
- : {}),
228
+ const pathKey = (path: readonly number[]): string => path.join('.')
229
+
230
+ /** Evidence as words, for a message: `Button "Save"`. App text, so cut and without quotes or line breaks. */
231
+ function describeEvidence(evidence: UiEvidence): string {
232
+ const name = evidence.name.replace(/["\r\n]+/g, ' ').trim()
233
+ const role = /^[A-Za-z][\w-]{0,39}$/.test(evidence.role) ? evidence.role : 'Element'
234
+ return name ? `${role} "${name.length > 60 ? `${name.slice(0, 59)}…` : name}"` : role
235
+ }
236
+
237
+ /** How many controls fit a ref; one means it was one of several identical controls and the window has changed since. */
238
+ function fitText(count: number): string {
239
+ return count > 1
240
+ ? `${count} controls fit`
241
+ : 'the window changed and which of several identical controls it was cannot be told for'
242
+ }
243
+
244
+ function refFailure(code: UiActFailureCode, detail: string): UiActResult {
245
+ return {
246
+ ok: false,
247
+ delivery: 'not_delivered',
248
+ retrySafety: 'safe',
249
+ code,
250
+ detail,
251
+ }
252
+ }
253
+
254
+ function factsOfNode(node: UiNode): UiRefFacts {
255
+ return {
256
+ role: node.role,
257
+ name: node.name,
258
+ ...(node.automationId !== undefined ? { automationId: node.automationId } : {}),
259
+ selected: false,
260
+ actions: [],
261
+ path: node.path,
262
+ }
263
+ }
264
+
265
+ /** Whether the model would be shown this element: a nameless control nobody can act on is passed through. */
266
+ function isSilent(element: UiElement): boolean {
267
+ return element.ref === '' && element.name.trim().length === 0 && element.value === undefined
268
+ }
269
+
270
+ function visibleCount(element: UiElement): number {
271
+ let count = isSilent(element) ? 0 : 1
272
+ for (const child of element.children ?? []) count += visibleCount(child)
273
+ return count
274
+ }
275
+
276
+ /**
277
+ * The top of a big tree: breadth first, shallow levels before deep ones, so
278
+ * the whole window's layout is shown before any one region's detail. What is
279
+ * left out is counted on the element that holds it, and that element is a
280
+ * region the model can open.
281
+ */
282
+ function outlineOf(
283
+ root: UiElement,
284
+ basePath: readonly number[],
285
+ budget: number,
286
+ page?: { readonly offset: number },
287
+ ): { root: UiElement; regions: Set<string>; next: number | undefined } {
288
+ const keep = new Set<UiElement>([root])
289
+ const queue: UiElement[] = [root]
290
+ let used = isSilent(root) ? 0 : 1
291
+ let next: number | undefined
292
+ while (queue.length > 0) {
293
+ const element = queue.shift() as UiElement
294
+ const isRoot = element === root
295
+ // A region opened by itself lists a page of its own children; the page
296
+ // after it is asked for with the offset it reports.
297
+ const children = element.children ?? []
298
+ const first = isRoot && page ? Math.min(page.offset, children.length) : 0
299
+ const cap = isRoot && page ? OUTLINE_PAGE : OUTLINE_PER_PARENT
300
+ let listed = 0
301
+ let cut = false
302
+ for (let index = first; index < children.length; index++) {
303
+ const child = children[index] as UiElement
304
+ const cost = isSilent(child) ? 0 : 1
305
+ // One long list must not use the budget its siblings' regions need.
306
+ // Once the list is cut, nothing after the cut is listed, nameless or
307
+ // not: the next page begins at the cut and would repeat it.
308
+ if (cut || used + cost > budget || listed + cost > cap || keep.size > budget * 4) {
309
+ cut = true
310
+ if (isRoot && page && next === undefined) next = index
311
+ continue
312
+ }
313
+ used += cost
314
+ listed += cost
315
+ keep.add(child)
316
+ queue.push(child)
317
+ }
318
+ }
319
+ const regions = new Set<string>()
320
+ const build = (element: UiElement, path: readonly number[]): UiElement => {
321
+ const children = element.children ?? []
322
+ const kept: UiElement[] = []
323
+ children.forEach((child, index) => {
324
+ if (!keep.has(child)) return
325
+ const built = build(child, [...path, index])
326
+ ORIGINAL_INDEX.set(built, index)
327
+ kept.push(built)
328
+ })
329
+ const hidden = children.length - kept.length
330
+ if (hidden > 0) regions.add(pathKey(path))
331
+ const { children: _children, ...rest } = element
332
+ return Object.freeze({
333
+ ...rest,
334
+ ...(kept.length > 0 ? { children: Object.freeze(kept) } : {}),
335
+ ...(hidden > 0 ? { hiddenChildren: hidden } : {}),
336
+ }) as UiElement
337
+ }
338
+ return { root: build(root, basePath), regions, next }
339
+ }
340
+
341
+ /** The paths of the elements a view contains. */
342
+ function collectShown(element: UiElement, path: readonly number[], into: Set<string>): void {
343
+ into.add(pathKey(path))
344
+ const children = element.children ?? []
345
+ // A pruned view lists the kept children in order, but their indexes in the
346
+ // full tree are not 0..n; the view carries them by identity (see withRefs).
347
+ children.forEach((child, index) => {
348
+ collectShown(child, [...path, pathIndex(element, child, index)], into)
111
349
  })
112
350
  }
113
351
 
352
+ const ORIGINAL_INDEX = new WeakMap<UiElement, number>()
353
+ function pathIndex(_parent: UiElement, child: UiElement, fallback: number): number {
354
+ return ORIGINAL_INDEX.get(child) ?? fallback
355
+ }
356
+
357
+ /** The elements of a view with the adapter's refs in place of driver handles. */
358
+ function withRefs(
359
+ element: UiElement,
360
+ path: readonly number[],
361
+ refAt: (path: readonly number[]) => string,
362
+ ): UiElement {
363
+ const children = (element.children ?? []).map((child, index) =>
364
+ withRefs(child, [...path, pathIndex(element, child, index)], refAt),
365
+ )
366
+ const { children: _children, ...rest } = element
367
+ return Object.freeze({
368
+ ...rest,
369
+ ref: refAt(path),
370
+ ...(children.length > 0 ? { children: Object.freeze(children) } : {}),
371
+ }) as UiElement
372
+ }
373
+
114
374
  export class CuaDriverAdapter implements Adapter {
115
375
  readonly capabilities: ComputerUseCapabilities
116
376
  readonly backend: string
117
377
  private readonly client: McpStdioClient
118
378
  /** Window id → owning pid, from the latest list; `bring_to_front` needs both. */
119
379
  private readonly windowPids = new Map<string, number>()
380
+ /** Window id → application name, for naming the program a foreground burst is for. */
381
+ private readonly windowApps = new Map<string, string>()
382
+ private readonly foreground: ForegroundLadder | undefined
383
+ private readonly presence: Presence | undefined
384
+ /** False once the driver would not switch its own cursor off: Namzu's is then not shown, so there is never a second one. */
385
+ private driverCursorOff: boolean | undefined
120
386
  /** cua-driver's screenshot resize registry is per PID, so only this capture may drive input. */
121
387
  private windowFrame: WindowCaptureFrame | undefined
122
388
  /** Capture and scoped input must not race over cua-driver's per-PID resize ratio. */
123
389
  private windowOperation: Promise<void> = Promise.resolve()
124
- /** Only refs from the latest snapshot may address driver tokens. */
390
+ /** Refs the model holds, by the adapter's ref. A handle is usable only in its window's latest read; otherwise the ref is found again. */
125
391
  private uiRefs = new Map<string, UiRefEntry>()
392
+ /** Per window: the latest read of its tree, which is the only one its driver handles belong to. */
393
+ private readonly windowReads = new Map<number, { seq: number; at: number }>()
126
394
  private readonly uiRefNamespace = randomUUID()
127
- private nextSnapshot = 0
395
+ private nextRead = 0
396
+ private nextRef = 0
397
+ private readonly now: () => number
398
+ private readonly settle: (ms: number) => Promise<void>
128
399
  /** A successful revival invalidates refusals from the previous lifecycle episode. */
129
400
  private sessionGeneration = 0
130
401
  /** Share one revival among calls refused by the same expired implicit session. */
@@ -132,6 +403,10 @@ export class CuaDriverAdapter implements Adapter {
132
403
 
133
404
  constructor(options: CuaDriverAdapterOptions) {
134
405
  this.backend = `cua-driver${options.version ? ` ${options.version}` : ''}`
406
+ this.foreground = options.foreground
407
+ this.presence = options.presence
408
+ this.now = options.now ?? Date.now
409
+ this.settle = options.settle ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)))
135
410
  this.client = new McpStdioClient({
136
411
  command: options.executable,
137
412
  args: ['mcp'],
@@ -141,7 +416,9 @@ export class CuaDriverAdapter implements Adapter {
141
416
  requestTimeoutMs: options.requestTimeoutMs ?? 15_000,
142
417
  startTimeoutMs: options.startTimeoutMs ?? 30_000,
143
418
  spawnProcess: options.spawnProcess,
144
- afterStart: disableAgentCursor,
419
+ afterStart: async (call) => {
420
+ this.driverCursorOff = await disableAgentCursor(call)
421
+ },
145
422
  })
146
423
  this.capabilities = Object.freeze({
147
424
  displayServer: 'win32',
@@ -209,15 +486,14 @@ export class CuaDriverAdapter implements Adapter {
209
486
  })
210
487
  return { type: 'ok' }
211
488
  case 'mouse_click':
212
- await this.pointer('click', {
489
+ return this.pointer('click', {
213
490
  scope: 'desktop',
214
491
  x: action.at.x,
215
492
  y: action.at.y,
216
493
  button: action.button,
217
494
  })
218
- return { type: 'ok' }
219
495
  case 'mouse_drag':
220
- await this.pointer('drag', {
496
+ return this.pointer('drag', {
221
497
  scope: 'desktop',
222
498
  from_x: action.from.x,
223
499
  from_y: action.from.y,
@@ -227,12 +503,12 @@ export class CuaDriverAdapter implements Adapter {
227
503
  duration_ms: DRAG.durationMs,
228
504
  steps: DRAG.steps,
229
505
  })
230
- return { type: 'ok' }
231
506
  case 'scroll': {
232
507
  let remaining = Math.max(1, Math.trunc(action.amount))
508
+ let last: ComputerUseResult = { type: 'ok' }
233
509
  while (remaining > 0) {
234
510
  const ticks = Math.min(remaining, MAX_SCROLL_TICKS)
235
- await this.pointer('scroll', {
511
+ last = await this.pointer('scroll', {
236
512
  scope: 'desktop',
237
513
  x: action.at.x,
238
514
  y: action.at.y,
@@ -241,44 +517,48 @@ export class CuaDriverAdapter implements Adapter {
241
517
  })
242
518
  remaining -= ticks
243
519
  }
244
- return { type: 'ok' }
520
+ return last
245
521
  }
246
522
  case 'type_text':
247
- if (action.text.length > 0) {
248
- await this.callTool('type_text', {
249
- scope: 'desktop',
250
- text: action.text,
251
- })
252
- }
253
- return { type: 'ok' }
523
+ if (action.text.length === 0) return { type: 'ok' }
524
+ return this.keyboard('type_text', {
525
+ scope: 'desktop',
526
+ text: action.text,
527
+ })
254
528
  case 'key': {
255
529
  const plan = translateKeyForCuaDriver(action.keys)
256
- if (plan.tool === 'type_text') {
257
- await this.callTool('type_text', {
530
+ if (plan.tool === 'type_text')
531
+ return this.keyboard('type_text', {
258
532
  scope: 'desktop',
259
533
  text: plan.text,
260
534
  })
261
- } else if (plan.tool === 'press_key') {
262
- await this.callTool('press_key', { scope: 'desktop', key: plan.key })
263
- } else {
264
- await this.callTool('hotkey', {
535
+ if (plan.tool === 'press_key')
536
+ return this.keyboard('press_key', {
265
537
  scope: 'desktop',
266
- keys: [...plan.keys],
538
+ key: plan.key,
267
539
  })
268
- }
269
- return { type: 'ok' }
540
+ return this.keyboard('hotkey', {
541
+ scope: 'desktop',
542
+ keys: [...plan.keys],
543
+ })
270
544
  }
271
545
  }
272
546
  }
273
547
 
274
548
  async listWindows(): Promise<readonly WindowInfo[]> {
549
+ // The model is about to work in a window: have the overlay ready for its first action.
550
+ this.tryPresence((presence) => presence.warm())
275
551
  const listed = structured(
276
552
  await this.callTool('list_windows', {}, LIST_TIMEOUT_MS),
277
553
  'list_windows',
278
554
  )
279
555
  const windows = toWindowInfos(listed.windows)
280
556
  this.windowPids.clear()
281
- for (const window of windows) this.windowPids.set(window.id, window.pid)
557
+ this.windowApps.clear()
558
+ for (const window of windows) {
559
+ this.windowPids.set(window.id, window.pid)
560
+ this.windowApps.set(window.id, window.app)
561
+ }
282
562
  return windows
283
563
  }
284
564
 
@@ -406,11 +686,258 @@ export class CuaDriverAdapter implements Adapter {
406
686
  }
407
687
  }
408
688
 
409
- async executeWindow(captureId: string, action: WindowInputAction): Promise<void> {
689
+ async executeWindow(
690
+ captureId: string,
691
+ action: WindowInputAction,
692
+ ): Promise<WindowInputResult | undefined> {
410
693
  return this.serializeWindowOperation(() => this.executeWindowInternal(captureId, action))
411
694
  }
412
695
 
413
- private async executeWindowInternal(captureId: string, action: WindowInputAction): Promise<void> {
696
+ /**
697
+ * One window input, then a check of what the window shows. The driver
698
+ * cannot confirm a background input, so one it left unconfirmed is judged
699
+ * by reading the window before and after (see `observe.ts`).
700
+ *
701
+ * An input that provably had no effect (the window did not change at all)
702
+ * is sent once more, on the screen through the foreground ladder, and
703
+ * judged again; one that changed the window in a way that cannot be tied to
704
+ * it is never sent twice (see `escalation.ts`).
705
+ */
706
+ private async executeWindowInternal(
707
+ captureId: string,
708
+ action: WindowInputAction,
709
+ ): Promise<WindowInputResult | undefined> {
710
+ const first: InputRoute = { foreground: false, onScreen: false }
711
+ const result = await this.attemptWindowInput(captureId, action, first)
712
+ if (!result || !canBeJudgedByStillness(action)) return result
713
+ const summary: AttemptSummary = {
714
+ delivery: result.delivery,
715
+ retrySafety: result.retrySafety,
716
+ ...(result.detail !== undefined ? { detail: result.detail } : {}),
717
+ ...(first.outcome ? { outcome: first.outcome } : {}),
718
+ onScreen: first.onScreen,
719
+ }
720
+ const explicit = 'delivery_mode' in action ? action.delivery_mode : undefined
721
+ if (
722
+ !shouldRetryOnScreen(summary, {
723
+ hasScreen: this.foreground !== undefined,
724
+ explicitMode: explicit,
725
+ })
726
+ )
727
+ return result
728
+ // The retry is made once; its answer is final.
729
+ const second: InputRoute = { foreground: true, onScreen: false }
730
+ const again = await this.attemptWindowInput(captureId, action, second)
731
+ if (!again) return result
732
+ const finalDetail = escalationDetail({
733
+ delivery: again.delivery,
734
+ retrySafety: again.retrySafety,
735
+ ...(again.detail !== undefined ? { detail: again.detail } : {}),
736
+ ...(second.outcome ? { outcome: second.outcome } : {}),
737
+ onScreen: second.onScreen,
738
+ ...(second.blocked !== undefined ? { blocked: second.blocked } : {}),
739
+ })
740
+ if (again.delivery === 'delivered_verified')
741
+ return { ...again, detail: [finalDetail, again.detail].filter(Boolean).join(' ') }
742
+ return { ...again, detail: finalDetail }
743
+ }
744
+
745
+ private async attemptWindowInput(
746
+ captureId: string,
747
+ action: WindowInputAction,
748
+ route: InputRoute,
749
+ ): Promise<WindowInputResult | undefined> {
750
+ const frame = this.windowFrame
751
+ const watched =
752
+ action.type === 'type_text' || action.type === 'key' || action.type === 'mouse_click'
753
+ const hwnd = frame && frame.id === captureId ? parseWindowId(frame.window.id) : undefined
754
+ const target = hwnd !== undefined && frame ? { hwnd, pid: frame.window.pid } : undefined
755
+ const typed =
756
+ action.type === 'type_text'
757
+ ? action.text
758
+ : action.type === 'key' && translateKeyForCuaDriver(action.keys).tool === 'type_text'
759
+ ? (translateKeyForCuaDriver(action.keys) as { text: string }).text
760
+ : undefined
761
+ // Text for a classic edit control goes by window message: it needs neither focus nor the screen.
762
+ if (
763
+ action.type === 'type_text' &&
764
+ action.text.length > 0 &&
765
+ frame &&
766
+ target &&
767
+ action.delivery_mode !== 'foreground' &&
768
+ !route.foreground
769
+ ) {
770
+ const byMessage = await this.typeByMessages(frame, action.text)
771
+ if (byMessage) return byMessage
772
+ }
773
+ // A keyboard delivery that asked for the screen is judged by the edit control's own text, where there is one.
774
+ const editBefore =
775
+ typed !== undefined && frame && target && this.foreground
776
+ ? await this.foreground.editText({
777
+ hwnd: frame.window.id,
778
+ op: 'get',
779
+ pick: 'focus',
780
+ })
781
+ : undefined
782
+ let before: Observation | undefined
783
+ let earlier: Observation | undefined
784
+ let windows: ReadonlySet<string> | undefined
785
+ if (watched && target) {
786
+ // A press or a key has no text to look for, so it is attributed only if the window was still before it.
787
+ if (typed === undefined) earlier = await this.observe(target)
788
+ before = await this.observe(target)
789
+ // A new window of the program is an effect of a press and the sign of one for a text.
790
+ windows = await this.windowIdsOf(target.pid)
791
+ }
792
+ // A shortcut that stands for a command of the window's classic menu is that command, sent as the message
793
+ // the menu item sends: no key is pressed and the screen is not used.
794
+ const byMenu =
795
+ action.type === 'key' &&
796
+ frame &&
797
+ target &&
798
+ action.delivery_mode !== 'foreground' &&
799
+ !route.foreground
800
+ ? await this.shortcutByMenu(frame, action.keys)
801
+ : undefined
802
+ const sent = byMenu ?? (await this.deliverWindowInput(captureId, action, route))
803
+ let edit: EditStill | undefined
804
+ if (
805
+ sent?.delivery === 'delivered_unverified' &&
806
+ editBefore?.found &&
807
+ typed !== undefined &&
808
+ frame
809
+ ) {
810
+ const editAfter = await this.foreground?.editText({
811
+ hwnd: frame.window.id,
812
+ op: 'get',
813
+ pick: 'focus',
814
+ })
815
+ const verdict = editAfter?.found ? judgeEditBetween(typed, editBefore, editAfter) : undefined
816
+ if (verdict)
817
+ return {
818
+ delivery: verdict.delivery,
819
+ retrySafety: verdict.retrySafety,
820
+ detail: verdict.detail,
821
+ ...(verdict.observed !== undefined ? { readBack: { observed: verdict.observed } } : {}),
822
+ }
823
+ edit = !editAfter?.found
824
+ ? 'unknown'
825
+ : editAfter.len === editBefore.len && editAfter.text === editBefore.text
826
+ ? 'unchanged'
827
+ : 'changed'
828
+ }
829
+ if (!sent || sent.delivery !== 'delivered_unverified' || !target || !before) return sent
830
+ const seen = await this.verifyByReading(target, {
831
+ typed,
832
+ before,
833
+ earlier,
834
+ windows,
835
+ edit,
836
+ // A command the app was handed by message is delivered; a window that did not change shows no missing effect, so it is never sent again.
837
+ stillness: byMenu === undefined && canBeJudgedByStillness(action),
838
+ })
839
+ if (!seen) return sent
840
+ // A person at the keyboard or mouse during a burst can change the window: it proves nothing.
841
+ if (seen.outcome && route.interfered) return sent
842
+ if (seen.outcome) route.outcome = seen.outcome
843
+ return {
844
+ delivery: seen.delivery,
845
+ retrySafety: seen.retrySafety,
846
+ detail: seen.outcome ? [seen.detail, sent.detail].filter(Boolean).join(' ') : seen.detail,
847
+ ...(seen.observed !== undefined ? { readBack: { observed: seen.observed } } : {}),
848
+ }
849
+ }
850
+
851
+ /**
852
+ * Read the window again until it shows an effect of the input, a few
853
+ * times with a short wait between (the effect of an input arrives after it
854
+ * returns), then once more to see that it held still.
855
+ */
856
+ private async verifyByReading(
857
+ target: { hwnd: number; pid: number },
858
+ reads: {
859
+ typed: string | undefined
860
+ before: Observation
861
+ earlier: Observation | undefined
862
+ /** The program's windows before the input: a new one afterwards (a dialog) is its effect. */
863
+ windows: ReadonlySet<string> | undefined
864
+ /** What the text control the text went to reads now against before, where one was read. */
865
+ edit?: EditStill | undefined
866
+ /** Say, when no effect shows, whether the window held still (a window input) or leave it unsaid (a control's own action). */
867
+ stillness?: boolean
868
+ },
869
+ ): Promise<ObservedVerdict | undefined> {
870
+ const afters: Observation[] = []
871
+ for (const wait of OBSERVE_WAITS_MS) {
872
+ if (wait > 0) await this.settle(wait)
873
+ const opened = reads.windows ? await this.newWindowOf(target.pid, reads.windows) : undefined
874
+ if (opened)
875
+ return {
876
+ delivery: 'delivered_verified',
877
+ retrySafety: 'unsafe',
878
+ ...(opened.title.trim() !== '' ? { observed: opened.title.trim() } : {}),
879
+ detail: 'A new window of the same program opened after the input.',
880
+ }
881
+ const after = await this.observe(target)
882
+ if (!after) return undefined
883
+ afters.push(after)
884
+ if (sameObservation(reads.before, after)) continue
885
+ const later = reads.typed === undefined ? await this.observe(target) : undefined
886
+ const verdict = judgeObserved(reads.typed !== undefined ? { typed: reads.typed } : {}, {
887
+ before: reads.before,
888
+ after,
889
+ ...(later ? { later } : {}),
890
+ ...(reads.earlier ? { earlier: reads.earlier } : {}),
891
+ })
892
+ if (verdict) return verdict
893
+ }
894
+ if (!reads.stillness) return undefined
895
+ return judgeStillness({
896
+ before: reads.before,
897
+ ...(reads.earlier ? { earlier: reads.earlier } : {}),
898
+ afters,
899
+ opened: false,
900
+ ...(reads.edit ? { edit: reads.edit } : {}),
901
+ })
902
+ }
903
+
904
+ private async windowIdsOf(pid: number): Promise<ReadonlySet<string> | undefined> {
905
+ try {
906
+ return new Set((await this.listWindows()).filter((w) => w.pid === pid).map((w) => w.id))
907
+ } catch {
908
+ return undefined
909
+ }
910
+ }
911
+
912
+ private async newWindowOf(
913
+ pid: number,
914
+ known: ReadonlySet<string>,
915
+ ): Promise<WindowInfo | undefined> {
916
+ try {
917
+ return (await this.listWindows()).find((w) => w.pid === pid && !known.has(w.id))
918
+ } catch {
919
+ return undefined
920
+ }
921
+ }
922
+
923
+ /** A fresh read of a window, as the texts it shows; undefined when the read failed. Refs the model holds are kept pointing at their controls. */
924
+ private async observe(target: { hwnd: number; pid: number }): Promise<Observation | undefined> {
925
+ try {
926
+ const read = await this.readWindowTree(target, {})
927
+ this.bindRead(target, read, { shown: new Set(), regions: new Set() })
928
+ return observationOf(read.tree, {
929
+ walkCut: read.state.truncated === true || read.tree.count >= UI_WALK_CUT_AT,
930
+ })
931
+ } catch {
932
+ return undefined
933
+ }
934
+ }
935
+
936
+ private async deliverWindowInput(
937
+ captureId: string,
938
+ action: WindowInputAction,
939
+ route: InputRoute = { foreground: false, onScreen: false },
940
+ ): Promise<WindowInputResult | undefined> {
414
941
  const frame = this.windowFrame
415
942
  if (!frame || frame.id !== captureId)
416
943
  throw new Error(
@@ -437,7 +964,7 @@ export class CuaDriverAdapter implements Adapter {
437
964
  pid: frame.window.pid,
438
965
  window_id: parseWindowId(frame.window.id),
439
966
  } as const
440
- const call = async (name: string, args: Record<string, unknown>) => {
967
+ const call = async (name: string, args: Record<string, unknown>): Promise<McpToolResult> => {
441
968
  const windows = await this.listWindows()
442
969
  const current = windows.find((window) => window.id === frame.window.id)
443
970
  if (
@@ -452,19 +979,132 @@ export class CuaDriverAdapter implements Adapter {
452
979
  throw new Error(
453
980
  'computer-use: the captured window changed or its driver restarted; take a new window screenshot.',
454
981
  )
455
- await this.callTool(name, { ...target, ...args }, undefined, undefined, undefined, frame)
982
+ this.showPresence(frame, current.bounds, name, args)
983
+ return this.callTool(name, { ...target, ...args }, undefined, undefined, undefined, frame)
456
984
  }
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)
985
+ // The driver's hotkey finds a shortcut only through an accelerator the window names, and refuses (sending
986
+ // nothing) when there is none; the same combination as a key with modifiers is real input.
987
+ const dispatch = async (
988
+ name: string,
989
+ args: Record<string, unknown>,
990
+ ): Promise<McpToolResult> => {
991
+ try {
992
+ return await call(name, args)
993
+ } catch (error) {
994
+ const keys = args.keys
995
+ if (
996
+ name === 'hotkey' &&
997
+ Array.isArray(keys) &&
998
+ keys.length > 1 &&
999
+ error instanceof McpToolError &&
1000
+ /AcceleratorKey/i.test(error.message)
1001
+ ) {
1002
+ const { keys: _keys, ...rest } = args
1003
+ return await call('press_key', {
1004
+ ...rest,
1005
+ key: keys[keys.length - 1],
1006
+ modifiers: keys.slice(0, -1),
1007
+ })
463
1008
  }
464
- return
465
- case 'mouse_drag':
466
- try {
467
- await call('drag', {
1009
+ throw error
1010
+ }
1011
+ }
1012
+ // One window input: in the background first. A refusal that foreground
1013
+ // delivery can cure (the window cannot take background input, or it is
1014
+ // covered) is retried through the ladder; an explicit foreground request
1015
+ // goes through it too. The result says which happened.
1016
+ const send = async (
1017
+ name: string,
1018
+ args: Record<string, unknown>,
1019
+ ): Promise<WindowInputResult> => {
1020
+ const subject = {
1021
+ app: this.windowApps.get(frame.window.id) ?? frame.window.app,
1022
+ pid: frame.window.pid,
1023
+ hwnd: frame.window.id,
1024
+ }
1025
+ const inForeground = async (why: string, tries = 0): Promise<WindowInputResult> => {
1026
+ const ladder = this.foreground as ForegroundLadder
1027
+ const outcome = await ladder
1028
+ .run(this.burstRequest(subject, true), async (burst) => {
1029
+ await burst.checkpoint()
1030
+ try {
1031
+ return inputDelivery(await dispatch(name, { ...args, delivery_mode: 'foreground' }))
1032
+ } catch (error) {
1033
+ if (isDeliveredPointerAction(error)) return foregroundLostDelivery()
1034
+ if (error instanceof McpToolError) return failureDelivery(error)
1035
+ throw error
1036
+ }
1037
+ })
1038
+ .catch((error: unknown) => {
1039
+ if (error instanceof BurstInterrupted) return error
1040
+ throw error
1041
+ })
1042
+ // A person's input just before the send stopped the burst with nothing sent: the next pause is waited
1043
+ // for by the ladder's own gate, and the input goes then. Bounded; after it the result says so.
1044
+ if (
1045
+ outcome instanceof BurstInterrupted &&
1046
+ outcome.reason === 'person' &&
1047
+ tries < PAUSE_RETRIES
1048
+ )
1049
+ return inForeground(why, tries + 1)
1050
+ if (outcome instanceof BurstInterrupted) {
1051
+ route.blocked = outcome.reason === 'person' ? 'user_active' : 'elevated_target'
1052
+ return verdict(
1053
+ 'not_delivered',
1054
+ 'safe',
1055
+ outcome.reason === 'person'
1056
+ ? 'a person used the keyboard or mouse just before the input was sent, so nothing was sent. Try again in a moment.'
1057
+ : 'an administrator window came to the front just before the input was sent, so nothing was sent. Namzu cannot type into it; try again once it is gone.',
1058
+ )
1059
+ }
1060
+ if (outcome.kind === 'blocked') {
1061
+ route.blocked = outcome.block.code
1062
+ return verdict('not_delivered', 'safe', outcome.block.detail)
1063
+ }
1064
+ route.onScreen = true
1065
+ const dropped = droppedInputNote(outcome)
1066
+ if (dropped) return verdict('not_delivered', 'safe', dropped)
1067
+ const note = interferenceNote(outcome)
1068
+ const base = outcome.value
1069
+ if (note) route.interfered = true
1070
+ if (note)
1071
+ return verdict(
1072
+ base.delivery === 'not_delivered' ? 'not_delivered' : 'delivered_unverified',
1073
+ base.delivery === 'not_delivered' ? base.retrySafety : 'unsafe',
1074
+ [base.detail, note].filter(Boolean).join(' '),
1075
+ )
1076
+ return {
1077
+ ...base,
1078
+ detail: [base.detail, why === '' ? undefined : foregroundNote(outcome)]
1079
+ .filter(Boolean)
1080
+ .join(' '),
1081
+ }
1082
+ }
1083
+ if ((args.delivery_mode === 'foreground' || route.foreground) && this.foreground)
1084
+ return inForeground('')
1085
+ try {
1086
+ return inputDelivery(await dispatch(name, args))
1087
+ } catch (error) {
1088
+ if (error instanceof McpToolError && this.foreground && foregroundCures(error))
1089
+ return inForeground('refused')
1090
+ throw error
1091
+ }
1092
+ }
1093
+ try {
1094
+ switch (action.type) {
1095
+ case 'mouse_click':
1096
+ try {
1097
+ return await send('click', {
1098
+ x: action.at.x,
1099
+ y: action.at.y,
1100
+ button: action.button,
1101
+ })
1102
+ } catch (error) {
1103
+ if (isDeliveredPointerAction(error)) return foregroundLostDelivery()
1104
+ throw error
1105
+ }
1106
+ case 'mouse_drag':
1107
+ return await send('drag', {
468
1108
  from_x: action.from.x,
469
1109
  from_y: action.from.y,
470
1110
  to_x: action.to.x,
@@ -473,40 +1113,137 @@ export class CuaDriverAdapter implements Adapter {
473
1113
  duration_ms: DRAG.durationMs,
474
1114
  steps: DRAG.steps,
475
1115
  })
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', {
1116
+ case 'scroll':
1117
+ throw new Error(
1118
+ '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.',
1119
+ )
1120
+ case 'type_text': {
1121
+ if (action.text.length === 0) return undefined
1122
+ return await send('type_text', {
487
1123
  text: action.text,
488
1124
  ...(action.delivery_mode ? { delivery_mode: action.delivery_mode } : {}),
489
1125
  })
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
1126
+ }
1127
+ case 'key': {
1128
+ const plan = translateKeyForCuaDriver(action.keys)
1129
+ const delivery = action.delivery_mode ? { delivery_mode: action.delivery_mode } : {}
1130
+ if (plan.tool === 'type_text')
1131
+ return await send('type_text', { text: plan.text, ...delivery })
1132
+ if (plan.tool === 'press_key')
1133
+ return await send('press_key', { key: plan.key, ...delivery })
1134
+ return await send('hotkey', { keys: [...plan.keys], ...delivery })
1135
+ }
498
1136
  }
1137
+ } catch (error) {
1138
+ // The driver answered with a refusal or a tool error: it says what it
1139
+ // did not do, and that is a typed result, not a crash.
1140
+ if (error instanceof McpToolError) return failureDelivery(error)
1141
+ throw error
499
1142
  }
500
1143
  }
501
1144
 
502
1145
  /**
503
1146
  * One window's controls. Without an id, the window in front — which,
504
1147
  * for an agent run from a terminal, is usually that terminal.
1148
+ *
1149
+ * A window with many controls comes back as an outline: the top levels,
1150
+ * with each unexpanded region marked by how many children it hides and
1151
+ * given a ref. `options.root` opens one such region; refs outside it stay
1152
+ * valid. `options.query` keeps only the controls whose text matches.
505
1153
  */
506
- async uiSnapshot(windowId?: string): Promise<UiSnapshot> {
1154
+ async uiSnapshot(requested?: string, options: UiSnapshotOptions = {}): Promise<UiSnapshot> {
1155
+ let windowId = requested
1156
+ let rootEntry: UiRefEntry | undefined
1157
+ if (options.root !== undefined) {
1158
+ rootEntry = this.uiRefs.get(options.root)
1159
+ if (!rootEntry)
1160
+ throw new Error(
1161
+ `STALE_REF: ${options.root} is not a region or control this session was shown. Take a ui_snapshot of the window and use a ref from it.`,
1162
+ )
1163
+ const own = windowIdOf(rootEntry.hwnd)
1164
+ if (windowId !== undefined && parseWindowId(windowId) !== rootEntry.hwnd)
1165
+ throw new Error(
1166
+ `${options.root} belongs to window ${own}, not ${windowId}. Pass the window it came from, or leave window_id out.`,
1167
+ )
1168
+ windowId = own
1169
+ }
507
1170
  const target = await this.resolveWindow(windowId)
1171
+ if (rootEntry && rootEntry.pid !== target.pid)
1172
+ throw new Error(
1173
+ `STALE_REF: window ${windowIdOf(target.hwnd)} now belongs to a different program than ${options.root} was read from. Take a new ui_snapshot.`,
1174
+ )
1175
+ const query = options.query?.trim() ? options.query.trim() : undefined
1176
+ let read = await this.readWindowTree(target, { query })
1177
+ const state0 = read.state
1178
+ const app0 = typeof state0.app_name === 'string' ? state0.app_name : ''
1179
+ // A browser builds its page tree when it is first asked: the first walk can
1180
+ // show only the window frame. One more walk shows the page.
1181
+ if (!query && !rootEntry && BROWSER_APP.test(app0) && read.tree.count < SPARSE_TREE)
1182
+ read = await this.readWindowTree(target, { query })
1183
+ const { state, tree } = read
1184
+
1185
+ let located: UiNode | undefined
1186
+ if (rootEntry) {
1187
+ const found = locate(rootEntry, tree, { actionable: !rootEntry.region })
1188
+ if (found.kind === 'ambiguous')
1189
+ throw new Error(
1190
+ `AMBIGUOUS_TARGET: ${fitText(found.count)} ${options.root} (${describeEvidence(rootEntry)}). Take a ui_snapshot of the whole window and pick the region from it.`,
1191
+ )
1192
+ if (found.kind === 'gone')
1193
+ throw new Error(
1194
+ `STALE_REF: ${options.root} (${describeEvidence(rootEntry)}) is no longer in the window. Take a ui_snapshot of the whole window.`,
1195
+ )
1196
+ located = found.node
1197
+ }
1198
+ const viewRoot = located?.element ?? tree.root
1199
+ const basePath = located?.path ?? []
1200
+ const view =
1201
+ !query && visibleCount(viewRoot) > OUTLINE_THRESHOLD
1202
+ ? outlineOf(
1203
+ viewRoot,
1204
+ basePath,
1205
+ OUTLINE_BUDGET,
1206
+ located ? { offset: options.offset ?? 0 } : undefined,
1207
+ )
1208
+ : { root: viewRoot, regions: new Set<string>(), next: undefined }
1209
+ const shownKeys = new Set<string>()
1210
+ collectShown(view.root, basePath, shownKeys)
1211
+ const refs = this.bindRead(target, read, {
1212
+ shown: shownKeys,
1213
+ regions: view.regions,
1214
+ partial: query !== undefined,
1215
+ })
1216
+ const refAt = (path: readonly number[]): string => refs.get(pathKey(path)) ?? ''
1217
+ const root = withRefs(view.root, basePath, refAt)
1218
+
1219
+ const title = typeof state.window_title === 'string' ? state.window_title : undefined
1220
+ const app =
1221
+ typeof state.app_name === 'string' ? state.app_name.replace(/\.exe$/i, '') : undefined
1222
+ return {
1223
+ windowId: windowIdOf(target.hwnd),
1224
+ ...(title !== undefined ? { title } : {}),
1225
+ ...(app !== undefined ? { app } : {}),
1226
+ root,
1227
+ ...(state.truncated === true || tree.count >= UI_WALK_CUT_AT ? { truncated: true } : {}),
1228
+ ...(view.regions.size > 0 ? { outline: true } : {}),
1229
+ total: tree.count,
1230
+ ...(rootEntry ? { region: true } : {}),
1231
+ ...(view.next !== undefined ? { next: view.next } : {}),
1232
+ }
1233
+ }
1234
+
1235
+ /** One `get_window_state` walk, with the process and session it was read from. */
1236
+ private async readWindowTree(
1237
+ target: { hwnd: number; pid: number },
1238
+ options: { query?: string | undefined } = {},
1239
+ ): Promise<{
1240
+ state: Record<string, unknown>
1241
+ tree: ParsedUiTree
1242
+ processStarts: number
1243
+ generation: number
1244
+ }> {
508
1245
  let processStarts = 0
509
- let snapshotGeneration = this.sessionGeneration
1246
+ let generation = this.sessionGeneration
510
1247
  const state = structured(
511
1248
  await this.callTool(
512
1249
  'get_window_state',
@@ -515,72 +1252,263 @@ export class CuaDriverAdapter implements Adapter {
515
1252
  window_id: target.hwnd,
516
1253
  include_screenshot: false,
517
1254
  max_elements: UI_MAX_ELEMENTS,
1255
+ // Since 0.35 the structured `elements` array is left out unless
1256
+ // asked for; the tree is built from both it and the markdown.
1257
+ full_output: true,
1258
+ ...(options.query ? { query: options.query } : {}),
518
1259
  },
519
1260
  UI_TREE_TIMEOUT_MS,
520
1261
  undefined,
521
1262
  (starts) => {
522
1263
  processStarts = starts
523
- snapshotGeneration = this.sessionGeneration
1264
+ generation = this.sessionGeneration
524
1265
  },
525
1266
  ),
526
1267
  'get_window_state',
527
1268
  )
528
- if (snapshotGeneration !== this.sessionGeneration || processStarts === 0)
1269
+ if (generation !== this.sessionGeneration || processStarts === 0)
529
1270
  throw new McpToolError('get_window_state', 'stale UI snapshot; take a new one')
530
- const tree = toUiTree(state)
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,
1271
+ if (typeof state.pid === 'number' && state.pid !== target.pid)
1272
+ throw new McpToolError('get_window_state', 'window changed owner; take a new UI snapshot')
1273
+ return { state, tree: toUiTree(state), processStarts, generation }
1274
+ }
1275
+
1276
+ /**
1277
+ * Record a read of a window: every ref the model already holds for it is
1278
+ * pointed at the control it named in this read (found by its evidence),
1279
+ * and the controls the model is being shown, and the regions it can open,
1280
+ * get refs. A ref whose control is not found keeps its old, now dead,
1281
+ * read, so using it re-resolves and reports why. Returns ref by path.
1282
+ */
1283
+ private bindRead(
1284
+ target: { hwnd: number; pid: number },
1285
+ read: { tree: ParsedUiTree; processStarts: number; generation: number },
1286
+ scope: {
1287
+ shown: ReadonlySet<string>
1288
+ regions: ReadonlySet<string>
1289
+ /** A filtered (query) read: its places are not the window's, so it records no places. */
1290
+ partial?: boolean
1291
+ },
1292
+ ): Map<string, string> {
1293
+ const seq = ++this.nextRead
1294
+ const at = this.now()
1295
+ this.windowReads.set(target.hwnd, { seq, at })
1296
+ const byPath = new Map<string, string>()
1297
+ const claimed = new Set<string>()
1298
+ const named = new Map<string, number>()
1299
+ for (const node of read.tree.nodes) {
1300
+ const key = `${node.role}\u0000${node.name.trim()}`
1301
+ named.set(key, (named.get(key) ?? 0) + 1)
1302
+ }
1303
+ const bound = (node: UiNode, entry: UiRefEntry, ref: string): void => {
1304
+ const key = pathKey(node.path)
1305
+ claimed.add(key)
1306
+ byPath.set(key, ref)
1307
+ const twin =
1308
+ node.automationId === undefined &&
1309
+ node.name.trim() !== '' &&
1310
+ (named.get(`${node.role}\u0000${node.name.trim()}`) ?? 0) > 1
1311
+ this.uiRefs.set(ref, {
1312
+ ...(node.facts ?? factsOfNode(node)),
1313
+ twin,
1314
+ ...(scope.partial
1315
+ ? {}
1316
+ : {
1317
+ childCount: node.element.children?.length ?? 0,
1318
+ treeSig: read.tree.signature,
1319
+ }),
1320
+ token: node.token,
539
1321
  pid: target.pid,
540
- generation: snapshotGeneration,
541
- processStarts,
1322
+ hwnd: target.hwnd,
1323
+ region: entry.region,
1324
+ ...(node.element.bounds ? { bounds: node.element.bounds } : {}),
1325
+ generation: read.generation,
1326
+ processStarts: read.processStarts,
1327
+ readSeq: seq,
1328
+ readAt: at,
542
1329
  })
543
- return ref
544
- })
545
- this.uiRefs = refs
546
- const title = typeof state.window_title === 'string' ? state.window_title : undefined
547
- const app =
548
- typeof state.app_name === 'string' ? state.app_name.replace(/\.exe$/i, '') : undefined
1330
+ }
1331
+ // A filtered read has other places than the window; it only adds refs.
1332
+ // A handle another program reuses is not the window the ref came from.
1333
+ if (!scope.partial) {
1334
+ for (const [ref, entry] of [...this.uiRefs]) {
1335
+ if (entry.hwnd !== target.hwnd || entry.pid !== target.pid) continue
1336
+ const found = locate(entry, read.tree, { actionable: !entry.region })
1337
+ if (found.kind !== 'found' || claimed.has(pathKey(found.node.path))) continue
1338
+ bound(found.node, entry, ref)
1339
+ }
1340
+ }
1341
+ let created = 0
1342
+ for (const node of read.tree.nodes) {
1343
+ const key = pathKey(node.path)
1344
+ if (claimed.has(key)) continue
1345
+ const region = scope.regions.has(key)
1346
+ const actionable = node.token !== '' && scope.shown.has(key)
1347
+ if (!region && !actionable) continue
1348
+ // A match set larger than the ref budget would evict its own refs.
1349
+ if (created >= NEW_REFS_PER_READ) break
1350
+ created++
1351
+ const ref = `cua-ui:${this.uiRefNamespace}:${++this.nextRef}`
1352
+ const entry = { region: !actionable } as UiRefEntry
1353
+ bound(node, entry, ref)
1354
+ }
1355
+ this.trimRefs(seq)
1356
+ return byPath
1357
+ }
1358
+
1359
+ /** The model holds only so many refs; the oldest reads go first. */
1360
+ private trimRefs(keepSeq: number): void {
1361
+ if (this.uiRefs.size <= MAX_REFS) return
1362
+ // The read that just answered keeps every ref it handed out.
1363
+ const oldest = [...this.uiRefs]
1364
+ .filter(([, entry]) => entry.readSeq !== keepSeq)
1365
+ .sort((a, b) => a[1].readSeq - b[1].readSeq)
1366
+ for (const [ref] of oldest.slice(0, this.uiRefs.size - MAX_REFS)) this.uiRefs.delete(ref)
1367
+ }
1368
+
1369
+ /**
1370
+ * The ref's control as it is now: the entry itself when it was read
1371
+ * recently in the window's latest read, else found again in a fresh read
1372
+ * by its evidence (id, then place, then role and name). Never a guess:
1373
+ * several fits is AMBIGUOUS_TARGET, none is STALE_REF, and nothing has been
1374
+ * sent in either case.
1375
+ */
1376
+ private async resolveRef(
1377
+ ref: string,
1378
+ entry: UiRefEntry,
1379
+ ): Promise<{ entry: UiRefEntry } | { fail: UiActResult }> {
1380
+ const latest = this.windowReads.get(entry.hwnd)
1381
+ if (
1382
+ latest &&
1383
+ entry.readSeq === latest.seq &&
1384
+ entry.generation === this.sessionGeneration &&
1385
+ this.now() - entry.readAt <= IDENTITY_FRESH_MS
1386
+ )
1387
+ return { entry }
1388
+ const target = { hwnd: entry.hwnd, pid: entry.pid }
1389
+ let read: Awaited<ReturnType<CuaDriverAdapter['readWindowTree']>>
1390
+ try {
1391
+ read = await this.readWindowTree(target, {})
1392
+ } catch (error) {
1393
+ const gone = await this.windowIsGone(entry)
1394
+ if (gone)
1395
+ return {
1396
+ fail: refFailure(
1397
+ 'STALE_REF',
1398
+ `the window of ${describeEvidence(entry)} is closed. Nothing was sent. List the windows again.`,
1399
+ ),
1400
+ }
1401
+ return {
1402
+ fail: {
1403
+ ok: false,
1404
+ delivery: 'not_delivered',
1405
+ retrySafety: 'safe',
1406
+ detail: `the window could not be read to confirm ${describeEvidence(entry)} is still there, so nothing was sent${error instanceof Error ? ` (${trimText(error.message, 160)})` : ''}. Try again.`,
1407
+ },
1408
+ }
1409
+ }
1410
+ const found = locate(entry, read.tree, { actionable: true })
1411
+ this.bindRead(target, read, { shown: new Set(), regions: new Set() })
1412
+ const next = this.uiRefs.get(ref)
1413
+ if (found.kind === 'found' && next && next.readSeq === this.windowReads.get(entry.hwnd)?.seq)
1414
+ return { entry: next }
1415
+ if (found.kind === 'ambiguous' || found.kind === 'found')
1416
+ return {
1417
+ fail: refFailure(
1418
+ 'AMBIGUOUS_TARGET',
1419
+ `${found.kind === 'ambiguous' ? fitText(found.count) : 'several controls fit'} ${describeEvidence(entry)}, so nothing was sent. Take a ui_snapshot and use the ref of the one you mean.`,
1420
+ ),
1421
+ }
549
1422
  return {
550
- windowId: windowIdOf(target.hwnd),
551
- ...(title !== undefined ? { title } : {}),
552
- ...(app !== undefined ? { app } : {}),
553
- root,
554
- ...(state.truncated === true ? { truncated: true } : {}),
1423
+ fail: refFailure(
1424
+ 'STALE_REF',
1425
+ `${describeEvidence(entry)} is no longer in the window, or can no longer be acted on. Nothing was sent. Take a ui_snapshot and choose from what it shows.`,
1426
+ ),
1427
+ }
1428
+ }
1429
+
1430
+ /** Whether the ref's window has closed (or changed owner). Costs a window list, so only asked after a failure. */
1431
+ private async windowIsGone(entry: UiRefEntry): Promise<boolean> {
1432
+ try {
1433
+ const windows = await this.listWindows()
1434
+ const id = windowIdOf(entry.hwnd)
1435
+ const found = windows.find((window) => window.id === id)
1436
+ return !found || found.pid !== entry.pid
1437
+ } catch {
1438
+ return false
555
1439
  }
556
1440
  }
557
1441
 
558
1442
  async uiAct(ref: string, action: UiElementAction, value?: string): Promise<UiActResult> {
559
- const facts = this.uiRefs.get(ref)
560
- if (!facts)
1443
+ return this.actOn(ref, action, value, true)
1444
+ }
1445
+
1446
+ private async actOn(
1447
+ ref: string,
1448
+ action: UiElementAction,
1449
+ value: string | undefined,
1450
+ retry: boolean,
1451
+ ): Promise<UiActResult> {
1452
+ const held = this.uiRefs.get(ref)
1453
+ if (!held)
1454
+ return refFailure(
1455
+ 'STALE_REF',
1456
+ `${ref} is not a control this session was shown, so nothing was sent. Take a ui_snapshot and use a ref from it.`,
1457
+ )
1458
+ if (held.region)
561
1459
  return {
562
1460
  ok: false,
563
- detail: `${ref} is not a control of the latest UI snapshot; take a new one.`,
1461
+ delivery: 'not_delivered',
1462
+ retrySafety: 'safe',
1463
+ detail: `${ref} is a region of the window (${describeEvidence(held)}), not a control, so nothing was sent. Read it with ui_snapshot {root: ${ref}} and act on a control inside it.`,
564
1464
  }
1465
+ const resolved = await this.resolveRef(ref, held)
1466
+ if ('fail' in resolved) return resolved.fail
1467
+ const facts = resolved.entry
565
1468
  const { pid, token } = facts
566
1469
  const uiRef = { ref, facts }
1470
+ this.tryPresence((presence) =>
1471
+ presence.mark({
1472
+ hwnd: facts.hwnd,
1473
+ kind: action === 'set_value' ? 'type' : 'click',
1474
+ ...(facts.bounds
1475
+ ? {
1476
+ at: {
1477
+ x: facts.bounds.x + facts.bounds.width / 2,
1478
+ y: facts.bounds.y + facts.bounds.height / 2,
1479
+ },
1480
+ }
1481
+ : {}),
1482
+ }),
1483
+ )
567
1484
  try {
568
1485
  switch (action) {
569
1486
  case 'invoke':
570
- case 'toggle':
571
- case 'select':
572
1487
  case 'expand':
573
1488
  case 'collapse':
574
1489
  // cua-driver's click on an element token performs the control's
575
1490
  // own pattern in the background (Invoke, or a posted click at its
576
1491
  // centre), with no pointer move and no change of foreground.
577
- return actResult(
578
- await this.callTool('click', { pid, element_token: token }, undefined, uiRef),
579
- )
1492
+ return await this.clickAndWatch(facts, uiRef)
1493
+ case 'select': {
1494
+ // A row that can also be invoked is selected by its selection pattern: the driver's click on it invokes, and a file row would open.
1495
+ if (ITEM_ROLES.test(facts.role) && facts.actions.includes('invoke'))
1496
+ return await this.selectWithoutOpening(facts)
1497
+ const sent = await this.clickRef(facts, uiRef)
1498
+ if (!sent.ok) return sent
1499
+ return judgeSelect(facts, await this.readBack(facts))
1500
+ }
1501
+ case 'toggle': {
1502
+ const sent = await this.clickRef(facts, uiRef)
1503
+ if (!sent.ok) return sent
1504
+ const back = await this.readBack(facts)
1505
+ return judgeToggle(facts, back)
1506
+ }
580
1507
  case 'set_value': {
581
1508
  const text = value ?? ''
1509
+ let sent: UiActResult
582
1510
  try {
583
- return actResult(
1511
+ sent = actResult(
584
1512
  await this.callTool(
585
1513
  'set_value',
586
1514
  { pid, element_token: token, value: text },
@@ -590,51 +1518,443 @@ export class CuaDriverAdapter implements Adapter {
590
1518
  )
591
1519
  } catch (error) {
592
1520
  if (
593
- !(error instanceof McpToolError) ||
594
- !/does not implement ValuePattern/i.test(error.message)
595
- )
596
- throw error
597
- // A classic Win32 edit reports no ValuePattern. Typing into it
598
- // equals setting it only while it is empty.
599
- if (facts.value !== undefined && facts.value.length > 0)
1521
+ error instanceof McpToolError &&
1522
+ /does not implement ValuePattern/i.test(error.message)
1523
+ ) {
1524
+ // A classic edit control takes its text by window message, never by focus or keys.
1525
+ const edited = await this.setByMessages(facts, text)
1526
+ if (edited) return edited
1527
+ // Typing instead would equal setting only while the field is
1528
+ // empty, and the driver's own report of it is not trustworthy.
600
1529
  return {
601
1530
  ok: false,
1531
+ delivery: 'not_delivered',
1532
+ retrySafety: 'safe',
602
1533
  detail:
603
- 'this field cannot be set directly and already holds text; click it, select its text (CTRL+A) and type the new text instead',
1534
+ 'this field has no settable value, and nothing was typed. A classic edit control takes text through the keyboard: click it in a window screenshot, then type_text (add delivery_mode:"foreground" when background typing is not delivered).',
604
1535
  }
605
- const typed = actResult(
606
- await this.callTool(
607
- 'type_text',
608
- { pid, element_token: token, text },
609
- undefined,
610
- uiRef,
611
- ),
612
- )
613
- return typed.ok
614
- ? {
615
- ok: true,
616
- detail: 'typed into the empty field, which has no settable value',
617
- }
618
- : typed
1536
+ }
1537
+ throw error
619
1538
  }
1539
+ if (!sent.ok) return sent
1540
+ const judged = judgeSetValue(facts, text, await this.readBack(facts))
1541
+ // A choice in a list that ignored the driver is made with the keyboard, in the foreground.
1542
+ if (judged.delivery === 'not_delivered' && CHOICE_ROLES.test(facts.role))
1543
+ return await this.chooseByKeyboard(ref, facts, text, judged)
1544
+ return judged
620
1545
  }
621
1546
  case 'focus':
622
1547
  case 'scroll_into_view':
623
1548
  return {
624
1549
  ok: false,
1550
+ delivery: 'not_delivered',
1551
+ retrySafety: 'safe',
625
1552
  detail: `this host cannot ${action === 'focus' ? 'focus' : 'scroll to'} a control by itself; invoke it or click it instead`,
626
1553
  }
627
1554
  }
628
1555
  } catch (error) {
629
- if (error instanceof McpToolError) return { ok: false, detail: toolRefusal(error) }
1556
+ if (error instanceof McpToolError && isStaleHandle(error)) {
1557
+ // The driver refused before acting: a newer read of the window replaced
1558
+ // the handle. Read again and find the control by what it is, once.
1559
+ this.windowReads.delete(facts.hwnd)
1560
+ if (retry) return this.actOn(ref, action, value, false)
1561
+ return refFailure(
1562
+ 'STALE_REF',
1563
+ `${describeEvidence(facts)} changed while it was being acted on. Nothing was sent. Take a ui_snapshot and try again.`,
1564
+ )
1565
+ }
1566
+ if (error instanceof McpToolError) return failureResult(error)
630
1567
  throw error
631
1568
  }
632
1569
  }
633
1570
 
1571
+ /**
1572
+ * Choose an option by the keyboard, for a list the driver's value call did
1573
+ * not change (a web page's select element ignores it in the background).
1574
+ * One foreground burst focuses the control, types the option and confirms
1575
+ * it; the control is then read back. Where that does not work either, the
1576
+ * model is told which route to use instead.
1577
+ */
1578
+ private async chooseByKeyboard(
1579
+ ref: string,
1580
+ stale: UiRefEntry,
1581
+ option: string,
1582
+ unchanged: UiActResult,
1583
+ ): Promise<UiActResult> {
1584
+ const ladder = this.foreground
1585
+ const instead =
1586
+ 'The driver and the keyboard could not change this list. If this is a web page, use the browser tool for it; otherwise choose the option in a window screenshot with the pointer.'
1587
+ if (!ladder) return unchanged
1588
+ // The read-back that judged the value replaced the driver's handle: click through the new one.
1589
+ const facts = this.uiRefs.get(ref) ?? stale
1590
+ const uiRef = { ref, facts }
1591
+ const { pid } = facts
1592
+ const hwnd = windowIdOf(facts.hwnd)
1593
+ const subject = {
1594
+ app: this.windowApps.get(hwnd) ?? `process ${pid}`,
1595
+ pid,
1596
+ hwnd,
1597
+ }
1598
+ const scope = {
1599
+ scope: 'window',
1600
+ pid,
1601
+ window_id: facts.hwnd,
1602
+ delivery_mode: 'foreground',
1603
+ }
1604
+ const outcome = await ladder
1605
+ .run(this.burstRequest(subject, true), async (burst) => {
1606
+ await burst.checkpoint()
1607
+ try {
1608
+ await this.callTool(
1609
+ 'click',
1610
+ { pid, element_token: facts.token, delivery_mode: 'foreground' },
1611
+ undefined,
1612
+ uiRef,
1613
+ )
1614
+ await burst.checkpoint()
1615
+ await this.callTool('type_text', { ...scope, text: option })
1616
+ await burst.checkpoint()
1617
+ await this.callTool('press_key', { ...scope, key: 'return' })
1618
+ return undefined
1619
+ } catch (error) {
1620
+ if (error instanceof McpToolError) return failureResult(error)
1621
+ throw error
1622
+ }
1623
+ })
1624
+ .catch((error: unknown) => {
1625
+ if (error instanceof BurstInterrupted) return error
1626
+ throw error
1627
+ })
1628
+ if (outcome instanceof BurstInterrupted)
1629
+ return {
1630
+ ok: false,
1631
+ delivery: 'not_delivered',
1632
+ retrySafety: 'safe',
1633
+ detail:
1634
+ outcome.reason === 'person'
1635
+ ? 'a person used the keyboard or mouse just before the choice was made, so it may not have been. Try again in a moment.'
1636
+ : 'an administrator window came to the front just before the choice was made; Namzu cannot type into it. Try again once it is gone.',
1637
+ }
1638
+ if (outcome.kind === 'blocked')
1639
+ return {
1640
+ ok: false,
1641
+ delivery: 'not_delivered',
1642
+ retrySafety: 'safe',
1643
+ detail: `${outcome.block.detail} ${instead}`,
1644
+ }
1645
+ const dropped = droppedInputNote(outcome)
1646
+ if (dropped)
1647
+ return {
1648
+ ok: false,
1649
+ delivery: 'not_delivered',
1650
+ retrySafety: 'safe',
1651
+ detail: `${dropped} ${instead}`,
1652
+ }
1653
+ const note = interferenceNote(outcome)
1654
+ if (outcome.value && !outcome.value.ok) return outcome.value
1655
+ const judged = judgeSetValue(facts, option, await this.readBack(facts))
1656
+ if (note)
1657
+ return {
1658
+ ...judged,
1659
+ delivery: 'delivered_unverified',
1660
+ retrySafety: 'unsafe',
1661
+ detail: note,
1662
+ }
1663
+ if (judged.delivery === 'delivered_verified')
1664
+ return { ...judged, detail: foregroundNote(outcome) }
1665
+ return { ...judged, detail: `${judged.detail ?? ''} ${instead}`.trim() }
1666
+ }
1667
+
1668
+ /**
1669
+ * Select a list or tree row that can also be invoked, through its selection
1670
+ * pattern, so that a file row is chosen and not opened. Where that cannot be
1671
+ * reached nothing is sent: the click that is left would open the item.
1672
+ */
1673
+ private async selectWithoutOpening(facts: UiRefEntry): Promise<UiActResult> {
1674
+ const result = await this.foreground?.selectItem({
1675
+ hwnd: windowIdOf(facts.hwnd),
1676
+ role: facts.role,
1677
+ name: facts.name,
1678
+ ...(facts.automationId ? { automationId: facts.automationId } : {}),
1679
+ ...(facts.bounds ? { bounds: facts.bounds } : {}),
1680
+ })
1681
+ if (!result?.found) {
1682
+ const why = result
1683
+ ? (SELECT_REFUSALS[result.reason] ?? 'the row could not be selected')
1684
+ : 'this host cannot select a row without opening it'
1685
+ return {
1686
+ ok: false,
1687
+ delivery: 'not_delivered',
1688
+ retrySafety: 'safe',
1689
+ detail: `${why}, and nothing was sent. Clicking the row would open it; use invoke to open it, or take a new ui_snapshot and try again.`,
1690
+ }
1691
+ }
1692
+ const back = await this.readBack(facts)
1693
+ if (back?.selected === true || (back === undefined && result.selected))
1694
+ return {
1695
+ ok: true,
1696
+ delivery: 'delivered_verified',
1697
+ retrySafety: 'unsafe',
1698
+ readBack: { expected: 'selected', observed: 'selected' },
1699
+ detail: 'The row is selected; it was not opened.',
1700
+ }
1701
+ return {
1702
+ ok: true,
1703
+ delivery: 'delivered_unverified',
1704
+ retrySafety: 'unsafe',
1705
+ readBack: { expected: 'selected', observed: 'not selected' },
1706
+ detail: 'the row was selected by its selection pattern, but it does not read as selected.',
1707
+ }
1708
+ }
1709
+
1710
+ /** Replace a classic edit control's text by window message; undefined where the control is not one this reaches. */
1711
+ private async setByMessages(facts: UiRefEntry, text: string): Promise<UiActResult | undefined> {
1712
+ const ladder = this.foreground
1713
+ if (!ladder) return undefined
1714
+ const result = await ladder.editText({
1715
+ hwnd: windowIdOf(facts.hwnd),
1716
+ op: 'set',
1717
+ text,
1718
+ pick: 'bounds',
1719
+ ...(facts.bounds
1720
+ ? {
1721
+ at: {
1722
+ x: facts.bounds.x + facts.bounds.width / 2,
1723
+ y: facts.bounds.y + facts.bounds.height / 2,
1724
+ },
1725
+ }
1726
+ : {}),
1727
+ })
1728
+ if (!result) return undefined
1729
+ if (!result.found) {
1730
+ if (result.reason === 'uipi' || result.reason === 'gone')
1731
+ return { ...judgeEdit('set', text, result), ok: false }
1732
+ return undefined
1733
+ }
1734
+ return judgeEdit('set', text, result)
1735
+ }
1736
+
1737
+ /**
1738
+ * A shortcut with a modifier, carried out as the window's own menu command. Undefined where the window has no
1739
+ * classic menu item for it (the usual case for a modern window), so the key goes the ordinary way.
1740
+ */
1741
+ private async shortcutByMenu(
1742
+ frame: WindowCaptureFrame,
1743
+ keys: string,
1744
+ ): Promise<WindowInputResult | undefined> {
1745
+ const ladder = this.foreground
1746
+ if (!ladder) return undefined
1747
+ const accelerator = menuAcceleratorOf(keys)
1748
+ if (accelerator === undefined) return undefined
1749
+ const result = await ladder.menuCommand({ hwnd: frame.window.id, accelerator })
1750
+ if (!result?.found) return undefined
1751
+ this.showPresence(frame, frame.window.bounds, 'hotkey', {})
1752
+ return {
1753
+ delivery: 'delivered_unverified',
1754
+ retrySafety: 'unsafe',
1755
+ detail: `Carried out as the window's menu command "${result.label ?? accelerator}" (no key pressed, the screen not used).`,
1756
+ }
1757
+ }
1758
+
1759
+ /** Type into the window's focused classic edit control by window message; undefined where there is none. */
1760
+ private async typeByMessages(
1761
+ frame: WindowCaptureFrame,
1762
+ text: string,
1763
+ ): Promise<WindowInputResult | undefined> {
1764
+ const ladder = this.foreground
1765
+ if (!ladder) return undefined
1766
+ const result = await ladder.editText({
1767
+ hwnd: frame.window.id,
1768
+ op: 'type',
1769
+ text,
1770
+ pick: 'focus',
1771
+ })
1772
+ if (!result) return undefined
1773
+ if (!result.found) {
1774
+ if (result.reason !== 'uipi') return undefined
1775
+ return judgeEdit('type', text, result)
1776
+ }
1777
+ this.showPresence(frame, frame.window.bounds, 'type_text', {})
1778
+ const { ok: _ok, ...verdict } = judgeEdit('type', text, result)
1779
+ return verdict
1780
+ }
1781
+
1782
+ /**
1783
+ * A click on a control that the control's own state does not answer for
1784
+ * (a button): when the driver cannot confirm it, the window is read before
1785
+ * and after, and the click is verified by what it changed.
1786
+ */
1787
+ private async clickAndWatch(
1788
+ facts: UiRefEntry,
1789
+ uiRef: { readonly ref: string; readonly facts: UiRefEntry },
1790
+ ): Promise<UiActResult> {
1791
+ const target = { hwnd: facts.hwnd, pid: facts.pid }
1792
+ const earlier = await this.observe(target)
1793
+ const before = await this.observe(target)
1794
+ const windows = await this.windowIdsOf(target.pid)
1795
+ // Each read of the window replaces the driver's handles: click through the refreshed one.
1796
+ const current = this.uiRefs.get(uiRef.ref) ?? facts
1797
+ const sent = await this.clickRef(current, {
1798
+ ref: uiRef.ref,
1799
+ facts: current,
1800
+ })
1801
+ if (!sent.ok || sent.delivery !== 'delivered_unverified' || !before) return sent
1802
+ const seen = await this.verifyByReading(target, {
1803
+ typed: undefined,
1804
+ before,
1805
+ earlier,
1806
+ windows,
1807
+ })
1808
+ if (!seen) return sent
1809
+ return {
1810
+ ok: true,
1811
+ delivery: seen.delivery,
1812
+ retrySafety: seen.retrySafety,
1813
+ detail: seen.detail,
1814
+ ...(seen.observed !== undefined ? { readBack: { observed: seen.observed } } : {}),
1815
+ }
1816
+ }
1817
+
1818
+ /**
1819
+ * A click on a control by its driver token, in the background. Where the
1820
+ * driver says the window cannot take background input (or is covered) the
1821
+ * same click is retried in the foreground through the ladder.
1822
+ */
1823
+ private async clickRef(
1824
+ facts: UiRefEntry,
1825
+ uiRef: { readonly ref: string; readonly facts: UiRefEntry },
1826
+ ): Promise<UiActResult> {
1827
+ const { pid, token } = facts
1828
+ try {
1829
+ return actResult(
1830
+ await this.callTool('click', { pid, element_token: token }, undefined, uiRef),
1831
+ )
1832
+ } catch (error) {
1833
+ const ladder = this.foreground
1834
+ if (!(error instanceof McpToolError) || !ladder || !foregroundCures(error)) throw error
1835
+ const subject = {
1836
+ app: this.windowApps.get(windowIdOf(facts.hwnd)) ?? `process ${pid}`,
1837
+ pid,
1838
+ hwnd: windowIdOf(facts.hwnd),
1839
+ }
1840
+ const outcome = await ladder
1841
+ .run(this.burstRequest(subject, true), async (burst) => {
1842
+ await burst.checkpoint()
1843
+ try {
1844
+ return actResult(
1845
+ await this.callTool(
1846
+ 'click',
1847
+ { pid, element_token: token, delivery_mode: 'foreground' },
1848
+ undefined,
1849
+ uiRef,
1850
+ ),
1851
+ )
1852
+ } catch (inner) {
1853
+ if (inner instanceof McpToolError) return failureResult(inner)
1854
+ throw inner
1855
+ }
1856
+ })
1857
+ .catch((inner: unknown) => {
1858
+ if (inner instanceof BurstInterrupted) return inner
1859
+ throw inner
1860
+ })
1861
+ if (outcome instanceof BurstInterrupted)
1862
+ return {
1863
+ ok: false,
1864
+ delivery: 'not_delivered',
1865
+ retrySafety: 'safe',
1866
+ detail:
1867
+ outcome.reason === 'person'
1868
+ ? 'a person used the keyboard or mouse just before the click was sent, so nothing was sent. Try again in a moment.'
1869
+ : 'an administrator window came to the front just before the click was sent, so nothing was sent. Namzu cannot type into it; try again once it is gone.',
1870
+ }
1871
+ if (outcome.kind === 'blocked')
1872
+ return {
1873
+ ok: false,
1874
+ delivery: 'not_delivered',
1875
+ retrySafety: 'safe',
1876
+ detail: outcome.block.detail,
1877
+ }
1878
+ const dropped = droppedInputNote(outcome)
1879
+ if (dropped)
1880
+ return {
1881
+ ok: false,
1882
+ delivery: 'not_delivered',
1883
+ retrySafety: 'safe',
1884
+ detail: dropped,
1885
+ }
1886
+ const note = interferenceNote(outcome)
1887
+ const base = outcome.value
1888
+ const detail = [base.detail, note ?? foregroundNote(outcome)].filter(Boolean).join(' ')
1889
+ if (note && base.delivery !== 'not_delivered')
1890
+ return {
1891
+ ...base,
1892
+ delivery: 'delivered_unverified',
1893
+ retrySafety: 'unsafe',
1894
+ detail,
1895
+ }
1896
+ return { ...base, detail }
1897
+ }
1898
+ }
1899
+
1900
+ /**
1901
+ * The control as a fresh read of its window shows it, or undefined when
1902
+ * that read failed or the control is gone. A failed read says nothing
1903
+ * about the action, so callers treat undefined as "unverified".
1904
+ */
1905
+ private async readBack(facts: UiRefEntry): Promise<UiRefFacts | undefined> {
1906
+ try {
1907
+ const target = { hwnd: facts.hwnd, pid: facts.pid }
1908
+ const read = await this.readWindowTree(target, {})
1909
+ const found = locate(facts, read.tree, { actionable: true })
1910
+ this.bindRead(target, read, { shown: new Set(), regions: new Set() })
1911
+ return found.kind === 'found' ? found.node.facts : undefined
1912
+ } catch {
1913
+ return undefined
1914
+ }
1915
+ }
1916
+
634
1917
  async dispose(): Promise<void> {
635
1918
  await this.client.dispose()
636
1919
  }
637
1920
 
1921
+ /** Tells the overlay where the agent is about to act in a window; never waits and never fails the action. */
1922
+ private showPresence(
1923
+ frame: WindowCaptureFrame,
1924
+ bounds: WindowInfo['bounds'],
1925
+ tool: string,
1926
+ args: Record<string, unknown>,
1927
+ ): void {
1928
+ const presence = this.presence
1929
+ if (!presence) return
1930
+ const hwnd = parseWindowId(frame.window.id)
1931
+ if (hwnd === undefined) return
1932
+ const scale = frame.width > 0 ? bounds.width / frame.width : 1
1933
+ const screen = (x: unknown, y: unknown): { x: number; y: number } | undefined =>
1934
+ typeof x === 'number' && typeof y === 'number'
1935
+ ? { x: bounds.x + x * scale, y: bounds.y + y * scale }
1936
+ : undefined
1937
+ const at = screen(args.x ?? args.to_x, args.y ?? args.to_y)
1938
+ const typing = tool === 'type_text' || tool === 'press_key' || tool === 'hotkey'
1939
+ this.tryPresence((overlay) =>
1940
+ overlay.mark({
1941
+ hwnd,
1942
+ kind: typing ? 'type' : 'click',
1943
+ ...(at && !typing ? { at } : {}),
1944
+ }),
1945
+ )
1946
+ }
1947
+
1948
+ /** The overlay is decoration: whatever it does, the action goes on. */
1949
+ private tryPresence(use: (presence: Presence) => void): void {
1950
+ if (!this.presence || this.driverCursorOff === false) return
1951
+ try {
1952
+ use(this.presence)
1953
+ } catch {
1954
+ // Nothing is shown; nothing else changes.
1955
+ }
1956
+ }
1957
+
638
1958
  private async serializeWindowOperation<T>(operation: () => Promise<T>): Promise<T> {
639
1959
  const previous = this.windowOperation
640
1960
  let release: () => void = () => undefined
@@ -673,22 +1993,31 @@ export class CuaDriverAdapter implements Adapter {
673
1993
  if (
674
1994
  uiRef &&
675
1995
  (this.uiRefs.get(uiRef.ref) !== uiRef.facts ||
676
- uiRef.facts.generation !== this.sessionGeneration)
1996
+ uiRef.facts.generation !== this.sessionGeneration ||
1997
+ this.windowReads.get(uiRef.facts.hwnd)?.seq !== uiRef.facts.readSeq)
677
1998
  )
678
1999
  throw new McpToolError(name, 'stale UI snapshot; take a new one')
679
2000
  const generation = this.sessionGeneration
2001
+ const signal = currentCallSignal()
2002
+ const changes = changesDesktop(name)
680
2003
  try {
681
- return await this.client.callTool(name, args, timeoutMs, {
2004
+ const result = await this.client.callTool(name, args, timeoutMs, {
2005
+ ...(signal ? { signal } : {}),
682
2006
  ...(uiRef || windowFrame
683
- ? { expectedStarts: uiRef?.facts.processStarts ?? windowFrame?.processStarts }
2007
+ ? {
2008
+ expectedStarts: uiRef?.facts.processStarts ?? windowFrame?.processStarts,
2009
+ }
684
2010
  : {}),
685
2011
  ...(onProcess ? { onProcess } : {}),
686
2012
  })
2013
+ if (changes) markSent()
2014
+ return result
687
2015
  } catch (error) {
2016
+ if (error instanceof CallAbortedError && error.sent && changes) markSent()
688
2017
  if (!isEndedSessionRefusal(error)) throw error
689
2018
  // The refusal proves the old session's element tokens are invalid,
690
2019
  // even if start_session fails and there is no successful revival.
691
- if (this.sessionGeneration === generation) this.uiRefs.clear()
2020
+ if (this.sessionGeneration === generation) this.windowReads.clear()
692
2021
  this.windowFrame = undefined
693
2022
  await this.reviveSession(generation)
694
2023
  // Element tokens belong to the old snapshot. A new lifecycle session
@@ -698,7 +2027,27 @@ export class CuaDriverAdapter implements Adapter {
698
2027
  throw new McpToolError(name, 'stale window screenshot; capture the window again')
699
2028
  // One retry only. A second refusal or an unacknowledged action is
700
2029
  // returned to the host without any further automatic replay.
701
- return this.client.callTool(name, args, timeoutMs, { onProcess })
2030
+ const retried = await this.client.callTool(name, args, timeoutMs, {
2031
+ ...(signal ? { signal } : {}),
2032
+ ...(onProcess ? { onProcess } : {}),
2033
+ })
2034
+ if (changes) markSent()
2035
+ return retried
2036
+ }
2037
+ }
2038
+
2039
+ /**
2040
+ * What a foreground burst asks of the ladder: the call's cancellation, and
2041
+ * the wait for calls a cancelled burst left in flight before the window and
2042
+ * cursor are put back.
2043
+ */
2044
+ private burstRequest(subject: ForegroundSubject, sendsInput: boolean): LadderRequest {
2045
+ const signal = currentCallSignal()
2046
+ return {
2047
+ subject,
2048
+ sendsInput,
2049
+ ...(signal ? { signal } : {}),
2050
+ settle: () => this.client.settled(),
702
2051
  }
703
2052
  }
704
2053
 
@@ -707,8 +2056,10 @@ export class CuaDriverAdapter implements Adapter {
707
2056
  if (!this.sessionRevival) {
708
2057
  this.sessionRevival = (async () => {
709
2058
  await this.client.callTool('start_session')
710
- await disableAgentCursor((name, args) => this.client.callTool(name, args))
711
- this.uiRefs.clear()
2059
+ this.driverCursorOff = await disableAgentCursor((name, args) =>
2060
+ this.client.callTool(name, args),
2061
+ )
2062
+ this.windowReads.clear()
712
2063
  this.windowFrame = undefined
713
2064
  this.sessionGeneration++
714
2065
  })().finally(() => {
@@ -741,15 +2092,24 @@ export class CuaDriverAdapter implements Adapter {
741
2092
  return { hwnd, pid }
742
2093
  }
743
2094
 
744
- private async pointer(tool: string, args: Record<string, unknown>): Promise<void> {
2095
+ /**
2096
+ * A display pointer action. A click that ends with another window in front
2097
+ * is reported as sent but unverified: it may have closed its own window,
2098
+ * or it may have missed. Neither is "done".
2099
+ */
2100
+ private async pointer(tool: string, args: Record<string, unknown>): Promise<ComputerUseResult> {
745
2101
  try {
746
- await this.callTool(tool, args)
2102
+ return okResult(inputDelivery(await this.callTool(tool, args)))
747
2103
  } catch (error) {
748
- if (isDeliveredPointerAction(error)) return
2104
+ if (isDeliveredPointerAction(error)) return okResult(foregroundLostDelivery())
749
2105
  throw error
750
2106
  }
751
2107
  }
752
2108
 
2109
+ private async keyboard(tool: string, args: Record<string, unknown>): Promise<ComputerUseResult> {
2110
+ return okResult(inputDelivery(await this.callTool(tool, args)))
2111
+ }
2112
+
753
2113
  private async capture(): Promise<ScreenshotResult> {
754
2114
  const result = await this.callTool('get_desktop_state', {}, CAPTURE_TIMEOUT_MS)
755
2115
  const image = result.content.find(
@@ -814,52 +2174,271 @@ export function isDeliveredPointerAction(error: unknown): boolean {
814
2174
  )
815
2175
  }
816
2176
 
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
2177
+ const trimText = (value: string, max = 80): string =>
2178
+ value.length > max ? `${value.slice(0, max - 1)}…` : value
2179
+
2180
+ /** A delivery verdict with the retry advice that goes with it. */
2181
+ function verdict(
2182
+ delivery: ActionDelivery,
2183
+ retrySafety: ActionRetrySafety,
2184
+ detail?: string,
2185
+ ): WindowInputResult {
2186
+ return { delivery, retrySafety, ...(detail !== undefined ? { detail } : {}) }
2187
+ }
2188
+
2189
+ /** `ok` with a delivery verdict: a call that returned is never proof that the effect happened. */
2190
+ function okResult(input: WindowInputResult): ComputerUseResult {
2191
+ return { type: 'ok', ...input }
2192
+ }
2193
+
2194
+ /** The click was sent, but the window it targeted is no longer in front afterwards. */
2195
+ function foregroundLostDelivery(): WindowInputResult {
2196
+ return verdict(
2197
+ 'delivered_unverified',
2198
+ 'unsafe',
2199
+ 'the click was sent, but another window was in front afterwards. It may have closed its own window or started another program, or it may have missed. Look at the screen before clicking again.',
2200
+ )
2201
+ }
2202
+
2203
+ /**
2204
+ * What a driver tool call that returned says about the input it sent.
2205
+ *
2206
+ * The driver reports `effect: "unverifiable"` for nearly every background
2207
+ * action, including ones that did nothing, and its `delivery_failed`
2208
+ * escalation shows up on input that arrived as well as input that did not.
2209
+ * Neither is proof, so only a `confirmed` effect is verified, and anything
2210
+ * else says "sent, not confirmed".
2211
+ */
2212
+ export function inputDelivery(result: McpToolResult): WindowInputResult {
2213
+ const facts = result.structuredContent ?? {}
2214
+ switch (facts.effect) {
2215
+ case 'refused': {
2216
+ const refusal = facts.refusal as { message?: unknown } | undefined
2217
+ return verdict(
2218
+ 'not_delivered',
2219
+ 'safe',
2220
+ typeof refusal?.message === 'string' ? refusal.message : 'cua-driver refused the action',
2221
+ )
2222
+ }
2223
+ case 'confirmed':
2224
+ return verdict('delivered_verified', 'unsafe')
2225
+ case 'suspected_noop':
2226
+ return verdict(
2227
+ 'delivered_unverified',
2228
+ 'unsafe',
2229
+ 'the driver suspects the input changed nothing; it may not have reached the target. Look at the window before repeating it.',
2230
+ )
2231
+ default: {
2232
+ const escalation = facts.escalation as { reason?: unknown } | undefined
2233
+ return verdict(
2234
+ 'delivered_unverified',
2235
+ 'unsafe',
2236
+ escalation?.reason === 'delivery_failed'
2237
+ ? 'the driver could not confirm that the input arrived. It may have; check the window before repeating it, and if nothing changed send it again with delivery_mode:"foreground".'
2238
+ : undefined,
2239
+ )
2240
+ }
2241
+ }
2242
+ }
2243
+
2244
+ /**
2245
+ * A driver tool error → what it means for delivery. A refusal the driver
2246
+ * names means it did not send the input (safe to repeat once the cause is
2247
+ * fixed). Any other error leaves the outcome unknown: it is reported as
2248
+ * unverified and unsafe to repeat.
2249
+ */
2250
+ export function failureDelivery(error: McpToolError): WindowInputResult {
2251
+ const facts = error.structuredContent ?? {}
2252
+ const code = typeof facts.code === 'string' ? facts.code : undefined
820
2253
  if (
821
2254
  code === 'background_unavailable' ||
822
2255
  code === 'background_occluded' ||
823
2256
  code === 'background_uipi_blocked'
824
2257
  )
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.',
2258
+ return verdict(
2259
+ 'not_delivered',
2260
+ 'safe',
2261
+ code === 'background_uipi_blocked'
2262
+ ? 'this window belongs to a program running with higher rights, so background input is blocked. Ask the user; do not try to get around it.'
2263
+ : code === 'background_occluded'
2264
+ ? 'the target is covered by another window, so background input cannot reach it. Nothing was sent.'
2265
+ : 'this window cannot take background input here (it needs real focus). Nothing was sent. Use a control by ref (ui_act) if the window offers one, or send it again with delivery_mode:"foreground".',
2266
+ )
2267
+ if (facts.status === 'refused') {
2268
+ const refusal = facts.refusal as { message?: unknown } | undefined
2269
+ return verdict(
2270
+ 'not_delivered',
2271
+ 'safe',
2272
+ typeof refusal?.message === 'string' ? refusal.message : error.message,
827
2273
  )
828
- return error
2274
+ }
2275
+ if (/stale (window|screenshot)/i.test(error.message))
2276
+ return verdict('not_delivered', 'safe', trimText(error.message, 300))
2277
+ if (/stale/i.test(`${error.message} ${JSON.stringify(facts)}`))
2278
+ return verdict(
2279
+ 'not_delivered',
2280
+ 'safe',
2281
+ 'that control is from an older UI snapshot; take a new one',
2282
+ )
2283
+ // An error the driver does not classify can arrive after input was sent (a
2284
+ // foreground burst calls this too), so it never invites a blind resend.
2285
+ return verdict(
2286
+ 'delivered_unverified',
2287
+ 'unsafe',
2288
+ `${trimText(error.message, 300)} The input may have been sent; look at the window before repeating it.`,
2289
+ )
2290
+ }
2291
+
2292
+ /** The driver refused a handle a newer read of its window replaced (nothing was sent). */
2293
+ function isStaleHandle(error: McpToolError): boolean {
2294
+ if (/stale (window|screenshot)/i.test(error.message)) return false
2295
+ return /stale_element_token|stale (UI|element)/i.test(
2296
+ `${error.message} ${JSON.stringify(error.structuredContent ?? {})}`,
2297
+ )
2298
+ }
2299
+
2300
+ /** Refusals that a foreground delivery can cure. `uipi_blocked` is not one: it blocks foreground input too. */
2301
+ function foregroundCures(error: McpToolError): boolean {
2302
+ const code = error.structuredContent?.code
2303
+ return code === 'background_unavailable' || code === 'background_occluded'
2304
+ }
2305
+
2306
+ function failureResult(error: McpToolError): UiActResult {
2307
+ const { delivery, retrySafety, detail } = failureDelivery(error)
2308
+ return {
2309
+ ok: false,
2310
+ delivery,
2311
+ retrySafety,
2312
+ ...(detail !== undefined ? { detail } : {}),
2313
+ }
829
2314
  }
830
2315
 
831
2316
  /**
832
- * cua-driver's action result → the host's. `confirmed`, `partial` and
833
- * `unverifiable` count as done: a background UIA Invoke is `unverifiable` by
834
- * design (the control does not report back), and the screenshot the tool
835
- * takes afterwards is where the model sees the effect.
2317
+ * cua-driver's action result → the host's. `unverifiable` is the driver's
2318
+ * answer to almost everything it does in the background, so a result that
2319
+ * returned is "sent", and the stateful actions are judged by reading the
2320
+ * control back.
836
2321
  */
837
2322
  export function actResult(result: McpToolResult): UiActResult {
838
- const facts = result.structuredContent ?? {}
839
- switch (facts.effect) {
840
- case 'suspected_noop':
841
- return {
842
- ok: false,
843
- detail: 'the control did not change; the action may not have reached it',
844
- }
845
- case 'refused': {
846
- const refusal = facts.refusal as { message?: unknown } | undefined
847
- return {
848
- ok: false,
849
- detail:
850
- typeof refusal?.message === 'string' ? refusal.message : 'cua-driver refused the action',
851
- }
2323
+ const sent = inputDelivery(result)
2324
+ return {
2325
+ ok: sent.delivery !== 'not_delivered' && result.structuredContent?.effect !== 'suspected_noop',
2326
+ delivery: sent.delivery,
2327
+ retrySafety: sent.retrySafety,
2328
+ ...(sent.detail !== undefined ? { detail: sent.detail } : {}),
2329
+ }
2330
+ }
2331
+
2332
+ const same = (a: string, b: string): boolean => a.trim() === b.trim()
2333
+
2334
+ /** set_value, judged by the field as a fresh read shows it. */
2335
+ export function judgeSetValue(
2336
+ before: UiRefFacts,
2337
+ expected: string,
2338
+ after: UiRefFacts | undefined,
2339
+ ): UiActResult {
2340
+ if (!after)
2341
+ return {
2342
+ ok: true,
2343
+ delivery: 'delivered_unverified',
2344
+ retrySafety: 'unsafe',
2345
+ detail:
2346
+ 'the value was sent, but the field could not be read back (the window may have changed). Check it before setting it again.',
2347
+ }
2348
+ if (after.value === undefined)
2349
+ return {
2350
+ ok: true,
2351
+ delivery: 'delivered_unverified',
2352
+ retrySafety: 'unsafe',
2353
+ detail:
2354
+ 'the value was sent; this control does not report its value, so it could not be checked. Look at the window.',
852
2355
  }
853
- default:
854
- return { ok: true }
2356
+ if (same(after.value, expected))
2357
+ return {
2358
+ ok: true,
2359
+ delivery: 'delivered_verified',
2360
+ retrySafety: 'safe',
2361
+ readBack: {
2362
+ expected: trimText(expected),
2363
+ observed: trimText(after.value),
2364
+ },
2365
+ }
2366
+ if (before.value !== undefined && same(before.value, after.value))
2367
+ return {
2368
+ ok: false,
2369
+ delivery: 'not_delivered',
2370
+ retrySafety: 'safe',
2371
+ readBack: {
2372
+ expected: trimText(expected),
2373
+ observed: trimText(after.value),
2374
+ },
2375
+ detail: `the driver reported success, but the control still holds ${JSON.stringify(trimText(after.value))}, not the value sent. Nothing changed. This control may need real focus: choose the option with the keyboard or the pointer in the foreground, or use the browser tool for a web page.`,
2376
+ }
2377
+ return {
2378
+ ok: true,
2379
+ delivery: 'delivered_unverified',
2380
+ retrySafety: 'unsafe',
2381
+ readBack: { expected: trimText(expected), observed: trimText(after.value) },
2382
+ detail: `the control changed, but it now holds ${JSON.stringify(trimText(after.value))} instead of the value sent; it may have reformatted it. Check before setting it again.`,
855
2383
  }
856
2384
  }
857
2385
 
858
- /** Why a tool call failed, in words that tell the model what to do next. */
859
- function toolRefusal(error: McpToolError): string {
860
- if (/stale/i.test(error.message))
861
- return 'that control is from an older UI snapshot; take a new one'
862
- return error.message.length > 300 ? `${error.message.slice(0, 299)}…` : error.message
2386
+ /** toggle, judged by whether the control's selected state flipped. */
2387
+ export function judgeToggle(before: UiRefFacts, after: UiRefFacts | undefined): UiActResult {
2388
+ if (!after)
2389
+ return {
2390
+ ok: true,
2391
+ delivery: 'delivered_unverified',
2392
+ retrySafety: 'unsafe',
2393
+ detail:
2394
+ 'the toggle was sent, but the control could not be read back. A second toggle would undo it; check first.',
2395
+ }
2396
+ if (after.selected !== before.selected)
2397
+ return {
2398
+ ok: true,
2399
+ delivery: 'delivered_verified',
2400
+ retrySafety: 'unsafe',
2401
+ readBack: {
2402
+ expected: String(!before.selected),
2403
+ observed: String(after.selected),
2404
+ },
2405
+ }
2406
+ return {
2407
+ ok: true,
2408
+ delivery: 'delivered_unverified',
2409
+ retrySafety: 'unsafe',
2410
+ readBack: { observed: String(after.selected) },
2411
+ detail:
2412
+ 'the toggle was sent, but the control still reads the same. It may not report its state, or it may not have changed. A second toggle could undo it; check the window first.',
2413
+ }
2414
+ }
2415
+
2416
+ const ITEM_ROLES = /^(ListItem|TreeItem|DataItem)$/
2417
+
2418
+ const SELECT_REFUSALS: Readonly<Record<string, string>> = {
2419
+ gone: 'the window is gone',
2420
+ not_found: 'the row is not in the window any more',
2421
+ ambiguous: 'more than one row matches',
2422
+ no_pattern: 'the row has no selection pattern',
2423
+ refused: 'the program refused the selection',
2424
+ }
2425
+
2426
+ /** select by a click, judged by whether the control now reads as selected (a row that can also be invoked takes the selection pattern instead). */
2427
+ export function judgeSelect(_before: UiRefFacts, after: UiRefFacts | undefined): UiActResult {
2428
+ if (after?.selected === true)
2429
+ return {
2430
+ ok: true,
2431
+ delivery: 'delivered_verified',
2432
+ retrySafety: 'unsafe',
2433
+ readBack: { expected: 'selected', observed: 'selected' },
2434
+ }
2435
+ return {
2436
+ ok: true,
2437
+ delivery: 'delivered_unverified',
2438
+ retrySafety: 'unsafe',
2439
+ ...(after ? { readBack: { expected: 'selected', observed: 'not selected' } } : {}),
2440
+ detail: `the click was sent, but the control does not read as selected${after ? '' : ' (it could not be read back)'}.`,
2441
+ }
863
2442
  }
864
2443
 
865
2444
  /** `0x…` hex, the form `bring_to_front` reports and `WindowInfo.id` carries. */