@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.
Files changed (121) hide show
  1. package/CHANGELOG.md +58 -1
  2. package/dist/SubprocessComputerUseHost.d.ts +57 -9
  3. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  4. package/dist/SubprocessComputerUseHost.js +213 -46
  5. package/dist/SubprocessComputerUseHost.js.map +1 -1
  6. package/dist/adapters/cua-driver/adapter.d.ts +171 -10
  7. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  8. package/dist/adapters/cua-driver/adapter.js +1476 -161
  9. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  10. package/dist/adapters/cua-driver/client.d.ts +16 -0
  11. package/dist/adapters/cua-driver/client.d.ts.map +1 -1
  12. package/dist/adapters/cua-driver/client.js +54 -5
  13. package/dist/adapters/cua-driver/client.js.map +1 -1
  14. package/dist/adapters/cua-driver/escalation.d.ts +67 -0
  15. package/dist/adapters/cua-driver/escalation.d.ts.map +1 -0
  16. package/dist/adapters/cua-driver/escalation.js +82 -0
  17. package/dist/adapters/cua-driver/escalation.js.map +1 -0
  18. package/dist/adapters/cua-driver/keys.d.ts +5 -0
  19. package/dist/adapters/cua-driver/keys.d.ts.map +1 -1
  20. package/dist/adapters/cua-driver/keys.js +23 -0
  21. package/dist/adapters/cua-driver/keys.js.map +1 -1
  22. package/dist/adapters/cua-driver/observe.d.ts +99 -0
  23. package/dist/adapters/cua-driver/observe.d.ts.map +1 -0
  24. package/dist/adapters/cua-driver/observe.js +227 -0
  25. package/dist/adapters/cua-driver/observe.js.map +1 -0
  26. package/dist/adapters/cua-driver/ui-tree.d.ts +75 -2
  27. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  28. package/dist/adapters/cua-driver/ui-tree.js +142 -14
  29. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  30. package/dist/adapters/types.d.ts +3 -3
  31. package/dist/adapters/types.d.ts.map +1 -1
  32. package/dist/adapters/types.js.map +1 -1
  33. package/dist/adapters/win32.d.ts +10 -0
  34. package/dist/adapters/win32.d.ts.map +1 -1
  35. package/dist/adapters/win32.js +12 -2
  36. package/dist/adapters/win32.js.map +1 -1
  37. package/dist/errors.d.ts +19 -0
  38. package/dist/errors.d.ts.map +1 -1
  39. package/dist/errors.js +26 -0
  40. package/dist/errors.js.map +1 -1
  41. package/dist/foreground/guard.d.ts +31 -0
  42. package/dist/foreground/guard.d.ts.map +1 -0
  43. package/dist/foreground/guard.js +156 -0
  44. package/dist/foreground/guard.js.map +1 -0
  45. package/dist/foreground/index.d.ts +11 -0
  46. package/dist/foreground/index.d.ts.map +1 -0
  47. package/dist/foreground/index.js +7 -0
  48. package/dist/foreground/index.js.map +1 -0
  49. package/dist/foreground/ladder.d.ts +143 -0
  50. package/dist/foreground/ladder.d.ts.map +1 -0
  51. package/dist/foreground/ladder.js +505 -0
  52. package/dist/foreground/ladder.js.map +1 -0
  53. package/dist/foreground/lease.d.ts +69 -0
  54. package/dist/foreground/lease.d.ts.map +1 -0
  55. package/dist/foreground/lease.js +182 -0
  56. package/dist/foreground/lease.js.map +1 -0
  57. package/dist/foreground/types.d.ts +287 -0
  58. package/dist/foreground/types.d.ts.map +1 -0
  59. package/dist/foreground/types.js +32 -0
  60. package/dist/foreground/types.js.map +1 -0
  61. package/dist/foreground/windows-helper-script.d.ts +19 -0
  62. package/dist/foreground/windows-helper-script.d.ts.map +1 -0
  63. package/dist/foreground/windows-helper-script.js +472 -0
  64. package/dist/foreground/windows-helper-script.js.map +1 -0
  65. package/dist/foreground/windows-monitor.d.ts +75 -0
  66. package/dist/foreground/windows-monitor.d.ts.map +1 -0
  67. package/dist/foreground/windows-monitor.js +216 -0
  68. package/dist/foreground/windows-monitor.js.map +1 -0
  69. package/dist/foreground/windows.d.ts +21 -0
  70. package/dist/foreground/windows.d.ts.map +1 -0
  71. package/dist/foreground/windows.js +54 -0
  72. package/dist/foreground/windows.js.map +1 -0
  73. package/dist/index.d.ts +6 -1
  74. package/dist/index.d.ts.map +1 -1
  75. package/dist/index.js +3 -1
  76. package/dist/index.js.map +1 -1
  77. package/dist/presence/helper-script.d.ts +39 -0
  78. package/dist/presence/helper-script.d.ts.map +1 -0
  79. package/dist/presence/helper-script.js +320 -0
  80. package/dist/presence/helper-script.js.map +1 -0
  81. package/dist/presence/index.d.ts +6 -0
  82. package/dist/presence/index.d.ts.map +1 -0
  83. package/dist/presence/index.js +4 -0
  84. package/dist/presence/index.js.map +1 -0
  85. package/dist/presence/presence.d.ts +70 -0
  86. package/dist/presence/presence.d.ts.map +1 -0
  87. package/dist/presence/presence.js +147 -0
  88. package/dist/presence/presence.js.map +1 -0
  89. package/dist/presence/windows.d.ts +19 -0
  90. package/dist/presence/windows.d.ts.map +1 -0
  91. package/dist/presence/windows.js +39 -0
  92. package/dist/presence/windows.js.map +1 -0
  93. package/dist/util/call-scope.d.ts +34 -0
  94. package/dist/util/call-scope.d.ts.map +1 -0
  95. package/dist/util/call-scope.js +58 -0
  96. package/dist/util/call-scope.js.map +1 -0
  97. package/package.json +2 -2
  98. package/src/SubprocessComputerUseHost.ts +287 -45
  99. package/src/adapters/cua-driver/adapter.ts +1751 -175
  100. package/src/adapters/cua-driver/client.ts +59 -2
  101. package/src/adapters/cua-driver/escalation.ts +137 -0
  102. package/src/adapters/cua-driver/keys.ts +20 -0
  103. package/src/adapters/cua-driver/observe.ts +310 -0
  104. package/src/adapters/cua-driver/ui-tree.ts +219 -15
  105. package/src/adapters/types.ts +7 -2
  106. package/src/adapters/win32.ts +26 -3
  107. package/src/errors.ts +32 -0
  108. package/src/foreground/guard.ts +182 -0
  109. package/src/foreground/index.ts +45 -0
  110. package/src/foreground/ladder.ts +616 -0
  111. package/src/foreground/lease.ts +232 -0
  112. package/src/foreground/types.ts +318 -0
  113. package/src/foreground/windows-helper-script.ts +471 -0
  114. package/src/foreground/windows-monitor.ts +288 -0
  115. package/src/foreground/windows.ts +73 -0
  116. package/src/index.ts +15 -1
  117. package/src/presence/helper-script.ts +323 -0
  118. package/src/presence/index.ts +17 -0
  119. package/src/presence/presence.ts +195 -0
  120. package/src/presence/windows.ts +54 -0
  121. package/src/util/call-scope.ts +73 -0
@@ -1,31 +1,202 @@
1
1
  import { randomUUID } from 'node:crypto';
2
+ import { droppedInputNote, foregroundNote, interferenceNote } from '../../foreground/guard.js';
3
+ import { BurstInterrupted } from '../../foreground/types.js';
4
+ import { CallAbortedError, currentCallSignal, markSent } from '../../util/call-scope.js';
2
5
  import { McpStdioClient, McpToolError, } from './client.js';
3
- import { translateKeyForCuaDriver } from './keys.js';
4
- import { toUiTree } from './ui-tree.js';
6
+ import { canBeJudgedByStillness, escalationDetail, judgeStillness, shouldRetryOnScreen, } from './escalation.js';
7
+ import { menuAcceleratorOf, translateKeyForCuaDriver } from './keys.js';
8
+ import { judgeEdit, judgeEditBetween, judgeObserved, observationOf, sameObservation, } from './observe.js';
9
+ import { locate, toUiTree, } from './ui-tree.js';
5
10
  const CAPTURE_TIMEOUT_MS = 30_000;
6
11
  const LIST_TIMEOUT_MS = 20_000;
7
12
  /** A browser window's tree takes 2–3 s; a huge one is cut by `UI_MAX_ELEMENTS` first. */
8
13
  const UI_TREE_TIMEOUT_MS = 30_000;
9
- /** The most controls one snapshot walks. The SDK shows the model at most ~14 000 characters of it. */
10
- const UI_MAX_ELEMENTS = 1_500;
14
+ /** The most nodes one read walks. The model is shown an outline of a large one, never all of it. */
15
+ const UI_MAX_ELEMENTS = 5_000;
16
+ /**
17
+ * The driver cuts a walk at its cap without saying so (the answer carries no
18
+ * flag), so a walk this close to the cap is treated as cut.
19
+ */
20
+ const UI_WALK_CUT_AT = Math.floor(UI_MAX_ELEMENTS * 0.95);
21
+ /** A window with more shown controls than this is returned as an outline. */
22
+ const OUTLINE_THRESHOLD = 220;
23
+ /** The most controls an outline shows; the rest are counted, not listed. */
24
+ const OUTLINE_BUDGET = 150;
25
+ /** The most children of one element an outline lists; a long list is opened as a region. */
26
+ const OUTLINE_PER_PARENT = 12;
27
+ /** The children of a region opened by itself that one page lists. */
28
+ const OUTLINE_PAGE = 60;
29
+ /** A browser tree this small is the window frame alone: the page has not been built yet. */
30
+ const SPARSE_TREE = 12;
31
+ /** Controls that offer a choice among options, which the keyboard can make when the driver cannot. */
32
+ const CHOICE_ROLES = /^(ComboBox|List|ListBox)$/i;
33
+ /** Waits (ms) before each read that looks for an input's effect: at once, then a little later. */
34
+ const OBSERVE_WAITS_MS = [0, 80, 200, 450];
35
+ /** How many times a burst that a person's input stopped before anything was sent waits for the next pause and goes again. */
36
+ const PAUSE_RETRIES = 3;
37
+ const BROWSER_APP = /chrome|msedge|edge|brave|vivaldi|opera|firefox|chromium/i;
38
+ /**
39
+ * A ref read longer ago than this is checked against a new read before it
40
+ * is acted on. Within it, the driver's own handle check (it refuses a handle
41
+ * a newer read of the window replaced) guards the write.
42
+ */
43
+ /** Driver tools that only read; every other tool may change the desktop. */
44
+ const READ_ONLY_TOOL = /^(get_|list_|start_session|set_agent_cursor|check_|describe)/;
45
+ /** Whether a driver tool call can change the desktop (so a lost one is an unknown outcome). */
46
+ export function changesDesktop(tool) {
47
+ return !READ_ONLY_TOOL.test(tool);
48
+ }
49
+ const IDENTITY_FRESH_MS = 3_000;
50
+ /** Refs the adapter keeps; the model is shown far fewer. */
51
+ const MAX_REFS = 4_000;
52
+ /** The most refs one read creates; a quarter of the budget, so one read cannot evict the rest. */
53
+ const NEW_REFS_PER_READ = 1_000;
11
54
  /** cua-driver refuses more than 50 ticks in one scroll call. */
12
55
  const MAX_SCROLL_TICKS = 50;
13
56
  /** A drag glides through intermediate moves; many targets ignore one that teleports. */
14
57
  const DRAG = { durationMs: 250, steps: 12 };
