@namzu/computer-use 3.1.0 → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +58 -1
- package/dist/SubprocessComputerUseHost.d.ts +57 -9
- package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
- package/dist/SubprocessComputerUseHost.js +213 -46
- package/dist/SubprocessComputerUseHost.js.map +1 -1
- package/dist/adapters/cua-driver/adapter.d.ts +171 -10
- package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
- package/dist/adapters/cua-driver/adapter.js +1476 -161
- package/dist/adapters/cua-driver/adapter.js.map +1 -1
- package/dist/adapters/cua-driver/client.d.ts +16 -0
- package/dist/adapters/cua-driver/client.d.ts.map +1 -1
- package/dist/adapters/cua-driver/client.js +54 -5
- package/dist/adapters/cua-driver/client.js.map +1 -1
- package/dist/adapters/cua-driver/escalation.d.ts +67 -0
- package/dist/adapters/cua-driver/escalation.d.ts.map +1 -0
- package/dist/adapters/cua-driver/escalation.js +82 -0
- package/dist/adapters/cua-driver/escalation.js.map +1 -0
- package/dist/adapters/cua-driver/keys.d.ts +5 -0
- package/dist/adapters/cua-driver/keys.d.ts.map +1 -1
- package/dist/adapters/cua-driver/keys.js +23 -0
- package/dist/adapters/cua-driver/keys.js.map +1 -1
- package/dist/adapters/cua-driver/observe.d.ts +99 -0
- package/dist/adapters/cua-driver/observe.d.ts.map +1 -0
- package/dist/adapters/cua-driver/observe.js +227 -0
- package/dist/adapters/cua-driver/observe.js.map +1 -0
- package/dist/adapters/cua-driver/ui-tree.d.ts +75 -2
- package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
- package/dist/adapters/cua-driver/ui-tree.js +142 -14
- package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
- package/dist/adapters/types.d.ts +3 -3
- package/dist/adapters/types.d.ts.map +1 -1
- package/dist/adapters/types.js.map +1 -1
- package/dist/adapters/win32.d.ts +10 -0
- package/dist/adapters/win32.d.ts.map +1 -1
- package/dist/adapters/win32.js +12 -2
- package/dist/adapters/win32.js.map +1 -1
- package/dist/errors.d.ts +19 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +26 -0
- package/dist/errors.js.map +1 -1
- package/dist/foreground/guard.d.ts +31 -0
- package/dist/foreground/guard.d.ts.map +1 -0
- package/dist/foreground/guard.js +156 -0
- package/dist/foreground/guard.js.map +1 -0
- package/dist/foreground/index.d.ts +11 -0
- package/dist/foreground/index.d.ts.map +1 -0
- package/dist/foreground/index.js +7 -0
- package/dist/foreground/index.js.map +1 -0
- package/dist/foreground/ladder.d.ts +143 -0
- package/dist/foreground/ladder.d.ts.map +1 -0
- package/dist/foreground/ladder.js +505 -0
- package/dist/foreground/ladder.js.map +1 -0
- package/dist/foreground/lease.d.ts +69 -0
- package/dist/foreground/lease.d.ts.map +1 -0
- package/dist/foreground/lease.js +182 -0
- package/dist/foreground/lease.js.map +1 -0
- package/dist/foreground/types.d.ts +287 -0
- package/dist/foreground/types.d.ts.map +1 -0
- package/dist/foreground/types.js +32 -0
- package/dist/foreground/types.js.map +1 -0
- package/dist/foreground/windows-helper-script.d.ts +19 -0
- package/dist/foreground/windows-helper-script.d.ts.map +1 -0
- package/dist/foreground/windows-helper-script.js +472 -0
- package/dist/foreground/windows-helper-script.js.map +1 -0
- package/dist/foreground/windows-monitor.d.ts +75 -0
- package/dist/foreground/windows-monitor.d.ts.map +1 -0
- package/dist/foreground/windows-monitor.js +216 -0
- package/dist/foreground/windows-monitor.js.map +1 -0
- package/dist/foreground/windows.d.ts +21 -0
- package/dist/foreground/windows.d.ts.map +1 -0
- package/dist/foreground/windows.js +54 -0
- package/dist/foreground/windows.js.map +1 -0
- package/dist/index.d.ts +6 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -1
- package/dist/index.js.map +1 -1
- package/dist/presence/helper-script.d.ts +39 -0
- package/dist/presence/helper-script.d.ts.map +1 -0
- package/dist/presence/helper-script.js +320 -0
- package/dist/presence/helper-script.js.map +1 -0
- package/dist/presence/index.d.ts +6 -0
- package/dist/presence/index.d.ts.map +1 -0
- package/dist/presence/index.js +4 -0
- package/dist/presence/index.js.map +1 -0
- package/dist/presence/presence.d.ts +70 -0
- package/dist/presence/presence.d.ts.map +1 -0
- package/dist/presence/presence.js +147 -0
- package/dist/presence/presence.js.map +1 -0
- package/dist/presence/windows.d.ts +19 -0
- package/dist/presence/windows.d.ts.map +1 -0
- package/dist/presence/windows.js +39 -0
- package/dist/presence/windows.js.map +1 -0
- package/dist/util/call-scope.d.ts +34 -0
- package/dist/util/call-scope.d.ts.map +1 -0
- package/dist/util/call-scope.js +58 -0
- package/dist/util/call-scope.js.map +1 -0
- package/package.json +2 -2
- package/src/SubprocessComputerUseHost.ts +287 -45
- package/src/adapters/cua-driver/adapter.ts +1751 -175
- package/src/adapters/cua-driver/client.ts +59 -2
- package/src/adapters/cua-driver/escalation.ts +137 -0
- package/src/adapters/cua-driver/keys.ts +20 -0
- package/src/adapters/cua-driver/observe.ts +310 -0
- package/src/adapters/cua-driver/ui-tree.ts +219 -15
- package/src/adapters/types.ts +7 -2
- package/src/adapters/win32.ts +26 -3
- package/src/errors.ts +32 -0
- package/src/foreground/guard.ts +182 -0
- package/src/foreground/index.ts +45 -0
- package/src/foreground/ladder.ts +616 -0
- package/src/foreground/lease.ts +232 -0
- package/src/foreground/types.ts +318 -0
- package/src/foreground/windows-helper-script.ts +471 -0
- package/src/foreground/windows-monitor.ts +288 -0
- package/src/foreground/windows.ts +73 -0
- package/src/index.ts +15 -1
- package/src/presence/helper-script.ts +323 -0
- package/src/presence/index.ts +17 -0
- package/src/presence/presence.ts +195 -0
- package/src/presence/windows.ts +54 -0
- 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 {
|
|
28
|
-
|
|
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
|
|
74
|
-
const UI_MAX_ELEMENTS =
|
|
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
|
-
|
|
81
|
-
|
|
82
|
-
|
|
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
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
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
|
-
/**
|
|
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
|
|
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:
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
520
|
+
return last
|
|
245
521
|
}
|
|
246
522
|
case 'type_text':
|
|
247
|
-
if (action.text.length
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
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
|
-
|
|
530
|
+
if (plan.tool === 'type_text')
|
|
531
|
+
return this.keyboard('type_text', {
|
|
258
532
|
scope: 'desktop',
|
|
259
533
|
text: plan.text,
|
|
260
534
|
})
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
} else {
|
|
264
|
-
await this.callTool('hotkey', {
|
|
535
|
+
if (plan.tool === 'press_key')
|
|
536
|
+
return this.keyboard('press_key', {
|
|
265
537
|
scope: 'desktop',
|
|
266
|
-
|
|
538
|
+
key: plan.key,
|
|
267
539
|
})
|
|
268
|
-
|
|
269
|
-
|
|
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
|
-
|
|
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(
|
|
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
|
-
|
|
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
|
-
|
|
982
|
+
this.showPresence(frame, current.bounds, name, args)
|
|
983
|
+
return this.callTool(name, { ...target, ...args }, undefined, undefined, undefined, frame)
|
|
456
984
|
}
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
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
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
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
|
-
|
|
477
|
-
throw
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
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
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
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(
|
|
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
|
|
1246
|
+
let generation = this.sessionGeneration
|
|
510
1247
|
const state = structured(
|
|
511
1248
|
await this.callTool(
|
|
512
1249
|
'get_window_state',
|
|
@@ -515,72 +1252,260 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
515
1252
|
window_id: target.hwnd,
|
|
516
1253
|
include_screenshot: false,
|
|
517
1254
|
max_elements: UI_MAX_ELEMENTS,
|
|
1255
|
+
...(options.query ? { query: options.query } : {}),
|
|
518
1256
|
},
|
|
519
1257
|
UI_TREE_TIMEOUT_MS,
|
|
520
1258
|
undefined,
|
|
521
1259
|
(starts) => {
|
|
522
1260
|
processStarts = starts
|
|
523
|
-
|
|
1261
|
+
generation = this.sessionGeneration
|
|
524
1262
|
},
|
|
525
1263
|
),
|
|
526
1264
|
'get_window_state',
|
|
527
1265
|
)
|
|
528
|
-
if (
|
|
1266
|
+
if (generation !== this.sessionGeneration || processStarts === 0)
|
|
529
1267
|
throw new McpToolError('get_window_state', 'stale UI snapshot; take a new one')
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
1268
|
+
if (typeof state.pid === 'number' && state.pid !== target.pid)
|
|
1269
|
+
throw new McpToolError('get_window_state', 'window changed owner; take a new UI snapshot')
|
|
1270
|
+
return { state, tree: toUiTree(state), processStarts, generation }
|
|
1271
|
+
}
|
|
1272
|
+
|
|
1273
|
+
/**
|
|
1274
|
+
* Record a read of a window: every ref the model already holds for it is
|
|
1275
|
+
* pointed at the control it named in this read (found by its evidence),
|
|
1276
|
+
* and the controls the model is being shown, and the regions it can open,
|
|
1277
|
+
* get refs. A ref whose control is not found keeps its old, now dead,
|
|
1278
|
+
* read, so using it re-resolves and reports why. Returns ref by path.
|
|
1279
|
+
*/
|
|
1280
|
+
private bindRead(
|
|
1281
|
+
target: { hwnd: number; pid: number },
|
|
1282
|
+
read: { tree: ParsedUiTree; processStarts: number; generation: number },
|
|
1283
|
+
scope: {
|
|
1284
|
+
shown: ReadonlySet<string>
|
|
1285
|
+
regions: ReadonlySet<string>
|
|
1286
|
+
/** A filtered (query) read: its places are not the window's, so it records no places. */
|
|
1287
|
+
partial?: boolean
|
|
1288
|
+
},
|
|
1289
|
+
): Map<string, string> {
|
|
1290
|
+
const seq = ++this.nextRead
|
|
1291
|
+
const at = this.now()
|
|
1292
|
+
this.windowReads.set(target.hwnd, { seq, at })
|
|
1293
|
+
const byPath = new Map<string, string>()
|
|
1294
|
+
const claimed = new Set<string>()
|
|
1295
|
+
const named = new Map<string, number>()
|
|
1296
|
+
for (const node of read.tree.nodes) {
|
|
1297
|
+
const key = `${node.role}\u0000${node.name.trim()}`
|
|
1298
|
+
named.set(key, (named.get(key) ?? 0) + 1)
|
|
1299
|
+
}
|
|
1300
|
+
const bound = (node: UiNode, entry: UiRefEntry, ref: string): void => {
|
|
1301
|
+
const key = pathKey(node.path)
|
|
1302
|
+
claimed.add(key)
|
|
1303
|
+
byPath.set(key, ref)
|
|
1304
|
+
const twin =
|
|
1305
|
+
node.automationId === undefined &&
|
|
1306
|
+
node.name.trim() !== '' &&
|
|
1307
|
+
(named.get(`${node.role}\u0000${node.name.trim()}`) ?? 0) > 1
|
|
1308
|
+
this.uiRefs.set(ref, {
|
|
1309
|
+
...(node.facts ?? factsOfNode(node)),
|
|
1310
|
+
twin,
|
|
1311
|
+
...(scope.partial
|
|
1312
|
+
? {}
|
|
1313
|
+
: {
|
|
1314
|
+
childCount: node.element.children?.length ?? 0,
|
|
1315
|
+
treeSig: read.tree.signature,
|
|
1316
|
+
}),
|
|
1317
|
+
token: node.token,
|
|
539
1318
|
pid: target.pid,
|
|
540
|
-
|
|
541
|
-
|
|
1319
|
+
hwnd: target.hwnd,
|
|
1320
|
+
region: entry.region,
|
|
1321
|
+
...(node.element.bounds ? { bounds: node.element.bounds } : {}),
|
|
1322
|
+
generation: read.generation,
|
|
1323
|
+
processStarts: read.processStarts,
|
|
1324
|
+
readSeq: seq,
|
|
1325
|
+
readAt: at,
|
|
542
1326
|
})
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
1327
|
+
}
|
|
1328
|
+
// A filtered read has other places than the window; it only adds refs.
|
|
1329
|
+
// A handle another program reuses is not the window the ref came from.
|
|
1330
|
+
if (!scope.partial) {
|
|
1331
|
+
for (const [ref, entry] of [...this.uiRefs]) {
|
|
1332
|
+
if (entry.hwnd !== target.hwnd || entry.pid !== target.pid) continue
|
|
1333
|
+
const found = locate(entry, read.tree, { actionable: !entry.region })
|
|
1334
|
+
if (found.kind !== 'found' || claimed.has(pathKey(found.node.path))) continue
|
|
1335
|
+
bound(found.node, entry, ref)
|
|
1336
|
+
}
|
|
1337
|
+
}
|
|
1338
|
+
let created = 0
|
|
1339
|
+
for (const node of read.tree.nodes) {
|
|
1340
|
+
const key = pathKey(node.path)
|
|
1341
|
+
if (claimed.has(key)) continue
|
|
1342
|
+
const region = scope.regions.has(key)
|
|
1343
|
+
const actionable = node.token !== '' && scope.shown.has(key)
|
|
1344
|
+
if (!region && !actionable) continue
|
|
1345
|
+
// A match set larger than the ref budget would evict its own refs.
|
|
1346
|
+
if (created >= NEW_REFS_PER_READ) break
|
|
1347
|
+
created++
|
|
1348
|
+
const ref = `cua-ui:${this.uiRefNamespace}:${++this.nextRef}`
|
|
1349
|
+
const entry = { region: !actionable } as UiRefEntry
|
|
1350
|
+
bound(node, entry, ref)
|
|
1351
|
+
}
|
|
1352
|
+
this.trimRefs(seq)
|
|
1353
|
+
return byPath
|
|
1354
|
+
}
|
|
1355
|
+
|
|
1356
|
+
/** The model holds only so many refs; the oldest reads go first. */
|
|
1357
|
+
private trimRefs(keepSeq: number): void {
|
|
1358
|
+
if (this.uiRefs.size <= MAX_REFS) return
|
|
1359
|
+
// The read that just answered keeps every ref it handed out.
|
|
1360
|
+
const oldest = [...this.uiRefs]
|
|
1361
|
+
.filter(([, entry]) => entry.readSeq !== keepSeq)
|
|
1362
|
+
.sort((a, b) => a[1].readSeq - b[1].readSeq)
|
|
1363
|
+
for (const [ref] of oldest.slice(0, this.uiRefs.size - MAX_REFS)) this.uiRefs.delete(ref)
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
/**
|
|
1367
|
+
* The ref's control as it is now: the entry itself when it was read
|
|
1368
|
+
* recently in the window's latest read, else found again in a fresh read
|
|
1369
|
+
* by its evidence (id, then place, then role and name). Never a guess:
|
|
1370
|
+
* several fits is AMBIGUOUS_TARGET, none is STALE_REF, and nothing has been
|
|
1371
|
+
* sent in either case.
|
|
1372
|
+
*/
|
|
1373
|
+
private async resolveRef(
|
|
1374
|
+
ref: string,
|
|
1375
|
+
entry: UiRefEntry,
|
|
1376
|
+
): Promise<{ entry: UiRefEntry } | { fail: UiActResult }> {
|
|
1377
|
+
const latest = this.windowReads.get(entry.hwnd)
|
|
1378
|
+
if (
|
|
1379
|
+
latest &&
|
|
1380
|
+
entry.readSeq === latest.seq &&
|
|
1381
|
+
entry.generation === this.sessionGeneration &&
|
|
1382
|
+
this.now() - entry.readAt <= IDENTITY_FRESH_MS
|
|
1383
|
+
)
|
|
1384
|
+
return { entry }
|
|
1385
|
+
const target = { hwnd: entry.hwnd, pid: entry.pid }
|
|
1386
|
+
let read: Awaited<ReturnType<CuaDriverAdapter['readWindowTree']>>
|
|
1387
|
+
try {
|
|
1388
|
+
read = await this.readWindowTree(target, {})
|
|
1389
|
+
} catch (error) {
|
|
1390
|
+
const gone = await this.windowIsGone(entry)
|
|
1391
|
+
if (gone)
|
|
1392
|
+
return {
|
|
1393
|
+
fail: refFailure(
|
|
1394
|
+
'STALE_REF',
|
|
1395
|
+
`the window of ${describeEvidence(entry)} is closed. Nothing was sent. List the windows again.`,
|
|
1396
|
+
),
|
|
1397
|
+
}
|
|
1398
|
+
return {
|
|
1399
|
+
fail: {
|
|
1400
|
+
ok: false,
|
|
1401
|
+
delivery: 'not_delivered',
|
|
1402
|
+
retrySafety: 'safe',
|
|
1403
|
+
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.`,
|
|
1404
|
+
},
|
|
1405
|
+
}
|
|
1406
|
+
}
|
|
1407
|
+
const found = locate(entry, read.tree, { actionable: true })
|
|
1408
|
+
this.bindRead(target, read, { shown: new Set(), regions: new Set() })
|
|
1409
|
+
const next = this.uiRefs.get(ref)
|
|
1410
|
+
if (found.kind === 'found' && next && next.readSeq === this.windowReads.get(entry.hwnd)?.seq)
|
|
1411
|
+
return { entry: next }
|
|
1412
|
+
if (found.kind === 'ambiguous' || found.kind === 'found')
|
|
1413
|
+
return {
|
|
1414
|
+
fail: refFailure(
|
|
1415
|
+
'AMBIGUOUS_TARGET',
|
|
1416
|
+
`${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.`,
|
|
1417
|
+
),
|
|
1418
|
+
}
|
|
549
1419
|
return {
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
1420
|
+
fail: refFailure(
|
|
1421
|
+
'STALE_REF',
|
|
1422
|
+
`${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.`,
|
|
1423
|
+
),
|
|
1424
|
+
}
|
|
1425
|
+
}
|
|
1426
|
+
|
|
1427
|
+
/** Whether the ref's window has closed (or changed owner). Costs a window list, so only asked after a failure. */
|
|
1428
|
+
private async windowIsGone(entry: UiRefEntry): Promise<boolean> {
|
|
1429
|
+
try {
|
|
1430
|
+
const windows = await this.listWindows()
|
|
1431
|
+
const id = windowIdOf(entry.hwnd)
|
|
1432
|
+
const found = windows.find((window) => window.id === id)
|
|
1433
|
+
return !found || found.pid !== entry.pid
|
|
1434
|
+
} catch {
|
|
1435
|
+
return false
|
|
555
1436
|
}
|
|
556
1437
|
}
|
|
557
1438
|
|
|
558
1439
|
async uiAct(ref: string, action: UiElementAction, value?: string): Promise<UiActResult> {
|
|
559
|
-
|
|
560
|
-
|
|
1440
|
+
return this.actOn(ref, action, value, true)
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
private async actOn(
|
|
1444
|
+
ref: string,
|
|
1445
|
+
action: UiElementAction,
|
|
1446
|
+
value: string | undefined,
|
|
1447
|
+
retry: boolean,
|
|
1448
|
+
): Promise<UiActResult> {
|
|
1449
|
+
const held = this.uiRefs.get(ref)
|
|
1450
|
+
if (!held)
|
|
1451
|
+
return refFailure(
|
|
1452
|
+
'STALE_REF',
|
|
1453
|
+
`${ref} is not a control this session was shown, so nothing was sent. Take a ui_snapshot and use a ref from it.`,
|
|
1454
|
+
)
|
|
1455
|
+
if (held.region)
|
|
561
1456
|
return {
|
|
562
1457
|
ok: false,
|
|
563
|
-
|
|
1458
|
+
delivery: 'not_delivered',
|
|
1459
|
+
retrySafety: 'safe',
|
|
1460
|
+
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
1461
|
}
|
|
1462
|
+
const resolved = await this.resolveRef(ref, held)
|
|
1463
|
+
if ('fail' in resolved) return resolved.fail
|
|
1464
|
+
const facts = resolved.entry
|
|
565
1465
|
const { pid, token } = facts
|
|
566
1466
|
const uiRef = { ref, facts }
|
|
1467
|
+
this.tryPresence((presence) =>
|
|
1468
|
+
presence.mark({
|
|
1469
|
+
hwnd: facts.hwnd,
|
|
1470
|
+
kind: action === 'set_value' ? 'type' : 'click',
|
|
1471
|
+
...(facts.bounds
|
|
1472
|
+
? {
|
|
1473
|
+
at: {
|
|
1474
|
+
x: facts.bounds.x + facts.bounds.width / 2,
|
|
1475
|
+
y: facts.bounds.y + facts.bounds.height / 2,
|
|
1476
|
+
},
|
|
1477
|
+
}
|
|
1478
|
+
: {}),
|
|
1479
|
+
}),
|
|
1480
|
+
)
|
|
567
1481
|
try {
|
|
568
1482
|
switch (action) {
|
|
569
1483
|
case 'invoke':
|
|
570
|
-
case 'toggle':
|
|
571
|
-
case 'select':
|
|
572
1484
|
case 'expand':
|
|
573
1485
|
case 'collapse':
|
|
574
1486
|
// cua-driver's click on an element token performs the control's
|
|
575
1487
|
// own pattern in the background (Invoke, or a posted click at its
|
|
576
1488
|
// centre), with no pointer move and no change of foreground.
|
|
577
|
-
return
|
|
578
|
-
|
|
579
|
-
|
|
1489
|
+
return await this.clickAndWatch(facts, uiRef)
|
|
1490
|
+
case 'select': {
|
|
1491
|
+
// 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.
|
|
1492
|
+
if (ITEM_ROLES.test(facts.role) && facts.actions.includes('invoke'))
|
|
1493
|
+
return await this.selectWithoutOpening(facts)
|
|
1494
|
+
const sent = await this.clickRef(facts, uiRef)
|
|
1495
|
+
if (!sent.ok) return sent
|
|
1496
|
+
return judgeSelect(facts, await this.readBack(facts))
|
|
1497
|
+
}
|
|
1498
|
+
case 'toggle': {
|
|
1499
|
+
const sent = await this.clickRef(facts, uiRef)
|
|
1500
|
+
if (!sent.ok) return sent
|
|
1501
|
+
const back = await this.readBack(facts)
|
|
1502
|
+
return judgeToggle(facts, back)
|
|
1503
|
+
}
|
|
580
1504
|
case 'set_value': {
|
|
581
1505
|
const text = value ?? ''
|
|
1506
|
+
let sent: UiActResult
|
|
582
1507
|
try {
|
|
583
|
-
|
|
1508
|
+
sent = actResult(
|
|
584
1509
|
await this.callTool(
|
|
585
1510
|
'set_value',
|
|
586
1511
|
{ pid, element_token: token, value: text },
|
|
@@ -590,51 +1515,443 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
590
1515
|
)
|
|
591
1516
|
} catch (error) {
|
|
592
1517
|
if (
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
)
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
1518
|
+
error instanceof McpToolError &&
|
|
1519
|
+
/does not implement ValuePattern/i.test(error.message)
|
|
1520
|
+
) {
|
|
1521
|
+
// A classic edit control takes its text by window message, never by focus or keys.
|
|
1522
|
+
const edited = await this.setByMessages(facts, text)
|
|
1523
|
+
if (edited) return edited
|
|
1524
|
+
// Typing instead would equal setting only while the field is
|
|
1525
|
+
// empty, and the driver's own report of it is not trustworthy.
|
|
600
1526
|
return {
|
|
601
1527
|
ok: false,
|
|
1528
|
+
delivery: 'not_delivered',
|
|
1529
|
+
retrySafety: 'safe',
|
|
602
1530
|
detail:
|
|
603
|
-
'this field
|
|
1531
|
+
'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
1532
|
}
|
|
605
|
-
|
|
606
|
-
|
|
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
|
|
1533
|
+
}
|
|
1534
|
+
throw error
|
|
619
1535
|
}
|
|
1536
|
+
if (!sent.ok) return sent
|
|
1537
|
+
const judged = judgeSetValue(facts, text, await this.readBack(facts))
|
|
1538
|
+
// A choice in a list that ignored the driver is made with the keyboard, in the foreground.
|
|
1539
|
+
if (judged.delivery === 'not_delivered' && CHOICE_ROLES.test(facts.role))
|
|
1540
|
+
return await this.chooseByKeyboard(ref, facts, text, judged)
|
|
1541
|
+
return judged
|
|
620
1542
|
}
|
|
621
1543
|
case 'focus':
|
|
622
1544
|
case 'scroll_into_view':
|
|
623
1545
|
return {
|
|
624
1546
|
ok: false,
|
|
1547
|
+
delivery: 'not_delivered',
|
|
1548
|
+
retrySafety: 'safe',
|
|
625
1549
|
detail: `this host cannot ${action === 'focus' ? 'focus' : 'scroll to'} a control by itself; invoke it or click it instead`,
|
|
626
1550
|
}
|
|
627
1551
|
}
|
|
628
1552
|
} catch (error) {
|
|
629
|
-
if (error instanceof McpToolError
|
|
1553
|
+
if (error instanceof McpToolError && isStaleHandle(error)) {
|
|
1554
|
+
// The driver refused before acting: a newer read of the window replaced
|
|
1555
|
+
// the handle. Read again and find the control by what it is, once.
|
|
1556
|
+
this.windowReads.delete(facts.hwnd)
|
|
1557
|
+
if (retry) return this.actOn(ref, action, value, false)
|
|
1558
|
+
return refFailure(
|
|
1559
|
+
'STALE_REF',
|
|
1560
|
+
`${describeEvidence(facts)} changed while it was being acted on. Nothing was sent. Take a ui_snapshot and try again.`,
|
|
1561
|
+
)
|
|
1562
|
+
}
|
|
1563
|
+
if (error instanceof McpToolError) return failureResult(error)
|
|
630
1564
|
throw error
|
|
631
1565
|
}
|
|
632
1566
|
}
|
|
633
1567
|
|
|
1568
|
+
/**
|
|
1569
|
+
* Choose an option by the keyboard, for a list the driver's value call did
|
|
1570
|
+
* not change (a web page's select element ignores it in the background).
|
|
1571
|
+
* One foreground burst focuses the control, types the option and confirms
|
|
1572
|
+
* it; the control is then read back. Where that does not work either, the
|
|
1573
|
+
* model is told which route to use instead.
|
|
1574
|
+
*/
|
|
1575
|
+
private async chooseByKeyboard(
|
|
1576
|
+
ref: string,
|
|
1577
|
+
stale: UiRefEntry,
|
|
1578
|
+
option: string,
|
|
1579
|
+
unchanged: UiActResult,
|
|
1580
|
+
): Promise<UiActResult> {
|
|
1581
|
+
const ladder = this.foreground
|
|
1582
|
+
const instead =
|
|
1583
|
+
'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.'
|
|
1584
|
+
if (!ladder) return unchanged
|
|
1585
|
+
// The read-back that judged the value replaced the driver's handle: click through the new one.
|
|
1586
|
+
const facts = this.uiRefs.get(ref) ?? stale
|
|
1587
|
+
const uiRef = { ref, facts }
|
|
1588
|
+
const { pid } = facts
|
|
1589
|
+
const hwnd = windowIdOf(facts.hwnd)
|
|
1590
|
+
const subject = {
|
|
1591
|
+
app: this.windowApps.get(hwnd) ?? `process ${pid}`,
|
|
1592
|
+
pid,
|
|
1593
|
+
hwnd,
|
|
1594
|
+
}
|
|
1595
|
+
const scope = {
|
|
1596
|
+
scope: 'window',
|
|
1597
|
+
pid,
|
|
1598
|
+
window_id: facts.hwnd,
|
|
1599
|
+
delivery_mode: 'foreground',
|
|
1600
|
+
}
|
|
1601
|
+
const outcome = await ladder
|
|
1602
|
+
.run(this.burstRequest(subject, true), async (burst) => {
|
|
1603
|
+
await burst.checkpoint()
|
|
1604
|
+
try {
|
|
1605
|
+
await this.callTool(
|
|
1606
|
+
'click',
|
|
1607
|
+
{ pid, element_token: facts.token, delivery_mode: 'foreground' },
|
|
1608
|
+
undefined,
|
|
1609
|
+
uiRef,
|
|
1610
|
+
)
|
|
1611
|
+
await burst.checkpoint()
|
|
1612
|
+
await this.callTool('type_text', { ...scope, text: option })
|
|
1613
|
+
await burst.checkpoint()
|
|
1614
|
+
await this.callTool('press_key', { ...scope, key: 'return' })
|
|
1615
|
+
return undefined
|
|
1616
|
+
} catch (error) {
|
|
1617
|
+
if (error instanceof McpToolError) return failureResult(error)
|
|
1618
|
+
throw error
|
|
1619
|
+
}
|
|
1620
|
+
})
|
|
1621
|
+
.catch((error: unknown) => {
|
|
1622
|
+
if (error instanceof BurstInterrupted) return error
|
|
1623
|
+
throw error
|
|
1624
|
+
})
|
|
1625
|
+
if (outcome instanceof BurstInterrupted)
|
|
1626
|
+
return {
|
|
1627
|
+
ok: false,
|
|
1628
|
+
delivery: 'not_delivered',
|
|
1629
|
+
retrySafety: 'safe',
|
|
1630
|
+
detail:
|
|
1631
|
+
outcome.reason === 'person'
|
|
1632
|
+
? 'a person used the keyboard or mouse just before the choice was made, so it may not have been. Try again in a moment.'
|
|
1633
|
+
: 'an administrator window came to the front just before the choice was made; Namzu cannot type into it. Try again once it is gone.',
|
|
1634
|
+
}
|
|
1635
|
+
if (outcome.kind === 'blocked')
|
|
1636
|
+
return {
|
|
1637
|
+
ok: false,
|
|
1638
|
+
delivery: 'not_delivered',
|
|
1639
|
+
retrySafety: 'safe',
|
|
1640
|
+
detail: `${outcome.block.detail} ${instead}`,
|
|
1641
|
+
}
|
|
1642
|
+
const dropped = droppedInputNote(outcome)
|
|
1643
|
+
if (dropped)
|
|
1644
|
+
return {
|
|
1645
|
+
ok: false,
|
|
1646
|
+
delivery: 'not_delivered',
|
|
1647
|
+
retrySafety: 'safe',
|
|
1648
|
+
detail: `${dropped} ${instead}`,
|
|
1649
|
+
}
|
|
1650
|
+
const note = interferenceNote(outcome)
|
|
1651
|
+
if (outcome.value && !outcome.value.ok) return outcome.value
|
|
1652
|
+
const judged = judgeSetValue(facts, option, await this.readBack(facts))
|
|
1653
|
+
if (note)
|
|
1654
|
+
return {
|
|
1655
|
+
...judged,
|
|
1656
|
+
delivery: 'delivered_unverified',
|
|
1657
|
+
retrySafety: 'unsafe',
|
|
1658
|
+
detail: note,
|
|
1659
|
+
}
|
|
1660
|
+
if (judged.delivery === 'delivered_verified')
|
|
1661
|
+
return { ...judged, detail: foregroundNote(outcome) }
|
|
1662
|
+
return { ...judged, detail: `${judged.detail ?? ''} ${instead}`.trim() }
|
|
1663
|
+
}
|
|
1664
|
+
|
|
1665
|
+
/**
|
|
1666
|
+
* Select a list or tree row that can also be invoked, through its selection
|
|
1667
|
+
* pattern, so that a file row is chosen and not opened. Where that cannot be
|
|
1668
|
+
* reached nothing is sent: the click that is left would open the item.
|
|
1669
|
+
*/
|
|
1670
|
+
private async selectWithoutOpening(facts: UiRefEntry): Promise<UiActResult> {
|
|
1671
|
+
const result = await this.foreground?.selectItem({
|
|
1672
|
+
hwnd: windowIdOf(facts.hwnd),
|
|
1673
|
+
role: facts.role,
|
|
1674
|
+
name: facts.name,
|
|
1675
|
+
...(facts.automationId ? { automationId: facts.automationId } : {}),
|
|
1676
|
+
...(facts.bounds ? { bounds: facts.bounds } : {}),
|
|
1677
|
+
})
|
|
1678
|
+
if (!result?.found) {
|
|
1679
|
+
const why = result
|
|
1680
|
+
? (SELECT_REFUSALS[result.reason] ?? 'the row could not be selected')
|
|
1681
|
+
: 'this host cannot select a row without opening it'
|
|
1682
|
+
return {
|
|
1683
|
+
ok: false,
|
|
1684
|
+
delivery: 'not_delivered',
|
|
1685
|
+
retrySafety: 'safe',
|
|
1686
|
+
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.`,
|
|
1687
|
+
}
|
|
1688
|
+
}
|
|
1689
|
+
const back = await this.readBack(facts)
|
|
1690
|
+
if (back?.selected === true || (back === undefined && result.selected))
|
|
1691
|
+
return {
|
|
1692
|
+
ok: true,
|
|
1693
|
+
delivery: 'delivered_verified',
|
|
1694
|
+
retrySafety: 'unsafe',
|
|
1695
|
+
readBack: { expected: 'selected', observed: 'selected' },
|
|
1696
|
+
detail: 'The row is selected; it was not opened.',
|
|
1697
|
+
}
|
|
1698
|
+
return {
|
|
1699
|
+
ok: true,
|
|
1700
|
+
delivery: 'delivered_unverified',
|
|
1701
|
+
retrySafety: 'unsafe',
|
|
1702
|
+
readBack: { expected: 'selected', observed: 'not selected' },
|
|
1703
|
+
detail: 'the row was selected by its selection pattern, but it does not read as selected.',
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
|
|
1707
|
+
/** Replace a classic edit control's text by window message; undefined where the control is not one this reaches. */
|
|
1708
|
+
private async setByMessages(facts: UiRefEntry, text: string): Promise<UiActResult | undefined> {
|
|
1709
|
+
const ladder = this.foreground
|
|
1710
|
+
if (!ladder) return undefined
|
|
1711
|
+
const result = await ladder.editText({
|
|
1712
|
+
hwnd: windowIdOf(facts.hwnd),
|
|
1713
|
+
op: 'set',
|
|
1714
|
+
text,
|
|
1715
|
+
pick: 'bounds',
|
|
1716
|
+
...(facts.bounds
|
|
1717
|
+
? {
|
|
1718
|
+
at: {
|
|
1719
|
+
x: facts.bounds.x + facts.bounds.width / 2,
|
|
1720
|
+
y: facts.bounds.y + facts.bounds.height / 2,
|
|
1721
|
+
},
|
|
1722
|
+
}
|
|
1723
|
+
: {}),
|
|
1724
|
+
})
|
|
1725
|
+
if (!result) return undefined
|
|
1726
|
+
if (!result.found) {
|
|
1727
|
+
if (result.reason === 'uipi' || result.reason === 'gone')
|
|
1728
|
+
return { ...judgeEdit('set', text, result), ok: false }
|
|
1729
|
+
return undefined
|
|
1730
|
+
}
|
|
1731
|
+
return judgeEdit('set', text, result)
|
|
1732
|
+
}
|
|
1733
|
+
|
|
1734
|
+
/**
|
|
1735
|
+
* A shortcut with a modifier, carried out as the window's own menu command. Undefined where the window has no
|
|
1736
|
+
* classic menu item for it (the usual case for a modern window), so the key goes the ordinary way.
|
|
1737
|
+
*/
|
|
1738
|
+
private async shortcutByMenu(
|
|
1739
|
+
frame: WindowCaptureFrame,
|
|
1740
|
+
keys: string,
|
|
1741
|
+
): Promise<WindowInputResult | undefined> {
|
|
1742
|
+
const ladder = this.foreground
|
|
1743
|
+
if (!ladder) return undefined
|
|
1744
|
+
const accelerator = menuAcceleratorOf(keys)
|
|
1745
|
+
if (accelerator === undefined) return undefined
|
|
1746
|
+
const result = await ladder.menuCommand({ hwnd: frame.window.id, accelerator })
|
|
1747
|
+
if (!result?.found) return undefined
|
|
1748
|
+
this.showPresence(frame, frame.window.bounds, 'hotkey', {})
|
|
1749
|
+
return {
|
|
1750
|
+
delivery: 'delivered_unverified',
|
|
1751
|
+
retrySafety: 'unsafe',
|
|
1752
|
+
detail: `Carried out as the window's menu command "${result.label ?? accelerator}" (no key pressed, the screen not used).`,
|
|
1753
|
+
}
|
|
1754
|
+
}
|
|
1755
|
+
|
|
1756
|
+
/** Type into the window's focused classic edit control by window message; undefined where there is none. */
|
|
1757
|
+
private async typeByMessages(
|
|
1758
|
+
frame: WindowCaptureFrame,
|
|
1759
|
+
text: string,
|
|
1760
|
+
): Promise<WindowInputResult | undefined> {
|
|
1761
|
+
const ladder = this.foreground
|
|
1762
|
+
if (!ladder) return undefined
|
|
1763
|
+
const result = await ladder.editText({
|
|
1764
|
+
hwnd: frame.window.id,
|
|
1765
|
+
op: 'type',
|
|
1766
|
+
text,
|
|
1767
|
+
pick: 'focus',
|
|
1768
|
+
})
|
|
1769
|
+
if (!result) return undefined
|
|
1770
|
+
if (!result.found) {
|
|
1771
|
+
if (result.reason !== 'uipi') return undefined
|
|
1772
|
+
return judgeEdit('type', text, result)
|
|
1773
|
+
}
|
|
1774
|
+
this.showPresence(frame, frame.window.bounds, 'type_text', {})
|
|
1775
|
+
const { ok: _ok, ...verdict } = judgeEdit('type', text, result)
|
|
1776
|
+
return verdict
|
|
1777
|
+
}
|
|
1778
|
+
|
|
1779
|
+
/**
|
|
1780
|
+
* A click on a control that the control's own state does not answer for
|
|
1781
|
+
* (a button): when the driver cannot confirm it, the window is read before
|
|
1782
|
+
* and after, and the click is verified by what it changed.
|
|
1783
|
+
*/
|
|
1784
|
+
private async clickAndWatch(
|
|
1785
|
+
facts: UiRefEntry,
|
|
1786
|
+
uiRef: { readonly ref: string; readonly facts: UiRefEntry },
|
|
1787
|
+
): Promise<UiActResult> {
|
|
1788
|
+
const target = { hwnd: facts.hwnd, pid: facts.pid }
|
|
1789
|
+
const earlier = await this.observe(target)
|
|
1790
|
+
const before = await this.observe(target)
|
|
1791
|
+
const windows = await this.windowIdsOf(target.pid)
|
|
1792
|
+
// Each read of the window replaces the driver's handles: click through the refreshed one.
|
|
1793
|
+
const current = this.uiRefs.get(uiRef.ref) ?? facts
|
|
1794
|
+
const sent = await this.clickRef(current, {
|
|
1795
|
+
ref: uiRef.ref,
|
|
1796
|
+
facts: current,
|
|
1797
|
+
})
|
|
1798
|
+
if (!sent.ok || sent.delivery !== 'delivered_unverified' || !before) return sent
|
|
1799
|
+
const seen = await this.verifyByReading(target, {
|
|
1800
|
+
typed: undefined,
|
|
1801
|
+
before,
|
|
1802
|
+
earlier,
|
|
1803
|
+
windows,
|
|
1804
|
+
})
|
|
1805
|
+
if (!seen) return sent
|
|
1806
|
+
return {
|
|
1807
|
+
ok: true,
|
|
1808
|
+
delivery: seen.delivery,
|
|
1809
|
+
retrySafety: seen.retrySafety,
|
|
1810
|
+
detail: seen.detail,
|
|
1811
|
+
...(seen.observed !== undefined ? { readBack: { observed: seen.observed } } : {}),
|
|
1812
|
+
}
|
|
1813
|
+
}
|
|
1814
|
+
|
|
1815
|
+
/**
|
|
1816
|
+
* A click on a control by its driver token, in the background. Where the
|
|
1817
|
+
* driver says the window cannot take background input (or is covered) the
|
|
1818
|
+
* same click is retried in the foreground through the ladder.
|
|
1819
|
+
*/
|
|
1820
|
+
private async clickRef(
|
|
1821
|
+
facts: UiRefEntry,
|
|
1822
|
+
uiRef: { readonly ref: string; readonly facts: UiRefEntry },
|
|
1823
|
+
): Promise<UiActResult> {
|
|
1824
|
+
const { pid, token } = facts
|
|
1825
|
+
try {
|
|
1826
|
+
return actResult(
|
|
1827
|
+
await this.callTool('click', { pid, element_token: token }, undefined, uiRef),
|
|
1828
|
+
)
|
|
1829
|
+
} catch (error) {
|
|
1830
|
+
const ladder = this.foreground
|
|
1831
|
+
if (!(error instanceof McpToolError) || !ladder || !foregroundCures(error)) throw error
|
|
1832
|
+
const subject = {
|
|
1833
|
+
app: this.windowApps.get(windowIdOf(facts.hwnd)) ?? `process ${pid}`,
|
|
1834
|
+
pid,
|
|
1835
|
+
hwnd: windowIdOf(facts.hwnd),
|
|
1836
|
+
}
|
|
1837
|
+
const outcome = await ladder
|
|
1838
|
+
.run(this.burstRequest(subject, true), async (burst) => {
|
|
1839
|
+
await burst.checkpoint()
|
|
1840
|
+
try {
|
|
1841
|
+
return actResult(
|
|
1842
|
+
await this.callTool(
|
|
1843
|
+
'click',
|
|
1844
|
+
{ pid, element_token: token, delivery_mode: 'foreground' },
|
|
1845
|
+
undefined,
|
|
1846
|
+
uiRef,
|
|
1847
|
+
),
|
|
1848
|
+
)
|
|
1849
|
+
} catch (inner) {
|
|
1850
|
+
if (inner instanceof McpToolError) return failureResult(inner)
|
|
1851
|
+
throw inner
|
|
1852
|
+
}
|
|
1853
|
+
})
|
|
1854
|
+
.catch((inner: unknown) => {
|
|
1855
|
+
if (inner instanceof BurstInterrupted) return inner
|
|
1856
|
+
throw inner
|
|
1857
|
+
})
|
|
1858
|
+
if (outcome instanceof BurstInterrupted)
|
|
1859
|
+
return {
|
|
1860
|
+
ok: false,
|
|
1861
|
+
delivery: 'not_delivered',
|
|
1862
|
+
retrySafety: 'safe',
|
|
1863
|
+
detail:
|
|
1864
|
+
outcome.reason === 'person'
|
|
1865
|
+
? 'a person used the keyboard or mouse just before the click was sent, so nothing was sent. Try again in a moment.'
|
|
1866
|
+
: '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.',
|
|
1867
|
+
}
|
|
1868
|
+
if (outcome.kind === 'blocked')
|
|
1869
|
+
return {
|
|
1870
|
+
ok: false,
|
|
1871
|
+
delivery: 'not_delivered',
|
|
1872
|
+
retrySafety: 'safe',
|
|
1873
|
+
detail: outcome.block.detail,
|
|
1874
|
+
}
|
|
1875
|
+
const dropped = droppedInputNote(outcome)
|
|
1876
|
+
if (dropped)
|
|
1877
|
+
return {
|
|
1878
|
+
ok: false,
|
|
1879
|
+
delivery: 'not_delivered',
|
|
1880
|
+
retrySafety: 'safe',
|
|
1881
|
+
detail: dropped,
|
|
1882
|
+
}
|
|
1883
|
+
const note = interferenceNote(outcome)
|
|
1884
|
+
const base = outcome.value
|
|
1885
|
+
const detail = [base.detail, note ?? foregroundNote(outcome)].filter(Boolean).join(' ')
|
|
1886
|
+
if (note && base.delivery !== 'not_delivered')
|
|
1887
|
+
return {
|
|
1888
|
+
...base,
|
|
1889
|
+
delivery: 'delivered_unverified',
|
|
1890
|
+
retrySafety: 'unsafe',
|
|
1891
|
+
detail,
|
|
1892
|
+
}
|
|
1893
|
+
return { ...base, detail }
|
|
1894
|
+
}
|
|
1895
|
+
}
|
|
1896
|
+
|
|
1897
|
+
/**
|
|
1898
|
+
* The control as a fresh read of its window shows it, or undefined when
|
|
1899
|
+
* that read failed or the control is gone. A failed read says nothing
|
|
1900
|
+
* about the action, so callers treat undefined as "unverified".
|
|
1901
|
+
*/
|
|
1902
|
+
private async readBack(facts: UiRefEntry): Promise<UiRefFacts | undefined> {
|
|
1903
|
+
try {
|
|
1904
|
+
const target = { hwnd: facts.hwnd, pid: facts.pid }
|
|
1905
|
+
const read = await this.readWindowTree(target, {})
|
|
1906
|
+
const found = locate(facts, read.tree, { actionable: true })
|
|
1907
|
+
this.bindRead(target, read, { shown: new Set(), regions: new Set() })
|
|
1908
|
+
return found.kind === 'found' ? found.node.facts : undefined
|
|
1909
|
+
} catch {
|
|
1910
|
+
return undefined
|
|
1911
|
+
}
|
|
1912
|
+
}
|
|
1913
|
+
|
|
634
1914
|
async dispose(): Promise<void> {
|
|
635
1915
|
await this.client.dispose()
|
|
636
1916
|
}
|
|
637
1917
|
|
|
1918
|
+
/** Tells the overlay where the agent is about to act in a window; never waits and never fails the action. */
|
|
1919
|
+
private showPresence(
|
|
1920
|
+
frame: WindowCaptureFrame,
|
|
1921
|
+
bounds: WindowInfo['bounds'],
|
|
1922
|
+
tool: string,
|
|
1923
|
+
args: Record<string, unknown>,
|
|
1924
|
+
): void {
|
|
1925
|
+
const presence = this.presence
|
|
1926
|
+
if (!presence) return
|
|
1927
|
+
const hwnd = parseWindowId(frame.window.id)
|
|
1928
|
+
if (hwnd === undefined) return
|
|
1929
|
+
const scale = frame.width > 0 ? bounds.width / frame.width : 1
|
|
1930
|
+
const screen = (x: unknown, y: unknown): { x: number; y: number } | undefined =>
|
|
1931
|
+
typeof x === 'number' && typeof y === 'number'
|
|
1932
|
+
? { x: bounds.x + x * scale, y: bounds.y + y * scale }
|
|
1933
|
+
: undefined
|
|
1934
|
+
const at = screen(args.x ?? args.to_x, args.y ?? args.to_y)
|
|
1935
|
+
const typing = tool === 'type_text' || tool === 'press_key' || tool === 'hotkey'
|
|
1936
|
+
this.tryPresence((overlay) =>
|
|
1937
|
+
overlay.mark({
|
|
1938
|
+
hwnd,
|
|
1939
|
+
kind: typing ? 'type' : 'click',
|
|
1940
|
+
...(at && !typing ? { at } : {}),
|
|
1941
|
+
}),
|
|
1942
|
+
)
|
|
1943
|
+
}
|
|
1944
|
+
|
|
1945
|
+
/** The overlay is decoration: whatever it does, the action goes on. */
|
|
1946
|
+
private tryPresence(use: (presence: Presence) => void): void {
|
|
1947
|
+
if (!this.presence || this.driverCursorOff === false) return
|
|
1948
|
+
try {
|
|
1949
|
+
use(this.presence)
|
|
1950
|
+
} catch {
|
|
1951
|
+
// Nothing is shown; nothing else changes.
|
|
1952
|
+
}
|
|
1953
|
+
}
|
|
1954
|
+
|
|
638
1955
|
private async serializeWindowOperation<T>(operation: () => Promise<T>): Promise<T> {
|
|
639
1956
|
const previous = this.windowOperation
|
|
640
1957
|
let release: () => void = () => undefined
|
|
@@ -673,22 +1990,31 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
673
1990
|
if (
|
|
674
1991
|
uiRef &&
|
|
675
1992
|
(this.uiRefs.get(uiRef.ref) !== uiRef.facts ||
|
|
676
|
-
uiRef.facts.generation !== this.sessionGeneration
|
|
1993
|
+
uiRef.facts.generation !== this.sessionGeneration ||
|
|
1994
|
+
this.windowReads.get(uiRef.facts.hwnd)?.seq !== uiRef.facts.readSeq)
|
|
677
1995
|
)
|
|
678
1996
|
throw new McpToolError(name, 'stale UI snapshot; take a new one')
|
|
679
1997
|
const generation = this.sessionGeneration
|
|
1998
|
+
const signal = currentCallSignal()
|
|
1999
|
+
const changes = changesDesktop(name)
|
|
680
2000
|
try {
|
|
681
|
-
|
|
2001
|
+
const result = await this.client.callTool(name, args, timeoutMs, {
|
|
2002
|
+
...(signal ? { signal } : {}),
|
|
682
2003
|
...(uiRef || windowFrame
|
|
683
|
-
? {
|
|
2004
|
+
? {
|
|
2005
|
+
expectedStarts: uiRef?.facts.processStarts ?? windowFrame?.processStarts,
|
|
2006
|
+
}
|
|
684
2007
|
: {}),
|
|
685
2008
|
...(onProcess ? { onProcess } : {}),
|
|
686
2009
|
})
|
|
2010
|
+
if (changes) markSent()
|
|
2011
|
+
return result
|
|
687
2012
|
} catch (error) {
|
|
2013
|
+
if (error instanceof CallAbortedError && error.sent && changes) markSent()
|
|
688
2014
|
if (!isEndedSessionRefusal(error)) throw error
|
|
689
2015
|
// The refusal proves the old session's element tokens are invalid,
|
|
690
2016
|
// even if start_session fails and there is no successful revival.
|
|
691
|
-
if (this.sessionGeneration === generation) this.
|
|
2017
|
+
if (this.sessionGeneration === generation) this.windowReads.clear()
|
|
692
2018
|
this.windowFrame = undefined
|
|
693
2019
|
await this.reviveSession(generation)
|
|
694
2020
|
// Element tokens belong to the old snapshot. A new lifecycle session
|
|
@@ -698,7 +2024,27 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
698
2024
|
throw new McpToolError(name, 'stale window screenshot; capture the window again')
|
|
699
2025
|
// One retry only. A second refusal or an unacknowledged action is
|
|
700
2026
|
// returned to the host without any further automatic replay.
|
|
701
|
-
|
|
2027
|
+
const retried = await this.client.callTool(name, args, timeoutMs, {
|
|
2028
|
+
...(signal ? { signal } : {}),
|
|
2029
|
+
...(onProcess ? { onProcess } : {}),
|
|
2030
|
+
})
|
|
2031
|
+
if (changes) markSent()
|
|
2032
|
+
return retried
|
|
2033
|
+
}
|
|
2034
|
+
}
|
|
2035
|
+
|
|
2036
|
+
/**
|
|
2037
|
+
* What a foreground burst asks of the ladder: the call's cancellation, and
|
|
2038
|
+
* the wait for calls a cancelled burst left in flight before the window and
|
|
2039
|
+
* cursor are put back.
|
|
2040
|
+
*/
|
|
2041
|
+
private burstRequest(subject: ForegroundSubject, sendsInput: boolean): LadderRequest {
|
|
2042
|
+
const signal = currentCallSignal()
|
|
2043
|
+
return {
|
|
2044
|
+
subject,
|
|
2045
|
+
sendsInput,
|
|
2046
|
+
...(signal ? { signal } : {}),
|
|
2047
|
+
settle: () => this.client.settled(),
|
|
702
2048
|
}
|
|
703
2049
|
}
|
|
704
2050
|
|
|
@@ -707,8 +2053,10 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
707
2053
|
if (!this.sessionRevival) {
|
|
708
2054
|
this.sessionRevival = (async () => {
|
|
709
2055
|
await this.client.callTool('start_session')
|
|
710
|
-
await disableAgentCursor((name, args) =>
|
|
711
|
-
|
|
2056
|
+
this.driverCursorOff = await disableAgentCursor((name, args) =>
|
|
2057
|
+
this.client.callTool(name, args),
|
|
2058
|
+
)
|
|
2059
|
+
this.windowReads.clear()
|
|
712
2060
|
this.windowFrame = undefined
|
|
713
2061
|
this.sessionGeneration++
|
|
714
2062
|
})().finally(() => {
|
|
@@ -741,15 +2089,24 @@ export class CuaDriverAdapter implements Adapter {
|
|
|
741
2089
|
return { hwnd, pid }
|
|
742
2090
|
}
|
|
743
2091
|
|
|
744
|
-
|
|
2092
|
+
/**
|
|
2093
|
+
* A display pointer action. A click that ends with another window in front
|
|
2094
|
+
* is reported as sent but unverified: it may have closed its own window,
|
|
2095
|
+
* or it may have missed. Neither is "done".
|
|
2096
|
+
*/
|
|
2097
|
+
private async pointer(tool: string, args: Record<string, unknown>): Promise<ComputerUseResult> {
|
|
745
2098
|
try {
|
|
746
|
-
await this.callTool(tool, args)
|
|
2099
|
+
return okResult(inputDelivery(await this.callTool(tool, args)))
|
|
747
2100
|
} catch (error) {
|
|
748
|
-
if (isDeliveredPointerAction(error)) return
|
|
2101
|
+
if (isDeliveredPointerAction(error)) return okResult(foregroundLostDelivery())
|
|
749
2102
|
throw error
|
|
750
2103
|
}
|
|
751
2104
|
}
|
|
752
2105
|
|
|
2106
|
+
private async keyboard(tool: string, args: Record<string, unknown>): Promise<ComputerUseResult> {
|
|
2107
|
+
return okResult(inputDelivery(await this.callTool(tool, args)))
|
|
2108
|
+
}
|
|
2109
|
+
|
|
753
2110
|
private async capture(): Promise<ScreenshotResult> {
|
|
754
2111
|
const result = await this.callTool('get_desktop_state', {}, CAPTURE_TIMEOUT_MS)
|
|
755
2112
|
const image = result.content.find(
|
|
@@ -814,52 +2171,271 @@ export function isDeliveredPointerAction(error: unknown): boolean {
|
|
|
814
2171
|
)
|
|
815
2172
|
}
|
|
816
2173
|
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
2174
|
+
const trimText = (value: string, max = 80): string =>
|
|
2175
|
+
value.length > max ? `${value.slice(0, max - 1)}…` : value
|
|
2176
|
+
|
|
2177
|
+
/** A delivery verdict with the retry advice that goes with it. */
|
|
2178
|
+
function verdict(
|
|
2179
|
+
delivery: ActionDelivery,
|
|
2180
|
+
retrySafety: ActionRetrySafety,
|
|
2181
|
+
detail?: string,
|
|
2182
|
+
): WindowInputResult {
|
|
2183
|
+
return { delivery, retrySafety, ...(detail !== undefined ? { detail } : {}) }
|
|
2184
|
+
}
|
|
2185
|
+
|
|
2186
|
+
/** `ok` with a delivery verdict: a call that returned is never proof that the effect happened. */
|
|
2187
|
+
function okResult(input: WindowInputResult): ComputerUseResult {
|
|
2188
|
+
return { type: 'ok', ...input }
|
|
2189
|
+
}
|
|
2190
|
+
|
|
2191
|
+
/** The click was sent, but the window it targeted is no longer in front afterwards. */
|
|
2192
|
+
function foregroundLostDelivery(): WindowInputResult {
|
|
2193
|
+
return verdict(
|
|
2194
|
+
'delivered_unverified',
|
|
2195
|
+
'unsafe',
|
|
2196
|
+
'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.',
|
|
2197
|
+
)
|
|
2198
|
+
}
|
|
2199
|
+
|
|
2200
|
+
/**
|
|
2201
|
+
* What a driver tool call that returned says about the input it sent.
|
|
2202
|
+
*
|
|
2203
|
+
* The driver reports `effect: "unverifiable"` for nearly every background
|
|
2204
|
+
* action, including ones that did nothing, and its `delivery_failed`
|
|
2205
|
+
* escalation shows up on input that arrived as well as input that did not.
|
|
2206
|
+
* Neither is proof, so only a `confirmed` effect is verified, and anything
|
|
2207
|
+
* else says "sent, not confirmed".
|
|
2208
|
+
*/
|
|
2209
|
+
export function inputDelivery(result: McpToolResult): WindowInputResult {
|
|
2210
|
+
const facts = result.structuredContent ?? {}
|
|
2211
|
+
switch (facts.effect) {
|
|
2212
|
+
case 'refused': {
|
|
2213
|
+
const refusal = facts.refusal as { message?: unknown } | undefined
|
|
2214
|
+
return verdict(
|
|
2215
|
+
'not_delivered',
|
|
2216
|
+
'safe',
|
|
2217
|
+
typeof refusal?.message === 'string' ? refusal.message : 'cua-driver refused the action',
|
|
2218
|
+
)
|
|
2219
|
+
}
|
|
2220
|
+
case 'confirmed':
|
|
2221
|
+
return verdict('delivered_verified', 'unsafe')
|
|
2222
|
+
case 'suspected_noop':
|
|
2223
|
+
return verdict(
|
|
2224
|
+
'delivered_unverified',
|
|
2225
|
+
'unsafe',
|
|
2226
|
+
'the driver suspects the input changed nothing; it may not have reached the target. Look at the window before repeating it.',
|
|
2227
|
+
)
|
|
2228
|
+
default: {
|
|
2229
|
+
const escalation = facts.escalation as { reason?: unknown } | undefined
|
|
2230
|
+
return verdict(
|
|
2231
|
+
'delivered_unverified',
|
|
2232
|
+
'unsafe',
|
|
2233
|
+
escalation?.reason === 'delivery_failed'
|
|
2234
|
+
? '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".'
|
|
2235
|
+
: undefined,
|
|
2236
|
+
)
|
|
2237
|
+
}
|
|
2238
|
+
}
|
|
2239
|
+
}
|
|
2240
|
+
|
|
2241
|
+
/**
|
|
2242
|
+
* A driver tool error → what it means for delivery. A refusal the driver
|
|
2243
|
+
* names means it did not send the input (safe to repeat once the cause is
|
|
2244
|
+
* fixed). Any other error leaves the outcome unknown: it is reported as
|
|
2245
|
+
* unverified and unsafe to repeat.
|
|
2246
|
+
*/
|
|
2247
|
+
export function failureDelivery(error: McpToolError): WindowInputResult {
|
|
2248
|
+
const facts = error.structuredContent ?? {}
|
|
2249
|
+
const code = typeof facts.code === 'string' ? facts.code : undefined
|
|
820
2250
|
if (
|
|
821
2251
|
code === 'background_unavailable' ||
|
|
822
2252
|
code === 'background_occluded' ||
|
|
823
2253
|
code === 'background_uipi_blocked'
|
|
824
2254
|
)
|
|
825
|
-
return
|
|
826
|
-
'
|
|
2255
|
+
return verdict(
|
|
2256
|
+
'not_delivered',
|
|
2257
|
+
'safe',
|
|
2258
|
+
code === 'background_uipi_blocked'
|
|
2259
|
+
? '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.'
|
|
2260
|
+
: code === 'background_occluded'
|
|
2261
|
+
? 'the target is covered by another window, so background input cannot reach it. Nothing was sent.'
|
|
2262
|
+
: '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".',
|
|
2263
|
+
)
|
|
2264
|
+
if (facts.status === 'refused') {
|
|
2265
|
+
const refusal = facts.refusal as { message?: unknown } | undefined
|
|
2266
|
+
return verdict(
|
|
2267
|
+
'not_delivered',
|
|
2268
|
+
'safe',
|
|
2269
|
+
typeof refusal?.message === 'string' ? refusal.message : error.message,
|
|
827
2270
|
)
|
|
828
|
-
|
|
2271
|
+
}
|
|
2272
|
+
if (/stale (window|screenshot)/i.test(error.message))
|
|
2273
|
+
return verdict('not_delivered', 'safe', trimText(error.message, 300))
|
|
2274
|
+
if (/stale/i.test(`${error.message} ${JSON.stringify(facts)}`))
|
|
2275
|
+
return verdict(
|
|
2276
|
+
'not_delivered',
|
|
2277
|
+
'safe',
|
|
2278
|
+
'that control is from an older UI snapshot; take a new one',
|
|
2279
|
+
)
|
|
2280
|
+
// An error the driver does not classify can arrive after input was sent (a
|
|
2281
|
+
// foreground burst calls this too), so it never invites a blind resend.
|
|
2282
|
+
return verdict(
|
|
2283
|
+
'delivered_unverified',
|
|
2284
|
+
'unsafe',
|
|
2285
|
+
`${trimText(error.message, 300)} The input may have been sent; look at the window before repeating it.`,
|
|
2286
|
+
)
|
|
2287
|
+
}
|
|
2288
|
+
|
|
2289
|
+
/** The driver refused a handle a newer read of its window replaced (nothing was sent). */
|
|
2290
|
+
function isStaleHandle(error: McpToolError): boolean {
|
|
2291
|
+
if (/stale (window|screenshot)/i.test(error.message)) return false
|
|
2292
|
+
return /stale_element_token|stale (UI|element)/i.test(
|
|
2293
|
+
`${error.message} ${JSON.stringify(error.structuredContent ?? {})}`,
|
|
2294
|
+
)
|
|
2295
|
+
}
|
|
2296
|
+
|
|
2297
|
+
/** Refusals that a foreground delivery can cure. `uipi_blocked` is not one: it blocks foreground input too. */
|
|
2298
|
+
function foregroundCures(error: McpToolError): boolean {
|
|
2299
|
+
const code = error.structuredContent?.code
|
|
2300
|
+
return code === 'background_unavailable' || code === 'background_occluded'
|
|
2301
|
+
}
|
|
2302
|
+
|
|
2303
|
+
function failureResult(error: McpToolError): UiActResult {
|
|
2304
|
+
const { delivery, retrySafety, detail } = failureDelivery(error)
|
|
2305
|
+
return {
|
|
2306
|
+
ok: false,
|
|
2307
|
+
delivery,
|
|
2308
|
+
retrySafety,
|
|
2309
|
+
...(detail !== undefined ? { detail } : {}),
|
|
2310
|
+
}
|
|
829
2311
|
}
|
|
830
2312
|
|
|
831
2313
|
/**
|
|
832
|
-
* cua-driver's action result → the host's. `
|
|
833
|
-
*
|
|
834
|
-
*
|
|
835
|
-
*
|
|
2314
|
+
* cua-driver's action result → the host's. `unverifiable` is the driver's
|
|
2315
|
+
* answer to almost everything it does in the background, so a result that
|
|
2316
|
+
* returned is "sent", and the stateful actions are judged by reading the
|
|
2317
|
+
* control back.
|
|
836
2318
|
*/
|
|
837
2319
|
export function actResult(result: McpToolResult): UiActResult {
|
|
838
|
-
const
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
2320
|
+
const sent = inputDelivery(result)
|
|
2321
|
+
return {
|
|
2322
|
+
ok: sent.delivery !== 'not_delivered' && result.structuredContent?.effect !== 'suspected_noop',
|
|
2323
|
+
delivery: sent.delivery,
|
|
2324
|
+
retrySafety: sent.retrySafety,
|
|
2325
|
+
...(sent.detail !== undefined ? { detail: sent.detail } : {}),
|
|
2326
|
+
}
|
|
2327
|
+
}
|
|
2328
|
+
|
|
2329
|
+
const same = (a: string, b: string): boolean => a.trim() === b.trim()
|
|
2330
|
+
|
|
2331
|
+
/** set_value, judged by the field as a fresh read shows it. */
|
|
2332
|
+
export function judgeSetValue(
|
|
2333
|
+
before: UiRefFacts,
|
|
2334
|
+
expected: string,
|
|
2335
|
+
after: UiRefFacts | undefined,
|
|
2336
|
+
): UiActResult {
|
|
2337
|
+
if (!after)
|
|
2338
|
+
return {
|
|
2339
|
+
ok: true,
|
|
2340
|
+
delivery: 'delivered_unverified',
|
|
2341
|
+
retrySafety: 'unsafe',
|
|
2342
|
+
detail:
|
|
2343
|
+
'the value was sent, but the field could not be read back (the window may have changed). Check it before setting it again.',
|
|
2344
|
+
}
|
|
2345
|
+
if (after.value === undefined)
|
|
2346
|
+
return {
|
|
2347
|
+
ok: true,
|
|
2348
|
+
delivery: 'delivered_unverified',
|
|
2349
|
+
retrySafety: 'unsafe',
|
|
2350
|
+
detail:
|
|
2351
|
+
'the value was sent; this control does not report its value, so it could not be checked. Look at the window.',
|
|
852
2352
|
}
|
|
853
|
-
|
|
854
|
-
|
|
2353
|
+
if (same(after.value, expected))
|
|
2354
|
+
return {
|
|
2355
|
+
ok: true,
|
|
2356
|
+
delivery: 'delivered_verified',
|
|
2357
|
+
retrySafety: 'safe',
|
|
2358
|
+
readBack: {
|
|
2359
|
+
expected: trimText(expected),
|
|
2360
|
+
observed: trimText(after.value),
|
|
2361
|
+
},
|
|
2362
|
+
}
|
|
2363
|
+
if (before.value !== undefined && same(before.value, after.value))
|
|
2364
|
+
return {
|
|
2365
|
+
ok: false,
|
|
2366
|
+
delivery: 'not_delivered',
|
|
2367
|
+
retrySafety: 'safe',
|
|
2368
|
+
readBack: {
|
|
2369
|
+
expected: trimText(expected),
|
|
2370
|
+
observed: trimText(after.value),
|
|
2371
|
+
},
|
|
2372
|
+
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.`,
|
|
2373
|
+
}
|
|
2374
|
+
return {
|
|
2375
|
+
ok: true,
|
|
2376
|
+
delivery: 'delivered_unverified',
|
|
2377
|
+
retrySafety: 'unsafe',
|
|
2378
|
+
readBack: { expected: trimText(expected), observed: trimText(after.value) },
|
|
2379
|
+
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
2380
|
}
|
|
856
2381
|
}
|
|
857
2382
|
|
|
858
|
-
/**
|
|
859
|
-
function
|
|
860
|
-
if (
|
|
861
|
-
return
|
|
862
|
-
|
|
2383
|
+
/** toggle, judged by whether the control's selected state flipped. */
|
|
2384
|
+
export function judgeToggle(before: UiRefFacts, after: UiRefFacts | undefined): UiActResult {
|
|
2385
|
+
if (!after)
|
|
2386
|
+
return {
|
|
2387
|
+
ok: true,
|
|
2388
|
+
delivery: 'delivered_unverified',
|
|
2389
|
+
retrySafety: 'unsafe',
|
|
2390
|
+
detail:
|
|
2391
|
+
'the toggle was sent, but the control could not be read back. A second toggle would undo it; check first.',
|
|
2392
|
+
}
|
|
2393
|
+
if (after.selected !== before.selected)
|
|
2394
|
+
return {
|
|
2395
|
+
ok: true,
|
|
2396
|
+
delivery: 'delivered_verified',
|
|
2397
|
+
retrySafety: 'unsafe',
|
|
2398
|
+
readBack: {
|
|
2399
|
+
expected: String(!before.selected),
|
|
2400
|
+
observed: String(after.selected),
|
|
2401
|
+
},
|
|
2402
|
+
}
|
|
2403
|
+
return {
|
|
2404
|
+
ok: true,
|
|
2405
|
+
delivery: 'delivered_unverified',
|
|
2406
|
+
retrySafety: 'unsafe',
|
|
2407
|
+
readBack: { observed: String(after.selected) },
|
|
2408
|
+
detail:
|
|
2409
|
+
'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.',
|
|
2410
|
+
}
|
|
2411
|
+
}
|
|
2412
|
+
|
|
2413
|
+
const ITEM_ROLES = /^(ListItem|TreeItem|DataItem)$/
|
|
2414
|
+
|
|
2415
|
+
const SELECT_REFUSALS: Readonly<Record<string, string>> = {
|
|
2416
|
+
gone: 'the window is gone',
|
|
2417
|
+
not_found: 'the row is not in the window any more',
|
|
2418
|
+
ambiguous: 'more than one row matches',
|
|
2419
|
+
no_pattern: 'the row has no selection pattern',
|
|
2420
|
+
refused: 'the program refused the selection',
|
|
2421
|
+
}
|
|
2422
|
+
|
|
2423
|
+
/** 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). */
|
|
2424
|
+
export function judgeSelect(_before: UiRefFacts, after: UiRefFacts | undefined): UiActResult {
|
|
2425
|
+
if (after?.selected === true)
|
|
2426
|
+
return {
|
|
2427
|
+
ok: true,
|
|
2428
|
+
delivery: 'delivered_verified',
|
|
2429
|
+
retrySafety: 'unsafe',
|
|
2430
|
+
readBack: { expected: 'selected', observed: 'selected' },
|
|
2431
|
+
}
|
|
2432
|
+
return {
|
|
2433
|
+
ok: true,
|
|
2434
|
+
delivery: 'delivered_unverified',
|
|
2435
|
+
retrySafety: 'unsafe',
|
|
2436
|
+
...(after ? { readBack: { expected: 'selected', observed: 'not selected' } } : {}),
|
|
2437
|
+
detail: `the click was sent, but the control does not read as selected${after ? '' : ' (it could not be read back)'}.`,
|
|
2438
|
+
}
|
|
863
2439
|
}
|
|
864
2440
|
|
|
865
2441
|
/** `0x…` hex, the form `bring_to_front` reports and `WindowInfo.id` carries. */
|