58
+ /**
59
+ * Switches the driver's own animated cursor off for the session (Namzu draws
60
+ * its own, and two cursors are never shown). The driver keeps an empty,
61
+ * fully transparent, click-through overlay window either way; with the cursor off it draws nothing into it. Returns whether
62
+ * the driver confirmed it: a build without the tool still works, only slower,
63
+ * and then Namzu shows no cursor of its own (see `tryPresence`).
64
+ */
15
65
  async function disableAgentCursor(call) {
16
- // Best effort: a build without the tool still works, only slower.
17
- await call('set_agent_cursor_enabled', { enabled: false }).catch(() => undefined);
66
+ try {
67
+ const result = await call('set_agent_cursor_enabled', { enabled: false });
68
+ return result.structuredContent?.enabled === false;
69
+ }
70
+ catch {
71
+ return false;
72
+ }
18
73
  }
19
- /** Replace process-local driver tokens before any UI tree leaves this adapter. */
20
- function withOpaqueRefs(element, refFor) {
21
- return Object.freeze({
22
- ...element,
23
- ref: element.ref ? refFor(element.ref) : '',
24
- ...(element.children
25
- ? {
26
- children: Object.freeze(element.children.map((child) => withOpaqueRefs(child, refFor))),
74
+ const pathKey = (path) => path.join('.');
75
+ /** Evidence as words, for a message: `Button "Save"`. App text, so cut and without quotes or line breaks. */
76
+ function describeEvidence(evidence) {
77
+ const name = evidence.name.replace(/["\r\n]+/g, ' ').trim();
78
+ const role = /^[A-Za-z][\w-]{0,39}$/.test(evidence.role) ? evidence.role : 'Element';
79
+ return name ? `${role} "${name.length > 60 ? `${name.slice(0, 59)}…` : name}"` : role;
80
+ }
81
+ /** How many controls fit a ref; one means it was one of several identical controls and the window has changed since. */
82
+ function fitText(count) {
83
+ return count > 1
84
+ ? `${count} controls fit`
85
+ : 'the window changed and which of several identical controls it was cannot be told for';
86
+ }
87
+ function refFailure(code, detail) {
88
+ return {
89
+ ok: false,
90
+ delivery: 'not_delivered',
91
+ retrySafety: 'safe',
92
+ code,
93
+ detail,
94
+ };
95
+ }
96
+ function factsOfNode(node) {
97
+ return {
98
+ role: node.role,
99
+ name: node.name,
100
+ ...(node.automationId !== undefined ? { automationId: node.automationId } : {}),
101
+ selected: false,
102
+ actions: [],
103
+ path: node.path,
104
+ };
105
+ }
106
+ /** Whether the model would be shown this element: a nameless control nobody can act on is passed through. */
107
+ function isSilent(element) {
108
+ return element.ref === '' && element.name.trim().length === 0 && element.value === undefined;
109
+ }
110
+ function visibleCount(element) {
111
+ let count = isSilent(element) ? 0 : 1;
112
+ for (const child of element.children ?? [])
113
+ count += visibleCount(child);
114
+ return count;
115
+ }
116
+ /**
117
+ * The top of a big tree: breadth first, shallow levels before deep ones, so
118
+ * the whole window's layout is shown before any one region's detail. What is
119
+ * left out is counted on the element that holds it, and that element is a
120
+ * region the model can open.
121
+ */
122
+ function outlineOf(root, basePath, budget, page) {
123
+ const keep = new Set([root]);
124
+ const queue = [root];
125
+ let used = isSilent(root) ? 0 : 1;
126
+ let next;
127
+ while (queue.length > 0) {
128
+ const element = queue.shift();
129
+ const isRoot = element === root;
130
+ // A region opened by itself lists a page of its own children; the page
131
+ // after it is asked for with the offset it reports.
132
+ const children = element.children ?? [];
133
+ const first = isRoot && page ? Math.min(page.offset, children.length) : 0;
134
+ const cap = isRoot && page ? OUTLINE_PAGE : OUTLINE_PER_PARENT;
135
+ let listed = 0;
136
+ let cut = false;
137
+ for (let index = first; index < children.length; index++) {
138
+ const child = children[index];
139
+ const cost = isSilent(child) ? 0 : 1;
140
+ // One long list must not use the budget its siblings' regions need.
141
+ // Once the list is cut, nothing after the cut is listed, nameless or
142
+ // not: the next page begins at the cut and would repeat it.
143
+ if (cut || used + cost > budget || listed + cost > cap || keep.size > budget * 4) {
144
+ cut = true;
145
+ if (isRoot && page && next === undefined)
146
+ next = index;
147
+ continue;
27
148
  }
28
- : {}),
149
+ used += cost;
150
+ listed += cost;
151
+ keep.add(child);
152
+ queue.push(child);
153
+ }
154
+ }
155
+ const regions = new Set();
156
+ const build = (element, path) => {
157
+ const children = element.children ?? [];
158
+ const kept = [];
159
+ children.forEach((child, index) => {
160
+ if (!keep.has(child))
161
+ return;
162
+ const built = build(child, [...path, index]);
163
+ ORIGINAL_INDEX.set(built, index);
164
+ kept.push(built);
165
+ });
166
+ const hidden = children.length - kept.length;
167
+ if (hidden > 0)
168
+ regions.add(pathKey(path));
169
+ const { children: _children, ...rest } = element;
170
+ return Object.freeze({
171
+ ...rest,
172
+ ...(kept.length > 0 ? { children: Object.freeze(kept) } : {}),
173
+ ...(hidden > 0 ? { hiddenChildren: hidden } : {}),
174
+ });
175
+ };
176
+ return { root: build(root, basePath), regions, next };
177
+ }
178
+ /** The paths of the elements a view contains. */
179
+ function collectShown(element, path, into) {
180
+ into.add(pathKey(path));
181
+ const children = element.children ?? [];
182
+ // A pruned view lists the kept children in order, but their indexes in the
183
+ // full tree are not 0..n; the view carries them by identity (see withRefs).
184
+ children.forEach((child, index) => {
185
+ collectShown(child, [...path, pathIndex(element, child, index)], into);
186
+ });
187
+ }
188
+ const ORIGINAL_INDEX = new WeakMap();
189
+ function pathIndex(_parent, child, fallback) {
190
+ return ORIGINAL_INDEX.get(child) ?? fallback;
191
+ }
192
+ /** The elements of a view with the adapter's refs in place of driver handles. */
193
+ function withRefs(element, path, refAt) {
194
+ const children = (element.children ?? []).map((child, index) => withRefs(child, [...path, pathIndex(element, child, index)], refAt));
195
+ const { children: _children, ...rest } = element;
196
+ return Object.freeze({
197
+ ...rest,
198
+ ref: refAt(path),
199
+ ...(children.length > 0 ? { children: Object.freeze(children) } : {}),
29
200
  });
30
201
  }
31
202
  export class CuaDriverAdapter {
@@ -34,20 +205,35 @@ export class CuaDriverAdapter {
34
205
  client;
35
206
  /** Window id → owning pid, from the latest list; `bring_to_front` needs both. */
36
207
  windowPids = new Map();
208
+ /** Window id → application name, for naming the program a foreground burst is for. */
209
+ windowApps = new Map();
210
+ foreground;
211
+ presence;
212
+ /** False once the driver would not switch its own cursor off: Namzu's is then not shown, so there is never a second one. */
213
+ driverCursorOff;
37
214
  /** cua-driver's screenshot resize registry is per PID, so only this capture may drive input. */
38
215
  windowFrame;
39
216
  /** Capture and scoped input must not race over cua-driver's per-PID resize ratio. */
40
217
  windowOperation = Promise.resolve();
41
- /** Only refs from the latest snapshot may address driver tokens. */
218
+ /** 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. */
42
219
  uiRefs = new Map();
220
+ /** Per window: the latest read of its tree, which is the only one its driver handles belong to. */
221
+ windowReads = new Map();
43
222
  uiRefNamespace = randomUUID();
44
- nextSnapshot = 0;
223
+ nextRead = 0;
224
+ nextRef = 0;
225
+ now;
226
+ settle;
45
227
  /** A successful revival invalidates refusals from the previous lifecycle episode. */
46
228
  sessionGeneration = 0;
47
229
  /** Share one revival among calls refused by the same expired implicit session. */
48
230
  sessionRevival;
49
231
  constructor(options) {
50
232
  this.backend = `cua-driver${options.version ? ` ${options.version}` : ''}`;
233
+ this.foreground = options.foreground;
234
+ this.presence = options.presence;
235
+ this.now = options.now ?? Date.now;
236
+ this.settle = options.settle ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
51
237
  this.client = new McpStdioClient({
52
238
  command: options.executable,
53
239
  args: ['mcp'],
@@ -57,7 +243,9 @@ export class CuaDriverAdapter {
57
243
  requestTimeoutMs: options.requestTimeoutMs ?? 15_000,
58
244
  startTimeoutMs: options.startTimeoutMs ?? 30_000,
59
245
  spawnProcess: options.spawnProcess,
60
- afterStart: disableAgentCursor,
246
+ afterStart: async (call) => {
247
+ this.driverCursorOff = await disableAgentCursor(call);
248
+ },
61
249
  });
62
250
  this.capabilities = Object.freeze({
63
251
  displayServer: 'win32',
@@ -122,15 +310,14 @@ export class CuaDriverAdapter {
122
310
  });
123
311
  return { type: 'ok' };
124
312
  case 'mouse_click':
125
- await this.pointer('click', {
313
+ return this.pointer('click', {
126
314
  scope: 'desktop',
127
315
  x: action.at.x,
128
316
  y: action.at.y,
129
317
  button: action.button,
130
318
  });
131
- return { type: 'ok' };
132
319
  case 'mouse_drag':
133
- await this.pointer('drag', {
320
+ return this.pointer('drag', {
134
321
  scope: 'desktop',
135
322
  from_x: action.from.x,
136
323
  from_y: action.from.y,
@@ -140,12 +327,12 @@ export class CuaDriverAdapter {
140
327
  duration_ms: DRAG.durationMs,
141
328
  steps: DRAG.steps,
142
329
  });
143
- return { type: 'ok' };
144
330
  case 'scroll': {
145
331
  let remaining = Math.max(1, Math.trunc(action.amount));
332
+ let last = { type: 'ok' };
146
333
  while (remaining > 0) {
147
334
  const ticks = Math.min(remaining, MAX_SCROLL_TICKS);
148
- await this.pointer('scroll', {
335
+ last = await this.pointer('scroll', {
149
336
  scope: 'desktop',
150
337
  x: action.at.x,
151
338
  y: action.at.y,
@@ -154,43 +341,45 @@ export class CuaDriverAdapter {
154
341
  });
155
342
  remaining -= ticks;
156
343
  }
157
- return { type: 'ok' };
344
+ return last;
158
345
  }
159
346
  case 'type_text':
160
- if (action.text.length > 0) {
161
- await this.callTool('type_text', {
162
- scope: 'desktop',
163
- text: action.text,
164
- });
165
- }
166
- return { type: 'ok' };
347
+ if (action.text.length === 0)
348
+ return { type: 'ok' };
349
+ return this.keyboard('type_text', {
350
+ scope: 'desktop',
351
+ text: action.text,
352
+ });
167
353
  case 'key': {
168
354
  const plan = translateKeyForCuaDriver(action.keys);
169
- if (plan.tool === 'type_text') {
170
- await this.callTool('type_text', {
355
+ if (plan.tool === 'type_text')
356
+ return this.keyboard('type_text', {
171
357
  scope: 'desktop',
172
358
  text: plan.text,
173
359
  });
174
- }
175
- else if (plan.tool === 'press_key') {
176
- await this.callTool('press_key', { scope: 'desktop', key: plan.key });
177
- }
178
- else {
179
- await this.callTool('hotkey', {
360
+ if (plan.tool === 'press_key')
361
+ return this.keyboard('press_key', {
180
362
  scope: 'desktop',
181
- keys: [...plan.keys],
363
+ key: plan.key,
182
364
  });
183
- }
184
- return { type: 'ok' };
365
+ return this.keyboard('hotkey', {
366
+ scope: 'desktop',
367
+ keys: [...plan.keys],
368
+ });
185
369
  }
186
370
  }
187
371
  }
188
372
  async listWindows() {
373
+ // The model is about to work in a window: have the overlay ready for its first action.
374
+ this.tryPresence((presence) => presence.warm());
189
375
  const listed = structured(await this.callTool('list_windows', {}, LIST_TIMEOUT_MS), 'list_windows');
190
376
  const windows = toWindowInfos(listed.windows);
191
377
  this.windowPids.clear();
192
- for (const window of windows)
378
+ this.windowApps.clear();
379
+ for (const window of windows) {
193
380
  this.windowPids.set(window.id, window.pid);
381
+ this.windowApps.set(window.id, window.app);
382
+ }
194
383
  return windows;
195
384
  }
196
385
  async focusWindow(id) {
@@ -290,7 +479,224 @@ export class CuaDriverAdapter {
290
479
  async executeWindow(captureId, action) {
291
480
  return this.serializeWindowOperation(() => this.executeWindowInternal(captureId, action));
292
481
  }
482
+ /**
483
+ * One window input, then a check of what the window shows. The driver
484
+ * cannot confirm a background input, so one it left unconfirmed is judged
485
+ * by reading the window before and after (see `observe.ts`).
486
+ *
487
+ * An input that provably had no effect (the window did not change at all)
488
+ * is sent once more, on the screen through the foreground ladder, and
489
+ * judged again; one that changed the window in a way that cannot be tied to
490
+ * it is never sent twice (see `escalation.ts`).
491
+ */
293
492
  async executeWindowInternal(captureId, action) {
493
+ const first = { foreground: false, onScreen: false };
494
+ const result = await this.attemptWindowInput(captureId, action, first);
495
+ if (!result || !canBeJudgedByStillness(action))
496
+ return result;
497
+ const summary = {
498
+ delivery: result.delivery,
499
+ retrySafety: result.retrySafety,
500
+ ...(result.detail !== undefined ? { detail: result.detail } : {}),
501
+ ...(first.outcome ? { outcome: first.outcome } : {}),
502
+ onScreen: first.onScreen,
503
+ };
504
+ const explicit = 'delivery_mode' in action ? action.delivery_mode : undefined;
505
+ if (!shouldRetryOnScreen(summary, {
506
+ hasScreen: this.foreground !== undefined,
507
+ explicitMode: explicit,
508
+ }))
509
+ return result;
510
+ // The retry is made once; its answer is final.
511
+ const second = { foreground: true, onScreen: false };
512
+ const again = await this.attemptWindowInput(captureId, action, second);
513
+ if (!again)
514
+ return result;
515
+ const finalDetail = escalationDetail({
516
+ delivery: again.delivery,
517
+ retrySafety: again.retrySafety,
518
+ ...(again.detail !== undefined ? { detail: again.detail } : {}),
519
+ ...(second.outcome ? { outcome: second.outcome } : {}),
520
+ onScreen: second.onScreen,
521
+ ...(second.blocked !== undefined ? { blocked: second.blocked } : {}),
522
+ });
523
+ if (again.delivery === 'delivered_verified')
524
+ return { ...again, detail: [finalDetail, again.detail].filter(Boolean).join(' ') };
525
+ return { ...again, detail: finalDetail };
526
+ }
527
+ async attemptWindowInput(captureId, action, route) {
528
+ const frame = this.windowFrame;
529
+ const watched = action.type === 'type_text' || action.type === 'key' || action.type === 'mouse_click';
530
+ const hwnd = frame && frame.id === captureId ? parseWindowId(frame.window.id) : undefined;
531
+ const target = hwnd !== undefined && frame ? { hwnd, pid: frame.window.pid } : undefined;
532
+ const typed = action.type === 'type_text'
533
+ ? action.text
534
+ : action.type === 'key' && translateKeyForCuaDriver(action.keys).tool === 'type_text'
535
+ ? translateKeyForCuaDriver(action.keys).text
536
+ : undefined;
537
+ // Text for a classic edit control goes by window message: it needs neither focus nor the screen.
538
+ if (action.type === 'type_text' &&
539
+ action.text.length > 0 &&
540
+ frame &&
541
+ target &&
542
+ action.delivery_mode !== 'foreground' &&
543
+ !route.foreground) {
544
+ const byMessage = await this.typeByMessages(frame, action.text);
545
+ if (byMessage)
546
+ return byMessage;
547
+ }
548
+ // A keyboard delivery that asked for the screen is judged by the edit control's own text, where there is one.
549
+ const editBefore = typed !== undefined && frame && target && this.foreground
550
+ ? await this.foreground.editText({
551
+ hwnd: frame.window.id,
552
+ op: 'get',
553
+ pick: 'focus',
554
+ })
555
+ : undefined;
556
+ let before;
557
+ let earlier;
558
+ let windows;
559
+ if (watched && target) {
560
+ // A press or a key has no text to look for, so it is attributed only if the window was still before it.
561
+ if (typed === undefined)
562
+ earlier = await this.observe(target);
563
+ before = await this.observe(target);
564
+ // A new window of the program is an effect of a press and the sign of one for a text.
565
+ windows = await this.windowIdsOf(target.pid);
566
+ }
567
+ // A shortcut that stands for a command of the window's classic menu is that command, sent as the message
568
+ // the menu item sends: no key is pressed and the screen is not used.
569
+ const byMenu = action.type === 'key' &&
570
+ frame &&
571
+ target &&
572
+ action.delivery_mode !== 'foreground' &&
573
+ !route.foreground
574
+ ? await this.shortcutByMenu(frame, action.keys)
575
+ : undefined;
576
+ const sent = byMenu ?? (await this.deliverWindowInput(captureId, action, route));
577
+ let edit;
578
+ if (sent?.delivery === 'delivered_unverified' &&
579
+ editBefore?.found &&
580
+ typed !== undefined &&
581
+ frame) {
582
+ const editAfter = await this.foreground?.editText({
583
+ hwnd: frame.window.id,
584
+ op: 'get',
585
+ pick: 'focus',
586
+ });
587
+ const verdict = editAfter?.found ? judgeEditBetween(typed, editBefore, editAfter) : undefined;
588
+ if (verdict)
589
+ return {
590
+ delivery: verdict.delivery,
591
+ retrySafety: verdict.retrySafety,
592
+ detail: verdict.detail,
593
+ ...(verdict.observed !== undefined ? { readBack: { observed: verdict.observed } } : {}),
594
+ };
595
+ edit = !editAfter?.found
596
+ ? 'unknown'
597
+ : editAfter.len === editBefore.len && editAfter.text === editBefore.text
598
+ ? 'unchanged'
599
+ : 'changed';
600
+ }
601
+ if (!sent || sent.delivery !== 'delivered_unverified' || !target || !before)
602
+ return sent;
603
+ const seen = await this.verifyByReading(target, {
604
+ typed,
605
+ before,
606
+ earlier,
607
+ windows,
608
+ edit,
609
+ // 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.
610
+ stillness: byMenu === undefined && canBeJudgedByStillness(action),
611
+ });
612
+ if (!seen)
613
+ return sent;
614
+ // A person at the keyboard or mouse during a burst can change the window: it proves nothing.
615
+ if (seen.outcome && route.interfered)
616
+ return sent;
617
+ if (seen.outcome)
618
+ route.outcome = seen.outcome;
619
+ return {
620
+ delivery: seen.delivery,
621
+ retrySafety: seen.retrySafety,
622
+ detail: seen.outcome ? [seen.detail, sent.detail].filter(Boolean).join(' ') : seen.detail,
623
+ ...(seen.observed !== undefined ? { readBack: { observed: seen.observed } } : {}),
624
+ };
625
+ }
626
+ /**
627
+ * Read the window again until it shows an effect of the input, a few
628
+ * times with a short wait between (the effect of an input arrives after it
629
+ * returns), then once more to see that it held still.
630
+ */
631
+ async verifyByReading(target, reads) {
632
+ const afters = [];
633
+ for (const wait of OBSERVE_WAITS_MS) {
634
+ if (wait > 0)
635
+ await this.settle(wait);
636
+ const opened = reads.windows ? await this.newWindowOf(target.pid, reads.windows) : undefined;
637
+ if (opened)
638
+ return {
639
+ delivery: 'delivered_verified',
640
+ retrySafety: 'unsafe',
641
+ ...(opened.title.trim() !== '' ? { observed: opened.title.trim() } : {}),
642
+ detail: 'A new window of the same program opened after the input.',
643
+ };
644
+ const after = await this.observe(target);
645
+ if (!after)
646
+ return undefined;
647
+ afters.push(after);
648
+ if (sameObservation(reads.before, after))
649
+ continue;
650
+ const later = reads.typed === undefined ? await this.observe(target) : undefined;
651
+ const verdict = judgeObserved(reads.typed !== undefined ? { typed: reads.typed } : {}, {
652
+ before: reads.before,
653
+ after,
654
+ ...(later ? { later } : {}),
655
+ ...(reads.earlier ? { earlier: reads.earlier } : {}),
656
+ });
657
+ if (verdict)
658
+ return verdict;
659
+ }
660
+ if (!reads.stillness)
661
+ return undefined;
662
+ return judgeStillness({
663
+ before: reads.before,
664
+ ...(reads.earlier ? { earlier: reads.earlier } : {}),
665
+ afters,
666
+ opened: false,
667
+ ...(reads.edit ? { edit: reads.edit } : {}),
668
+ });
669
+ }
670
+ async windowIdsOf(pid) {
671
+ try {
672
+ return new Set((await this.listWindows()).filter((w) => w.pid === pid).map((w) => w.id));
673
+ }
674
+ catch {
675
+ return undefined;
676
+ }
677
+ }
678
+ async newWindowOf(pid, known) {
679
+ try {
680
+ return (await this.listWindows()).find((w) => w.pid === pid && !known.has(w.id));
681
+ }
682
+ catch {
683
+ return undefined;
684
+ }
685
+ }
686
+ /** 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. */
687
+ async observe(target) {
688
+ try {
689
+ const read = await this.readWindowTree(target, {});
690
+ this.bindRead(target, read, { shown: new Set(), regions: new Set() });
691
+ return observationOf(read.tree, {
692
+ walkCut: read.state.truncated === true || read.tree.count >= UI_WALK_CUT_AT,
693
+ });
694
+ }
695
+ catch {
696
+ return undefined;
697
+ }
698
+ }
699
+ async deliverWindowInput(captureId, action, route = { foreground: false, onScreen: false }) {
294
700
  const frame = this.windowFrame;
295
701
  if (!frame || frame.id !== captureId)
296
702
  throw new Error('computer-use: this window screenshot is stale; capture the window again before acting.');
@@ -325,21 +731,124 @@ export class CuaDriverAdapter {
325
731
  this.sessionGeneration !== frame.generation ||
326
732
  this.client.starts !== frame.processStarts)
327
733
  throw new Error('computer-use: the captured window changed or its driver restarted; take a new window screenshot.');
328
- await this.callTool(name, { ...target, ...args }, undefined, undefined, undefined, frame);
734
+ this.showPresence(frame, current.bounds, name, args);
735
+ return this.callTool(name, { ...target, ...args }, undefined, undefined, undefined, frame);
329
736
  };
330
- switch (action.type) {
331
- case 'mouse_click':
332
- try {
333
- await call('click', { x: action.at.x, y: action.at.y, button: action.button });
737
+ // The driver's hotkey finds a shortcut only through an accelerator the window names, and refuses (sending
738
+ // nothing) when there is none; the same combination as a key with modifiers is real input.
739
+ const dispatch = async (name, args) => {
740
+ try {
741
+ return await call(name, args);
742
+ }
743
+ catch (error) {
744
+ const keys = args.keys;
745
+ if (name === 'hotkey' &&
746
+ Array.isArray(keys) &&
747
+ keys.length > 1 &&
748
+ error instanceof McpToolError &&
749
+ /AcceleratorKey/i.test(error.message)) {
750
+ const { keys: _keys, ...rest } = args;
751
+ return await call('press_key', {
752
+ ...rest,
753
+ key: keys[keys.length - 1],
754
+ modifiers: keys.slice(0, -1),
755
+ });
756
+ }
757
+ throw error;
758
+ }
759
+ };
760
+ // One window input: in the background first. A refusal that foreground
761
+ // delivery can cure (the window cannot take background input, or it is
762
+ // covered) is retried through the ladder; an explicit foreground request
763
+ // goes through it too. The result says which happened.
764
+ const send = async (name, args) => {
765
+ const subject = {
766
+ app: this.windowApps.get(frame.window.id) ?? frame.window.app,
767
+ pid: frame.window.pid,
768
+ hwnd: frame.window.id,
769
+ };
770
+ const inForeground = async (why, tries = 0) => {
771
+ const ladder = this.foreground;
772
+ const outcome = await ladder
773
+ .run(this.burstRequest(subject, true), async (burst) => {
774
+ await burst.checkpoint();
775
+ try {
776
+ return inputDelivery(await dispatch(name, { ...args, delivery_mode: 'foreground' }));
777
+ }
778
+ catch (error) {
779
+ if (isDeliveredPointerAction(error))
780
+ return foregroundLostDelivery();
781
+ if (error instanceof McpToolError)
782
+ return failureDelivery(error);
783
+ throw error;
784
+ }
785
+ })
786
+ .catch((error) => {
787
+ if (error instanceof BurstInterrupted)
788
+ return error;
789
+ throw error;
790
+ });
791
+ // A person's input just before the send stopped the burst with nothing sent: the next pause is waited
792
+ // for by the ladder's own gate, and the input goes then. Bounded; after it the result says so.
793
+ if (outcome instanceof BurstInterrupted &&
794
+ outcome.reason === 'person' &&
795
+ tries < PAUSE_RETRIES)
796
+ return inForeground(why, tries + 1);
797
+ if (outcome instanceof BurstInterrupted) {
798
+ route.blocked = outcome.reason === 'person' ? 'user_active' : 'elevated_target';
799
+ return verdict('not_delivered', 'safe', outcome.reason === 'person'
800
+ ? 'a person used the keyboard or mouse just before the input was sent, so nothing was sent. Try again in a moment.'
801
+ : '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.');
334
802
  }
335
- catch (error) {
336
- if (!isDeliveredPointerAction(error))
337
- throw windowPointerRefusal(error);
803
+ if (outcome.kind === 'blocked') {
804
+ route.blocked = outcome.block.code;
805
+ return verdict('not_delivered', 'safe', outcome.block.detail);
338
806
  }
339
- return;
340
- case 'mouse_drag':
341
- try {
342
- await call('drag', {
807
+ route.onScreen = true;
808
+ const dropped = droppedInputNote(outcome);
809
+ if (dropped)
810
+ return verdict('not_delivered', 'safe', dropped);
811
+ const note = interferenceNote(outcome);
812
+ const base = outcome.value;
813
+ if (note)
814
+ route.interfered = true;
815
+ if (note)
816
+ return verdict(base.delivery === 'not_delivered' ? 'not_delivered' : 'delivered_unverified', base.delivery === 'not_delivered' ? base.retrySafety : 'unsafe', [base.detail, note].filter(Boolean).join(' '));
817
+ return {
818
+ ...base,
819
+ detail: [base.detail, why === '' ? undefined : foregroundNote(outcome)]
820
+ .filter(Boolean)
821
+ .join(' '),
822
+ };
823
+ };
824
+ if ((args.delivery_mode === 'foreground' || route.foreground) && this.foreground)
825
+ return inForeground('');
826
+ try {
827
+ return inputDelivery(await dispatch(name, args));
828
+ }
829
+ catch (error) {
830
+ if (error instanceof McpToolError && this.foreground && foregroundCures(error))
831
+ return inForeground('refused');
832
+ throw error;
833
+ }
834
+ };
835
+ try {
836
+ switch (action.type) {
837
+ case 'mouse_click':
838
+ try {
839
+ return await send('click', {
840
+ x: action.at.x,
841
+ y: action.at.y,
842
+ button: action.button,
843
+ });
844
+ }
845
+ catch (error) {
846
+ if (isDeliveredPointerAction(error))
847
+ return foregroundLostDelivery();
848
+ throw error;
849
+ }
850
+ case 'mouse_drag':
851
+ return await send('drag', {
343
852
  from_x: action.from.x,
344
853
  from_y: action.from.y,
345
854
  to_x: action.to.x,
@@ -348,140 +857,744 @@ export class CuaDriverAdapter {
348
857
  duration_ms: DRAG.durationMs,
349
858
  steps: DRAG.steps,
350
859
  });
351
- }
352
- catch (error) {
353
- throw windowPointerRefusal(error);
354
- }
355
- return;
356
- case 'scroll':
357
- throw new Error('computer-use: window pixel scrolling is unavailable on this Windows driver; use foreground PAGE_DOWN or ARROW_DOWN in this window, or take a deliberate display screenshot before display scrolling.');
358
- case 'type_text':
359
- if (action.text.length > 0)
360
- await call('type_text', {
860
+ case 'scroll':
861
+ throw new Error('computer-use: window pixel scrolling is unavailable on this Windows driver; use foreground PAGE_DOWN or ARROW_DOWN in this window, or take a deliberate display screenshot before display scrolling.');
862
+ case 'type_text': {
863
+ if (action.text.length === 0)
864
+ return undefined;
865
+ return await send('type_text', {
361
866
  text: action.text,
362
867
  ...(action.delivery_mode ? { delivery_mode: action.delivery_mode } : {}),
363
868
  });
364
- return;
365
- case 'key': {
366
- const plan = translateKeyForCuaDriver(action.keys);
367
- const delivery = action.delivery_mode ? { delivery_mode: action.delivery_mode } : {};
368
- if (plan.tool === 'type_text')
369
- await call('type_text', { text: plan.text, ...delivery });
370
- else if (plan.tool === 'press_key')
371
- await call('press_key', { key: plan.key, ...delivery });
372
- else
373
- await call('hotkey', { keys: [...plan.keys], ...delivery });
374
- return;
869
+ }
870
+ case 'key': {
871
+ const plan = translateKeyForCuaDriver(action.keys);
872
+ const delivery = action.delivery_mode ? { delivery_mode: action.delivery_mode } : {};
873
+ if (plan.tool === 'type_text')
874
+ return await send('type_text', { text: plan.text, ...delivery });
875
+ if (plan.tool === 'press_key')
876
+ return await send('press_key', { key: plan.key, ...delivery });
877
+ return await send('hotkey', { keys: [...plan.keys], ...delivery });
878
+ }
375
879
  }
376
880
  }
881
+ catch (error) {
882
+ // The driver answered with a refusal or a tool error: it says what it
883
+ // did not do, and that is a typed result, not a crash.
884
+ if (error instanceof McpToolError)
885
+ return failureDelivery(error);
886
+ throw error;
887
+ }
377
888
  }
378
889
  /**
379
890
  * One window's controls. Without an id, the window in front — which,
380
891
  * for an agent run from a terminal, is usually that terminal.
892
+ *
893
+ * A window with many controls comes back as an outline: the top levels,
894
+ * with each unexpanded region marked by how many children it hides and
895
+ * given a ref. `options.root` opens one such region; refs outside it stay
896
+ * valid. `options.query` keeps only the controls whose text matches.
381
897
  */
382
- async uiSnapshot(windowId) {
898
+ async uiSnapshot(requested, options = {}) {
899
+ let windowId = requested;
900
+ let rootEntry;
901
+ if (options.root !== undefined) {
902
+ rootEntry = this.uiRefs.get(options.root);
903
+ if (!rootEntry)
904
+ throw new Error(`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.`);
905
+ const own = windowIdOf(rootEntry.hwnd);
906
+ if (windowId !== undefined && parseWindowId(windowId) !== rootEntry.hwnd)
907
+ throw new Error(`${options.root} belongs to window ${own}, not ${windowId}. Pass the window it came from, or leave window_id out.`);
908
+ windowId = own;
909
+ }
383
910
  const target = await this.resolveWindow(windowId);
911
+ if (rootEntry && rootEntry.pid !== target.pid)
912
+ throw new Error(`STALE_REF: window ${windowIdOf(target.hwnd)} now belongs to a different program than ${options.root} was read from. Take a new ui_snapshot.`);
913
+ const query = options.query?.trim() ? options.query.trim() : undefined;
914
+ let read = await this.readWindowTree(target, { query });
915
+ const state0 = read.state;
916
+ const app0 = typeof state0.app_name === 'string' ? state0.app_name : '';
917
+ // A browser builds its page tree when it is first asked: the first walk can
918
+ // show only the window frame. One more walk shows the page.
919
+ if (!query && !rootEntry && BROWSER_APP.test(app0) && read.tree.count < SPARSE_TREE)
920
+ read = await this.readWindowTree(target, { query });
921
+ const { state, tree } = read;
922
+ let located;
923
+ if (rootEntry) {
924
+ const found = locate(rootEntry, tree, { actionable: !rootEntry.region });
925
+ if (found.kind === 'ambiguous')
926
+ throw new Error(`AMBIGUOUS_TARGET: ${fitText(found.count)} ${options.root} (${describeEvidence(rootEntry)}). Take a ui_snapshot of the whole window and pick the region from it.`);
927
+ if (found.kind === 'gone')
928
+ throw new Error(`STALE_REF: ${options.root} (${describeEvidence(rootEntry)}) is no longer in the window. Take a ui_snapshot of the whole window.`);
929
+ located = found.node;
930
+ }
931
+ const viewRoot = located?.element ?? tree.root;
932
+ const basePath = located?.path ?? [];
933
+ const view = !query && visibleCount(viewRoot) > OUTLINE_THRESHOLD
934
+ ? outlineOf(viewRoot, basePath, OUTLINE_BUDGET, located ? { offset: options.offset ?? 0 } : undefined)
935
+ : { root: viewRoot, regions: new Set(), next: undefined };
936
+ const shownKeys = new Set();
937
+ collectShown(view.root, basePath, shownKeys);
938
+ const refs = this.bindRead(target, read, {
939
+ shown: shownKeys,
940
+ regions: view.regions,
941
+ partial: query !== undefined,
942
+ });
943
+ const refAt = (path) => refs.get(pathKey(path)) ?? '';
944
+ const root = withRefs(view.root, basePath, refAt);
945
+ const title = typeof state.window_title === 'string' ? state.window_title : undefined;
946
+ const app = typeof state.app_name === 'string' ? state.app_name.replace(/\.exe$/i, '') : undefined;
947
+ return {
948
+ windowId: windowIdOf(target.hwnd),
949
+ ...(title !== undefined ? { title } : {}),
950
+ ...(app !== undefined ? { app } : {}),
951
+ root,
952
+ ...(state.truncated === true || tree.count >= UI_WALK_CUT_AT ? { truncated: true } : {}),
953
+ ...(view.regions.size > 0 ? { outline: true } : {}),
954
+ total: tree.count,
955
+ ...(rootEntry ? { region: true } : {}),
956
+ ...(view.next !== undefined ? { next: view.next } : {}),
957
+ };
958
+ }
959
+ /** One `get_window_state` walk, with the process and session it was read from. */
960
+ async readWindowTree(target, options = {}) {
384
961
  let processStarts = 0;
385
- let snapshotGeneration = this.sessionGeneration;
962
+ let generation = this.sessionGeneration;
386
963
  const state = structured(await this.callTool('get_window_state', {
387
964
  pid: target.pid,
388
965
  window_id: target.hwnd,
389
966
  include_screenshot: false,
390
967
  max_elements: UI_MAX_ELEMENTS,
968
+ ...(options.query ? { query: options.query } : {}),
391
969
  }, UI_TREE_TIMEOUT_MS, undefined, (starts) => {
392
970
  processStarts = starts;
393
- snapshotGeneration = this.sessionGeneration;
971
+ generation = this.sessionGeneration;
394
972
  }), 'get_window_state');
395
- if (snapshotGeneration !== this.sessionGeneration || processStarts === 0)
973
+ if (generation !== this.sessionGeneration || processStarts === 0)
396
974
  throw new McpToolError('get_window_state', 'stale UI snapshot; take a new one');
397
- const tree = toUiTree(state);
398
- const snapshot = ++this.nextSnapshot;
399
- const refs = new Map();
400
- let ordinal = 0;
401
- const root = withOpaqueRefs(tree.root, (token) => {
402
- const ref = `cua-ui:${this.uiRefNamespace}:${snapshot}:${++ordinal}`;
403
- refs.set(ref, {
404
- ...tree.refs.get(token),
405
- token,
975
+ if (typeof state.pid === 'number' && state.pid !== target.pid)
976
+ throw new McpToolError('get_window_state', 'window changed owner; take a new UI snapshot');
977
+ return { state, tree: toUiTree(state), processStarts, generation };
978
+ }
979
+ /**
980
+ * Record a read of a window: every ref the model already holds for it is
981
+ * pointed at the control it named in this read (found by its evidence),
982
+ * and the controls the model is being shown, and the regions it can open,
983
+ * get refs. A ref whose control is not found keeps its old, now dead,
984
+ * read, so using it re-resolves and reports why. Returns ref by path.
985
+ */
986
+ bindRead(target, read, scope) {
987
+ const seq = ++this.nextRead;
988
+ const at = this.now();
989
+ this.windowReads.set(target.hwnd, { seq, at });
990
+ const byPath = new Map();
991
+ const claimed = new Set();
992
+ const named = new Map();
993
+ for (const node of read.tree.nodes) {
994
+ const key = `${node.role}\u0000${node.name.trim()}`;
995
+ named.set(key, (named.get(key) ?? 0) + 1);
996
+ }
997
+ const bound = (node, entry, ref) => {
998
+ const key = pathKey(node.path);
999
+ claimed.add(key);
1000
+ byPath.set(key, ref);
1001
+ const twin = node.automationId === undefined &&
1002
+ node.name.trim() !== '' &&
1003
+ (named.get(`${node.role}\u0000${node.name.trim()}`) ?? 0) > 1;
1004
+ this.uiRefs.set(ref, {
1005
+ ...(node.facts ?? factsOfNode(node)),
1006
+ twin,
1007
+ ...(scope.partial
1008
+ ? {}
1009
+ : {
1010
+ childCount: node.element.children?.length ?? 0,
1011
+ treeSig: read.tree.signature,
1012
+ }),
1013
+ token: node.token,
406
1014
  pid: target.pid,
407
- generation: snapshotGeneration,
408
- processStarts,
1015
+ hwnd: target.hwnd,
1016
+ region: entry.region,
1017
+ ...(node.element.bounds ? { bounds: node.element.bounds } : {}),
1018
+ generation: read.generation,
1019
+ processStarts: read.processStarts,
1020
+ readSeq: seq,
1021
+ readAt: at,
409
1022
  });
410
- return ref;
411
- });
412
- this.uiRefs = refs;
413
- const title = typeof state.window_title === 'string' ? state.window_title : undefined;
414
- const app = typeof state.app_name === 'string' ? state.app_name.replace(/\.exe$/i, '') : undefined;
1023
+ };
1024
+ // A filtered read has other places than the window; it only adds refs.
1025
+ // A handle another program reuses is not the window the ref came from.
1026
+ if (!scope.partial) {
1027
+ for (const [ref, entry] of [...this.uiRefs]) {
1028
+ if (entry.hwnd !== target.hwnd || entry.pid !== target.pid)
1029
+ continue;
1030
+ const found = locate(entry, read.tree, { actionable: !entry.region });
1031
+ if (found.kind !== 'found' || claimed.has(pathKey(found.node.path)))
1032
+ continue;
1033
+ bound(found.node, entry, ref);
1034
+ }
1035
+ }
1036
+ let created = 0;
1037
+ for (const node of read.tree.nodes) {
1038
+ const key = pathKey(node.path);
1039
+ if (claimed.has(key))
1040
+ continue;
1041
+ const region = scope.regions.has(key);
1042
+ const actionable = node.token !== '' && scope.shown.has(key);
1043
+ if (!region && !actionable)
1044
+ continue;
1045
+ // A match set larger than the ref budget would evict its own refs.
1046
+ if (created >= NEW_REFS_PER_READ)
1047
+ break;
1048
+ created++;
1049
+ const ref = `cua-ui:${this.uiRefNamespace}:${++this.nextRef}`;
1050
+ const entry = { region: !actionable };
1051
+ bound(node, entry, ref);
1052
+ }
1053
+ this.trimRefs(seq);
1054
+ return byPath;
1055
+ }
1056
+ /** The model holds only so many refs; the oldest reads go first. */
1057
+ trimRefs(keepSeq) {
1058
+ if (this.uiRefs.size <= MAX_REFS)
1059
+ return;
1060
+ // The read that just answered keeps every ref it handed out.
1061
+ const oldest = [...this.uiRefs]
1062
+ .filter(([, entry]) => entry.readSeq !== keepSeq)
1063
+ .sort((a, b) => a[1].readSeq - b[1].readSeq);
1064
+ for (const [ref] of oldest.slice(0, this.uiRefs.size - MAX_REFS))
1065
+ this.uiRefs.delete(ref);
1066
+ }
1067
+ /**
1068
+ * The ref's control as it is now: the entry itself when it was read
1069
+ * recently in the window's latest read, else found again in a fresh read
1070
+ * by its evidence (id, then place, then role and name). Never a guess:
1071
+ * several fits is AMBIGUOUS_TARGET, none is STALE_REF, and nothing has been
1072
+ * sent in either case.
1073
+ */
1074
+ async resolveRef(ref, entry) {
1075
+ const latest = this.windowReads.get(entry.hwnd);
1076
+ if (latest &&
1077
+ entry.readSeq === latest.seq &&
1078
+ entry.generation === this.sessionGeneration &&
1079
+ this.now() - entry.readAt <= IDENTITY_FRESH_MS)
1080
+ return { entry };
1081
+ const target = { hwnd: entry.hwnd, pid: entry.pid };
1082
+ let read;
1083
+ try {
1084
+ read = await this.readWindowTree(target, {});
1085
+ }
1086
+ catch (error) {
1087
+ const gone = await this.windowIsGone(entry);
1088
+ if (gone)
1089
+ return {
1090
+ fail: refFailure('STALE_REF', `the window of ${describeEvidence(entry)} is closed. Nothing was sent. List the windows again.`),
1091
+ };
1092
+ return {
1093
+ fail: {
1094
+ ok: false,
1095
+ delivery: 'not_delivered',
1096
+ retrySafety: 'safe',
1097
+ 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.`,
1098
+ },
1099
+ };
1100
+ }
1101
+ const found = locate(entry, read.tree, { actionable: true });
1102
+ this.bindRead(target, read, { shown: new Set(), regions: new Set() });
1103
+ const next = this.uiRefs.get(ref);
1104
+ if (found.kind === 'found' && next && next.readSeq === this.windowReads.get(entry.hwnd)?.seq)
1105
+ return { entry: next };
1106
+ if (found.kind === 'ambiguous' || found.kind === 'found')
1107
+ return {
1108
+ fail: refFailure('AMBIGUOUS_TARGET', `${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.`),
1109
+ };
415
1110
  return {
416
- windowId: windowIdOf(target.hwnd),
417
- ...(title !== undefined ? { title } : {}),
418
- ...(app !== undefined ? { app } : {}),
419
- root,
420
- ...(state.truncated === true ? { truncated: true } : {}),
1111
+ fail: refFailure('STALE_REF', `${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.`),
421
1112
  };
422
1113
  }
1114
+ /** Whether the ref's window has closed (or changed owner). Costs a window list, so only asked after a failure. */
1115
+ async windowIsGone(entry) {
1116
+ try {
1117
+ const windows = await this.listWindows();
1118
+ const id = windowIdOf(entry.hwnd);
1119
+ const found = windows.find((window) => window.id === id);
1120
+ return !found || found.pid !== entry.pid;
1121
+ }
1122
+ catch {
1123
+ return false;
1124
+ }
1125
+ }
423
1126
  async uiAct(ref, action, value) {
424
- const facts = this.uiRefs.get(ref);
425
- if (!facts)
1127
+ return this.actOn(ref, action, value, true);
1128
+ }
1129
+ async actOn(ref, action, value, retry) {
1130
+ const held = this.uiRefs.get(ref);
1131
+ if (!held)
1132
+ return refFailure('STALE_REF', `${ref} is not a control this session was shown, so nothing was sent. Take a ui_snapshot and use a ref from it.`);
1133
+ if (held.region)
426
1134
  return {
427
1135
  ok: false,
428
- detail: `${ref} is not a control of the latest UI snapshot; take a new one.`,
1136
+ delivery: 'not_delivered',
1137
+ retrySafety: 'safe',
1138
+ 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.`,
429
1139
  };
1140
+ const resolved = await this.resolveRef(ref, held);
1141
+ if ('fail' in resolved)
1142
+ return resolved.fail;
1143
+ const facts = resolved.entry;
430
1144
  const { pid, token } = facts;
431
1145
  const uiRef = { ref, facts };
1146
+ this.tryPresence((presence) => presence.mark({
1147
+ hwnd: facts.hwnd,
1148
+ kind: action === 'set_value' ? 'type' : 'click',
1149
+ ...(facts.bounds
1150
+ ? {
1151
+ at: {
1152
+ x: facts.bounds.x + facts.bounds.width / 2,
1153
+ y: facts.bounds.y + facts.bounds.height / 2,
1154
+ },
1155
+ }
1156
+ : {}),
1157
+ }));
432
1158
  try {
433
1159
  switch (action) {
434
1160
  case 'invoke':
435
- case 'toggle':
436
- case 'select':
437
1161
  case 'expand':
438
1162
  case 'collapse':
439
1163
  // cua-driver's click on an element token performs the control's
440
1164
  // own pattern in the background (Invoke, or a posted click at its
441
1165
  // centre), with no pointer move and no change of foreground.
442
- return actResult(await this.callTool('click', { pid, element_token: token }, undefined, uiRef));
1166
+ return await this.clickAndWatch(facts, uiRef);
1167
+ case 'select': {
1168
+ // 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.
1169
+ if (ITEM_ROLES.test(facts.role) && facts.actions.includes('invoke'))
1170
+ return await this.selectWithoutOpening(facts);
1171
+ const sent = await this.clickRef(facts, uiRef);
1172
+ if (!sent.ok)
1173
+ return sent;
1174
+ return judgeSelect(facts, await this.readBack(facts));
1175
+ }
1176
+ case 'toggle': {
1177
+ const sent = await this.clickRef(facts, uiRef);
1178
+ if (!sent.ok)
1179
+ return sent;
1180
+ const back = await this.readBack(facts);
1181
+ return judgeToggle(facts, back);
1182
+ }
443
1183
  case 'set_value': {
444
1184
  const text = value ?? '';
1185
+ let sent;
445
1186
  try {
446
- return actResult(await this.callTool('set_value', { pid, element_token: token, value: text }, undefined, uiRef));
1187
+ sent = actResult(await this.callTool('set_value', { pid, element_token: token, value: text }, undefined, uiRef));
447
1188
  }
448
1189
  catch (error) {
449
- if (!(error instanceof McpToolError) ||
450
- !/does not implement ValuePattern/i.test(error.message))
451
- throw error;
452
- // A classic Win32 edit reports no ValuePattern. Typing into it
453
- // equals setting it only while it is empty.
454
- if (facts.value !== undefined && facts.value.length > 0)
1190
+ if (error instanceof McpToolError &&
1191
+ /does not implement ValuePattern/i.test(error.message)) {
1192
+ // A classic edit control takes its text by window message, never by focus or keys.
1193
+ const edited = await this.setByMessages(facts, text);
1194
+ if (edited)
1195
+ return edited;
1196
+ // Typing instead would equal setting only while the field is
1197
+ // empty, and the driver's own report of it is not trustworthy.
455
1198
  return {
456
1199
  ok: false,
457
- detail: 'this field cannot be set directly and already holds text; click it, select its text (CTRL+A) and type the new text instead',
1200
+ delivery: 'not_delivered',
1201
+ retrySafety: 'safe',
1202
+ detail: '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).',
458
1203
  };
459
- const typed = actResult(await this.callTool('type_text', { pid, element_token: token, text }, undefined, uiRef));
460
- return typed.ok
461
- ? {
462
- ok: true,
463
- detail: 'typed into the empty field, which has no settable value',
464
- }
465
- : typed;
1204
+ }
1205
+ throw error;
466
1206
  }
1207
+ if (!sent.ok)
1208
+ return sent;
1209
+ const judged = judgeSetValue(facts, text, await this.readBack(facts));
1210
+ // A choice in a list that ignored the driver is made with the keyboard, in the foreground.
1211
+ if (judged.delivery === 'not_delivered' && CHOICE_ROLES.test(facts.role))
1212
+ return await this.chooseByKeyboard(ref, facts, text, judged);
1213
+ return judged;
467
1214
  }
468
1215
  case 'focus':
469
1216
  case 'scroll_into_view':
470
1217
  return {
471
1218
  ok: false,
1219
+ delivery: 'not_delivered',
1220
+ retrySafety: 'safe',
472
1221
  detail: `this host cannot ${action === 'focus' ? 'focus' : 'scroll to'} a control by itself; invoke it or click it instead`,
473
1222
  };
474
1223
  }
475
1224
  }
476
1225
  catch (error) {
1226
+ if (error instanceof McpToolError && isStaleHandle(error)) {
1227
+ // The driver refused before acting: a newer read of the window replaced
1228
+ // the handle. Read again and find the control by what it is, once.
1229
+ this.windowReads.delete(facts.hwnd);
1230
+ if (retry)
1231
+ return this.actOn(ref, action, value, false);
1232
+ return refFailure('STALE_REF', `${describeEvidence(facts)} changed while it was being acted on. Nothing was sent. Take a ui_snapshot and try again.`);
1233
+ }
477
1234
  if (error instanceof McpToolError)
478
- return { ok: false, detail: toolRefusal(error) };
1235
+ return failureResult(error);
479
1236
  throw error;
480
1237
  }
481
1238
  }
1239
+ /**
1240
+ * Choose an option by the keyboard, for a list the driver's value call did
1241
+ * not change (a web page's select element ignores it in the background).
1242
+ * One foreground burst focuses the control, types the option and confirms
1243
+ * it; the control is then read back. Where that does not work either, the
1244
+ * model is told which route to use instead.
1245
+ */
1246
+ async chooseByKeyboard(ref, stale, option, unchanged) {
1247
+ const ladder = this.foreground;
1248
+ const instead = '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.';
1249
+ if (!ladder)
1250
+ return unchanged;
1251
+ // The read-back that judged the value replaced the driver's handle: click through the new one.
1252
+ const facts = this.uiRefs.get(ref) ?? stale;
1253
+ const uiRef = { ref, facts };
1254
+ const { pid } = facts;
1255
+ const hwnd = windowIdOf(facts.hwnd);
1256
+ const subject = {
1257
+ app: this.windowApps.get(hwnd) ?? `process ${pid}`,
1258
+ pid,
1259
+ hwnd,
1260
+ };
1261
+ const scope = {
1262
+ scope: 'window',
1263
+ pid,
1264
+ window_id: facts.hwnd,
1265
+ delivery_mode: 'foreground',
1266
+ };
1267
+ const outcome = await ladder
1268
+ .run(this.burstRequest(subject, true), async (burst) => {
1269
+ await burst.checkpoint();
1270
+ try {
1271
+ await this.callTool('click', { pid, element_token: facts.token, delivery_mode: 'foreground' }, undefined, uiRef);
1272
+ await burst.checkpoint();
1273
+ await this.callTool('type_text', { ...scope, text: option });
1274
+ await burst.checkpoint();
1275
+ await this.callTool('press_key', { ...scope, key: 'return' });
1276
+ return undefined;
1277
+ }
1278
+ catch (error) {
1279
+ if (error instanceof McpToolError)
1280
+ return failureResult(error);
1281
+ throw error;
1282
+ }
1283
+ })
1284
+ .catch((error) => {
1285
+ if (error instanceof BurstInterrupted)
1286
+ return error;
1287
+ throw error;
1288
+ });
1289
+ if (outcome instanceof BurstInterrupted)
1290
+ return {
1291
+ ok: false,
1292
+ delivery: 'not_delivered',
1293
+ retrySafety: 'safe',
1294
+ detail: outcome.reason === 'person'
1295
+ ? 'a person used the keyboard or mouse just before the choice was made, so it may not have been. Try again in a moment.'
1296
+ : 'an administrator window came to the front just before the choice was made; Namzu cannot type into it. Try again once it is gone.',
1297
+ };
1298
+ if (outcome.kind === 'blocked')
1299
+ return {
1300
+ ok: false,
1301
+ delivery: 'not_delivered',
1302
+ retrySafety: 'safe',
1303
+ detail: `${outcome.block.detail} ${instead}`,
1304
+ };
1305
+ const dropped = droppedInputNote(outcome);
1306
+ if (dropped)
1307
+ return {
1308
+ ok: false,
1309
+ delivery: 'not_delivered',
1310
+ retrySafety: 'safe',
1311
+ detail: `${dropped} ${instead}`,
1312
+ };
1313
+ const note = interferenceNote(outcome);
1314
+ if (outcome.value && !outcome.value.ok)
1315
+ return outcome.value;
1316
+ const judged = judgeSetValue(facts, option, await this.readBack(facts));
1317
+ if (note)
1318
+ return {
1319
+ ...judged,
1320
+ delivery: 'delivered_unverified',
1321
+ retrySafety: 'unsafe',
1322
+ detail: note,
1323
+ };
1324
+ if (judged.delivery === 'delivered_verified')
1325
+ return { ...judged, detail: foregroundNote(outcome) };
1326
+ return { ...judged, detail: `${judged.detail ?? ''} ${instead}`.trim() };
1327
+ }
1328
+ /**
1329
+ * Select a list or tree row that can also be invoked, through its selection
1330
+ * pattern, so that a file row is chosen and not opened. Where that cannot be
1331
+ * reached nothing is sent: the click that is left would open the item.
1332
+ */
1333
+ async selectWithoutOpening(facts) {
1334
+ const result = await this.foreground?.selectItem({
1335
+ hwnd: windowIdOf(facts.hwnd),
1336
+ role: facts.role,
1337
+ name: facts.name,
1338
+ ...(facts.automationId ? { automationId: facts.automationId } : {}),
1339
+ ...(facts.bounds ? { bounds: facts.bounds } : {}),
1340
+ });
1341
+ if (!result?.found) {
1342
+ const why = result
1343
+ ? (SELECT_REFUSALS[result.reason] ?? 'the row could not be selected')
1344
+ : 'this host cannot select a row without opening it';
1345
+ return {
1346
+ ok: false,
1347
+ delivery: 'not_delivered',
1348
+ retrySafety: 'safe',
1349
+ 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.`,
1350
+ };
1351
+ }
1352
+ const back = await this.readBack(facts);
1353
+ if (back?.selected === true || (back === undefined && result.selected))
1354
+ return {
1355
+ ok: true,
1356
+ delivery: 'delivered_verified',
1357
+ retrySafety: 'unsafe',
1358
+ readBack: { expected: 'selected', observed: 'selected' },
1359
+ detail: 'The row is selected; it was not opened.',
1360
+ };
1361
+ return {
1362
+ ok: true,
1363
+ delivery: 'delivered_unverified',
1364
+ retrySafety: 'unsafe',
1365
+ readBack: { expected: 'selected', observed: 'not selected' },
1366
+ detail: 'the row was selected by its selection pattern, but it does not read as selected.',
1367
+ };
1368
+ }
1369
+ /** Replace a classic edit control's text by window message; undefined where the control is not one this reaches. */
1370
+ async setByMessages(facts, text) {
1371
+ const ladder = this.foreground;
1372
+ if (!ladder)
1373
+ return undefined;
1374
+ const result = await ladder.editText({
1375
+ hwnd: windowIdOf(facts.hwnd),
1376
+ op: 'set',
1377
+ text,
1378
+ pick: 'bounds',
1379
+ ...(facts.bounds
1380
+ ? {
1381
+ at: {
1382
+ x: facts.bounds.x + facts.bounds.width / 2,
1383
+ y: facts.bounds.y + facts.bounds.height / 2,
1384
+ },
1385
+ }
1386
+ : {}),
1387
+ });
1388
+ if (!result)
1389
+ return undefined;
1390
+ if (!result.found) {
1391
+ if (result.reason === 'uipi' || result.reason === 'gone')
1392
+ return { ...judgeEdit('set', text, result), ok: false };
1393
+ return undefined;
1394
+ }
1395
+ return judgeEdit('set', text, result);
1396
+ }
1397
+ /**
1398
+ * A shortcut with a modifier, carried out as the window's own menu command. Undefined where the window has no
1399
+ * classic menu item for it (the usual case for a modern window), so the key goes the ordinary way.
1400
+ */
1401
+ async shortcutByMenu(frame, keys) {
1402
+ const ladder = this.foreground;
1403
+ if (!ladder)
1404
+ return undefined;
1405
+ const accelerator = menuAcceleratorOf(keys);
1406
+ if (accelerator === undefined)
1407
+ return undefined;
1408
+ const result = await ladder.menuCommand({ hwnd: frame.window.id, accelerator });
1409
+ if (!result?.found)
1410
+ return undefined;
1411
+ this.showPresence(frame, frame.window.bounds, 'hotkey', {});
1412
+ return {
1413
+ delivery: 'delivered_unverified',
1414
+ retrySafety: 'unsafe',
1415
+ detail: `Carried out as the window's menu command "${result.label ?? accelerator}" (no key pressed, the screen not used).`,
1416
+ };
1417
+ }
1418
+ /** Type into the window's focused classic edit control by window message; undefined where there is none. */
1419
+ async typeByMessages(frame, text) {
1420
+ const ladder = this.foreground;
1421
+ if (!ladder)
1422
+ return undefined;
1423
+ const result = await ladder.editText({
1424
+ hwnd: frame.window.id,
1425
+ op: 'type',
1426
+ text,
1427
+ pick: 'focus',
1428
+ });
1429
+ if (!result)
1430
+ return undefined;
1431
+ if (!result.found) {
1432
+ if (result.reason !== 'uipi')
1433
+ return undefined;
1434
+ return judgeEdit('type', text, result);
1435
+ }
1436
+ this.showPresence(frame, frame.window.bounds, 'type_text', {});
1437
+ const { ok: _ok, ...verdict } = judgeEdit('type', text, result);
1438
+ return verdict;
1439
+ }
1440
+ /**
1441
+ * A click on a control that the control's own state does not answer for
1442
+ * (a button): when the driver cannot confirm it, the window is read before
1443
+ * and after, and the click is verified by what it changed.
1444
+ */
1445
+ async clickAndWatch(facts, uiRef) {
1446
+ const target = { hwnd: facts.hwnd, pid: facts.pid };
1447
+ const earlier = await this.observe(target);
1448
+ const before = await this.observe(target);
1449
+ const windows = await this.windowIdsOf(target.pid);
1450
+ // Each read of the window replaces the driver's handles: click through the refreshed one.
1451
+ const current = this.uiRefs.get(uiRef.ref) ?? facts;
1452
+ const sent = await this.clickRef(current, {
1453
+ ref: uiRef.ref,
1454
+ facts: current,
1455
+ });
1456
+ if (!sent.ok || sent.delivery !== 'delivered_unverified' || !before)
1457
+ return sent;
1458
+ const seen = await this.verifyByReading(target, {
1459
+ typed: undefined,
1460
+ before,
1461
+ earlier,
1462
+ windows,
1463
+ });
1464
+ if (!seen)
1465
+ return sent;
1466
+ return {
1467
+ ok: true,
1468
+ delivery: seen.delivery,
1469
+ retrySafety: seen.retrySafety,
1470
+ detail: seen.detail,
1471
+ ...(seen.observed !== undefined ? { readBack: { observed: seen.observed } } : {}),
1472
+ };
1473
+ }
1474
+ /**
1475
+ * A click on a control by its driver token, in the background. Where the
1476
+ * driver says the window cannot take background input (or is covered) the
1477
+ * same click is retried in the foreground through the ladder.
1478
+ */
1479
+ async clickRef(facts, uiRef) {
1480
+ const { pid, token } = facts;
1481
+ try {
1482
+ return actResult(await this.callTool('click', { pid, element_token: token }, undefined, uiRef));
1483
+ }
1484
+ catch (error) {
1485
+ const ladder = this.foreground;
1486
+ if (!(error instanceof McpToolError) || !ladder || !foregroundCures(error))
1487
+ throw error;
1488
+ const subject = {
1489
+ app: this.windowApps.get(windowIdOf(facts.hwnd)) ?? `process ${pid}`,
1490
+ pid,
1491
+ hwnd: windowIdOf(facts.hwnd),
1492
+ };
1493
+ const outcome = await ladder
1494
+ .run(this.burstRequest(subject, true), async (burst) => {
1495
+ await burst.checkpoint();
1496
+ try {
1497
+ return actResult(await this.callTool('click', { pid, element_token: token, delivery_mode: 'foreground' }, undefined, uiRef));
1498
+ }
1499
+ catch (inner) {
1500
+ if (inner instanceof McpToolError)
1501
+ return failureResult(inner);
1502
+ throw inner;
1503
+ }
1504
+ })
1505
+ .catch((inner) => {
1506
+ if (inner instanceof BurstInterrupted)
1507
+ return inner;
1508
+ throw inner;
1509
+ });
1510
+ if (outcome instanceof BurstInterrupted)
1511
+ return {
1512
+ ok: false,
1513
+ delivery: 'not_delivered',
1514
+ retrySafety: 'safe',
1515
+ detail: outcome.reason === 'person'
1516
+ ? 'a person used the keyboard or mouse just before the click was sent, so nothing was sent. Try again in a moment.'
1517
+ : '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.',
1518
+ };
1519
+ if (outcome.kind === 'blocked')
1520
+ return {
1521
+ ok: false,
1522
+ delivery: 'not_delivered',
1523
+ retrySafety: 'safe',
1524
+ detail: outcome.block.detail,
1525
+ };
1526
+ const dropped = droppedInputNote(outcome);
1527
+ if (dropped)
1528
+ return {
1529
+ ok: false,
1530
+ delivery: 'not_delivered',
1531
+ retrySafety: 'safe',
1532
+ detail: dropped,
1533
+ };
1534
+ const note = interferenceNote(outcome);
1535
+ const base = outcome.value;
1536
+ const detail = [base.detail, note ?? foregroundNote(outcome)].filter(Boolean).join(' ');
1537
+ if (note && base.delivery !== 'not_delivered')
1538
+ return {
1539
+ ...base,
1540
+ delivery: 'delivered_unverified',
1541
+ retrySafety: 'unsafe',
1542
+ detail,
1543
+ };
1544
+ return { ...base, detail };
1545
+ }
1546
+ }
1547
+ /**
1548
+ * The control as a fresh read of its window shows it, or undefined when
1549
+ * that read failed or the control is gone. A failed read says nothing
1550
+ * about the action, so callers treat undefined as "unverified".
1551
+ */
1552
+ async readBack(facts) {
1553
+ try {
1554
+ const target = { hwnd: facts.hwnd, pid: facts.pid };
1555
+ const read = await this.readWindowTree(target, {});
1556
+ const found = locate(facts, read.tree, { actionable: true });
1557
+ this.bindRead(target, read, { shown: new Set(), regions: new Set() });
1558
+ return found.kind === 'found' ? found.node.facts : undefined;
1559
+ }
1560
+ catch {
1561
+ return undefined;
1562
+ }
1563
+ }
482
1564
  async dispose() {
483
1565
  await this.client.dispose();
484
1566
  }
1567
+ /** Tells the overlay where the agent is about to act in a window; never waits and never fails the action. */
1568
+ showPresence(frame, bounds, tool, args) {
1569
+ const presence = this.presence;
1570
+ if (!presence)
1571
+ return;
1572
+ const hwnd = parseWindowId(frame.window.id);
1573
+ if (hwnd === undefined)
1574
+ return;
1575
+ const scale = frame.width > 0 ? bounds.width / frame.width : 1;
1576
+ const screen = (x, y) => typeof x === 'number' && typeof y === 'number'
1577
+ ? { x: bounds.x + x * scale, y: bounds.y + y * scale }
1578
+ : undefined;
1579
+ const at = screen(args.x ?? args.to_x, args.y ?? args.to_y);
1580
+ const typing = tool === 'type_text' || tool === 'press_key' || tool === 'hotkey';
1581
+ this.tryPresence((overlay) => overlay.mark({
1582
+ hwnd,
1583
+ kind: typing ? 'type' : 'click',
1584
+ ...(at && !typing ? { at } : {}),
1585
+ }));
1586
+ }
1587
+ /** The overlay is decoration: whatever it does, the action goes on. */
1588
+ tryPresence(use) {
1589
+ if (!this.presence || this.driverCursorOff === false)
1590
+ return;
1591
+ try {
1592
+ use(this.presence);
1593
+ }
1594
+ catch {
1595
+ // Nothing is shown; nothing else changes.
1596
+ }
1597
+ }
485
1598
  async serializeWindowOperation(operation) {
486
1599
  const previous = this.windowOperation;
487
1600
  let release = () => undefined;
@@ -510,24 +1623,35 @@ export class CuaDriverAdapter {
510
1623
  throw new McpToolError(name, 'stale window screenshot; capture the window again');
511
1624
  if (uiRef &&
512
1625
  (this.uiRefs.get(uiRef.ref) !== uiRef.facts ||
513
- uiRef.facts.generation !== this.sessionGeneration))
1626
+ uiRef.facts.generation !== this.sessionGeneration ||
1627
+ this.windowReads.get(uiRef.facts.hwnd)?.seq !== uiRef.facts.readSeq))
514
1628
  throw new McpToolError(name, 'stale UI snapshot; take a new one');
515
1629
  const generation = this.sessionGeneration;
1630
+ const signal = currentCallSignal();
1631
+ const changes = changesDesktop(name);
516
1632
  try {
517
- return await this.client.callTool(name, args, timeoutMs, {
1633
+ const result = await this.client.callTool(name, args, timeoutMs, {
1634
+ ...(signal ? { signal } : {}),
518
1635
  ...(uiRef || windowFrame
519
- ? { expectedStarts: uiRef?.facts.processStarts ?? windowFrame?.processStarts }
1636
+ ? {
1637
+ expectedStarts: uiRef?.facts.processStarts ?? windowFrame?.processStarts,
1638
+ }
520
1639
  : {}),
521
1640
  ...(onProcess ? { onProcess } : {}),
522
1641
  });
1642
+ if (changes)
1643
+ markSent();
1644
+ return result;
523
1645
  }
524
1646
  catch (error) {
1647
+ if (error instanceof CallAbortedError && error.sent && changes)
1648
+ markSent();
525
1649
  if (!isEndedSessionRefusal(error))
526
1650
  throw error;
527
1651
  // The refusal proves the old session's element tokens are invalid,
528
1652
  // even if start_session fails and there is no successful revival.
529
1653
  if (this.sessionGeneration === generation)
530
- this.uiRefs.clear();
1654
+ this.windowReads.clear();
531
1655
  this.windowFrame = undefined;
532
1656
  await this.reviveSession(generation);
533
1657
  // Element tokens belong to the old snapshot. A new lifecycle session
@@ -538,17 +1662,37 @@ export class CuaDriverAdapter {
538
1662
  throw new McpToolError(name, 'stale window screenshot; capture the window again');
539
1663
  // One retry only. A second refusal or an unacknowledged action is
540
1664
  // returned to the host without any further automatic replay.
541
- return this.client.callTool(name, args, timeoutMs, { onProcess });
1665
+ const retried = await this.client.callTool(name, args, timeoutMs, {
1666
+ ...(signal ? { signal } : {}),
1667
+ ...(onProcess ? { onProcess } : {}),
1668
+ });
1669
+ if (changes)
1670
+ markSent();
1671
+ return retried;
542
1672
  }
543
1673
  }
1674
+ /**
1675
+ * What a foreground burst asks of the ladder: the call's cancellation, and
1676
+ * the wait for calls a cancelled burst left in flight before the window and
1677
+ * cursor are put back.
1678
+ */
1679
+ burstRequest(subject, sendsInput) {
1680
+ const signal = currentCallSignal();
1681
+ return {
1682
+ subject,
1683
+ sendsInput,
1684
+ ...(signal ? { signal } : {}),
1685
+ settle: () => this.client.settled(),
1686
+ };
1687
+ }
544
1688
  async reviveSession(generation) {
545
1689
  if (this.sessionGeneration !== generation)
546
1690
  return;
547
1691
  if (!this.sessionRevival) {
548
1692
  this.sessionRevival = (async () => {
549
1693
  await this.client.callTool('start_session');
550
- await disableAgentCursor((name, args) => this.client.callTool(name, args));
551
- this.uiRefs.clear();
1694
+ this.driverCursorOff = await disableAgentCursor((name, args) => this.client.callTool(name, args));
1695
+ this.windowReads.clear();
552
1696
  this.windowFrame = undefined;
553
1697
  this.sessionGeneration++;
554
1698
  })().finally(() => {
@@ -577,16 +1721,24 @@ export class CuaDriverAdapter {
577
1721
  throw new Error(`computer-use: no window ${windowId} is open now. List the windows again.`);
578
1722
  return { hwnd, pid };
579
1723
  }
1724
+ /**
1725
+ * A display pointer action. A click that ends with another window in front
1726
+ * is reported as sent but unverified: it may have closed its own window,
1727
+ * or it may have missed. Neither is "done".
1728
+ */
580
1729
  async pointer(tool, args) {
581
1730
  try {
582
- await this.callTool(tool, args);
1731
+ return okResult(inputDelivery(await this.callTool(tool, args)));
583
1732
  }
584
1733
  catch (error) {
585
1734
  if (isDeliveredPointerAction(error))
586
- return;
1735
+ return okResult(foregroundLostDelivery());
587
1736
  throw error;
588
1737
  }
589
1738
  }
1739
+ async keyboard(tool, args) {
1740
+ return okResult(inputDelivery(await this.callTool(tool, args)));
1741
+ }
590
1742
  async capture() {
591
1743
  const result = await this.callTool('get_desktop_state', {}, CAPTURE_TIMEOUT_MS);
592
1744
  const image = result.content.find((part) => part.type === 'image' && typeof part.data === 'string');
@@ -640,45 +1792,208 @@ export function isDeliveredPointerAction(error) {
640
1792
  /not foreground after the/.test(error.message) &&
641
1793
  !/no (mouse )?input was sent/.test(error.message));
642
1794
  }
643
- /** The pinned driver suggests foreground pointer input even when it cannot bind the OS hit test to our HWND. */
644
- function windowPointerRefusal(error) {
645
- const code = error instanceof McpToolError ? error.structuredContent?.code : undefined;
646
- if (code === 'background_unavailable' ||
647
- code === 'background_occluded' ||
648
- code === 'background_uipi_blocked')
649
- return new Error('computer-use: this window pointer action could not be delivered safely in background. No window-scoped foreground pointer retry is available; inspect a fresh window screenshot, use a control ref if available, or deliberately capture the display before display input.');
650
- return error;
1795
+ const trimText = (value, max = 80) => value.length > max ? `${value.slice(0, max - 1)}…` : value;
1796
+ /** A delivery verdict with the retry advice that goes with it. */
1797
+ function verdict(delivery, retrySafety, detail) {
1798
+ return { delivery, retrySafety, ...(detail !== undefined ? { detail } : {}) };
1799
+ }
1800
+ /** `ok` with a delivery verdict: a call that returned is never proof that the effect happened. */
1801
+ function okResult(input) {
1802
+ return { type: 'ok', ...input };
1803
+ }
1804
+ /** The click was sent, but the window it targeted is no longer in front afterwards. */
1805
+ function foregroundLostDelivery() {
1806
+ return verdict('delivered_unverified', 'unsafe', '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.');
651
1807
  }
652
1808
  /**
653
- * cua-driver's action result → the host's. `confirmed`, `partial` and
654
- * `unverifiable` count as done: a background UIA Invoke is `unverifiable` by
655
- * design (the control does not report back), and the screenshot the tool
656
- * takes afterwards is where the model sees the effect.
1809
+ * What a driver tool call that returned says about the input it sent.
1810
+ *
1811
+ * The driver reports `effect: "unverifiable"` for nearly every background
1812
+ * action, including ones that did nothing, and its `delivery_failed`
1813
+ * escalation shows up on input that arrived as well as input that did not.
1814
+ * Neither is proof, so only a `confirmed` effect is verified, and anything
1815
+ * else says "sent, not confirmed".
657
1816
  */
658
- export function actResult(result) {
1817
+ export function inputDelivery(result) {
659
1818
  const facts = result.structuredContent ?? {};
660
1819
  switch (facts.effect) {
661
- case 'suspected_noop':
662
- return {
663
- ok: false,
664
- detail: 'the control did not change; the action may not have reached it',
665
- };
666
1820
  case 'refused': {
667
1821
  const refusal = facts.refusal;
668
- return {
669
- ok: false,
670
- detail: typeof refusal?.message === 'string' ? refusal.message : 'cua-driver refused the action',
671
- };
1822
+ return verdict('not_delivered', 'safe', typeof refusal?.message === 'string' ? refusal.message : 'cua-driver refused the action');
1823
+ }
1824
+ case 'confirmed':
1825
+ return verdict('delivered_verified', 'unsafe');
1826
+ case 'suspected_noop':
1827
+ return verdict('delivered_unverified', 'unsafe', 'the driver suspects the input changed nothing; it may not have reached the target. Look at the window before repeating it.');
1828
+ default: {
1829
+ const escalation = facts.escalation;
1830
+ return verdict('delivered_unverified', 'unsafe', escalation?.reason === 'delivery_failed'
1831
+ ? '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".'
1832
+ : undefined);
672
1833
  }
673
- default:
674
- return { ok: true };
675
1834
  }
676
1835
  }
677
- /** Why a tool call failed, in words that tell the model what to do next. */
678
- function toolRefusal(error) {
679
- if (/stale/i.test(error.message))
680
- return 'that control is from an older UI snapshot; take a new one';
681
- return error.message.length > 300 ? `${error.message.slice(0, 299)}…` : error.message;
1836
+ /**
1837
+ * A driver tool error → what it means for delivery. A refusal the driver
1838
+ * names means it did not send the input (safe to repeat once the cause is
1839
+ * fixed). Any other error leaves the outcome unknown: it is reported as
1840
+ * unverified and unsafe to repeat.
1841
+ */
1842
+ export function failureDelivery(error) {
1843
+ const facts = error.structuredContent ?? {};
1844
+ const code = typeof facts.code === 'string' ? facts.code : undefined;
1845
+ if (code === 'background_unavailable' ||
1846
+ code === 'background_occluded' ||
1847
+ code === 'background_uipi_blocked')
1848
+ return verdict('not_delivered', 'safe', code === 'background_uipi_blocked'
1849
+ ? '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.'
1850
+ : code === 'background_occluded'
1851
+ ? 'the target is covered by another window, so background input cannot reach it. Nothing was sent.'
1852
+ : '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".');
1853
+ if (facts.status === 'refused') {
1854
+ const refusal = facts.refusal;
1855
+ return verdict('not_delivered', 'safe', typeof refusal?.message === 'string' ? refusal.message : error.message);
1856
+ }
1857
+ if (/stale (window|screenshot)/i.test(error.message))
1858
+ return verdict('not_delivered', 'safe', trimText(error.message, 300));
1859
+ if (/stale/i.test(`${error.message} ${JSON.stringify(facts)}`))
1860
+ return verdict('not_delivered', 'safe', 'that control is from an older UI snapshot; take a new one');
1861
+ // An error the driver does not classify can arrive after input was sent (a
1862
+ // foreground burst calls this too), so it never invites a blind resend.
1863
+ return verdict('delivered_unverified', 'unsafe', `${trimText(error.message, 300)} The input may have been sent; look at the window before repeating it.`);
1864
+ }
1865
+ /** The driver refused a handle a newer read of its window replaced (nothing was sent). */
1866
+ function isStaleHandle(error) {
1867
+ if (/stale (window|screenshot)/i.test(error.message))
1868
+ return false;
1869
+ return /stale_element_token|stale (UI|element)/i.test(`${error.message} ${JSON.stringify(error.structuredContent ?? {})}`);
1870
+ }
1871
+ /** Refusals that a foreground delivery can cure. `uipi_blocked` is not one: it blocks foreground input too. */
1872
+ function foregroundCures(error) {
1873
+ const code = error.structuredContent?.code;
1874
+ return code === 'background_unavailable' || code === 'background_occluded';
1875
+ }
1876
+ function failureResult(error) {
1877
+ const { delivery, retrySafety, detail } = failureDelivery(error);
1878
+ return {
1879
+ ok: false,
1880
+ delivery,
1881
+ retrySafety,
1882
+ ...(detail !== undefined ? { detail } : {}),
1883
+ };
1884
+ }
1885
+ /**
1886
+ * cua-driver's action result → the host's. `unverifiable` is the driver's
1887
+ * answer to almost everything it does in the background, so a result that
1888
+ * returned is "sent", and the stateful actions are judged by reading the
1889
+ * control back.
1890
+ */
1891
+ export function actResult(result) {
1892
+ const sent = inputDelivery(result);
1893
+ return {
1894
+ ok: sent.delivery !== 'not_delivered' && result.structuredContent?.effect !== 'suspected_noop',
1895
+ delivery: sent.delivery,
1896
+ retrySafety: sent.retrySafety,
1897
+ ...(sent.detail !== undefined ? { detail: sent.detail } : {}),
1898
+ };
1899
+ }
1900
+ const same = (a, b) => a.trim() === b.trim();
1901
+ /** set_value, judged by the field as a fresh read shows it. */
1902
+ export function judgeSetValue(before, expected, after) {
1903
+ if (!after)
1904
+ return {
1905
+ ok: true,
1906
+ delivery: 'delivered_unverified',
1907
+ retrySafety: 'unsafe',
1908
+ detail: 'the value was sent, but the field could not be read back (the window may have changed). Check it before setting it again.',
1909
+ };
1910
+ if (after.value === undefined)
1911
+ return {
1912
+ ok: true,
1913
+ delivery: 'delivered_unverified',
1914
+ retrySafety: 'unsafe',
1915
+ detail: 'the value was sent; this control does not report its value, so it could not be checked. Look at the window.',
1916
+ };
1917
+ if (same(after.value, expected))
1918
+ return {
1919
+ ok: true,
1920
+ delivery: 'delivered_verified',
1921
+ retrySafety: 'safe',
1922
+ readBack: {
1923
+ expected: trimText(expected),
1924
+ observed: trimText(after.value),
1925
+ },
1926
+ };
1927
+ if (before.value !== undefined && same(before.value, after.value))
1928
+ return {
1929
+ ok: false,
1930
+ delivery: 'not_delivered',
1931
+ retrySafety: 'safe',
1932
+ readBack: {
1933
+ expected: trimText(expected),
1934
+ observed: trimText(after.value),
1935
+ },
1936
+ 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.`,
1937
+ };
1938
+ return {
1939
+ ok: true,
1940
+ delivery: 'delivered_unverified',
1941
+ retrySafety: 'unsafe',
1942
+ readBack: { expected: trimText(expected), observed: trimText(after.value) },
1943
+ 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.`,
1944
+ };
1945
+ }
1946
+ /** toggle, judged by whether the control's selected state flipped. */
1947
+ export function judgeToggle(before, after) {
1948
+ if (!after)
1949
+ return {
1950
+ ok: true,
1951
+ delivery: 'delivered_unverified',
1952
+ retrySafety: 'unsafe',
1953
+ detail: 'the toggle was sent, but the control could not be read back. A second toggle would undo it; check first.',
1954
+ };
1955
+ if (after.selected !== before.selected)
1956
+ return {
1957
+ ok: true,
1958
+ delivery: 'delivered_verified',
1959
+ retrySafety: 'unsafe',
1960
+ readBack: {
1961
+ expected: String(!before.selected),
1962
+ observed: String(after.selected),
1963
+ },
1964
+ };
1965
+ return {
1966
+ ok: true,
1967
+ delivery: 'delivered_unverified',
1968
+ retrySafety: 'unsafe',
1969
+ readBack: { observed: String(after.selected) },
1970
+ detail: '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.',
1971
+ };
1972
+ }
1973
+ const ITEM_ROLES = /^(ListItem|TreeItem|DataItem)$/;
1974
+ const SELECT_REFUSALS = {
1975
+ gone: 'the window is gone',
1976
+ not_found: 'the row is not in the window any more',
1977
+ ambiguous: 'more than one row matches',
1978
+ no_pattern: 'the row has no selection pattern',
1979
+ refused: 'the program refused the selection',
1980
+ };
1981
+ /** 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). */
1982
+ export function judgeSelect(_before, after) {
1983
+ if (after?.selected === true)
1984
+ return {
1985
+ ok: true,
1986
+ delivery: 'delivered_verified',
1987
+ retrySafety: 'unsafe',
1988
+ readBack: { expected: 'selected', observed: 'selected' },
1989
+ };
1990
+ return {
1991
+ ok: true,
1992
+ delivery: 'delivered_unverified',
1993
+ retrySafety: 'unsafe',
1994
+ ...(after ? { readBack: { expected: 'selected', observed: 'not selected' } } : {}),
1995
+ detail: `the click was sent, but the control does not read as selected${after ? '' : ' (it could not be read back)'}.`,
1996
+ };
682
1997
  }
683
1998
  /** `0x…` hex, the form `bring_to_front` reports and `WindowInfo.id` carries. */
684
1999
  export function windowIdOf(hwnd) {