@namzu/computer-use 4.3.1 → 4.5.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 (143) hide show
  1. package/CHANGELOG.md +28 -0
  2. package/dist/SubprocessComputerUseHost.d.ts +21 -1
  3. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  4. package/dist/SubprocessComputerUseHost.js +67 -15
  5. package/dist/SubprocessComputerUseHost.js.map +1 -1
  6. package/dist/a11y/a11y.d.ts +16 -7
  7. package/dist/a11y/a11y.d.ts.map +1 -1
  8. package/dist/a11y/a11y.js +23 -5
  9. package/dist/a11y/a11y.js.map +1 -1
  10. package/dist/a11y/index.d.ts +7 -1
  11. package/dist/a11y/index.d.ts.map +1 -1
  12. package/dist/a11y/index.js +4 -1
  13. package/dist/a11y/index.js.map +1 -1
  14. package/dist/a11y/interface.d.ts +5 -0
  15. package/dist/a11y/interface.d.ts.map +1 -1
  16. package/dist/a11y/interface.js.map +1 -1
  17. package/dist/a11y/macos-helper.d.ts +80 -0
  18. package/dist/a11y/macos-helper.d.ts.map +1 -0
  19. package/dist/a11y/macos-helper.js +436 -0
  20. package/dist/a11y/macos-helper.js.map +1 -0
  21. package/dist/a11y/macos-signing.d.ts +56 -0
  22. package/dist/a11y/macos-signing.d.ts.map +1 -0
  23. package/dist/a11y/macos-signing.js +228 -0
  24. package/dist/a11y/macos-signing.js.map +1 -0
  25. package/dist/a11y/macos.d.ts +173 -0
  26. package/dist/a11y/macos.d.ts.map +1 -0
  27. package/dist/a11y/macos.js +271 -0
  28. package/dist/a11y/macos.js.map +1 -0
  29. package/dist/a11y/windows.d.ts +13 -2
  30. package/dist/a11y/windows.d.ts.map +1 -1
  31. package/dist/a11y/windows.js +29 -6
  32. package/dist/a11y/windows.js.map +1 -1
  33. package/dist/adapters/cua-driver/adapter.d.ts +26 -0
  34. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  35. package/dist/adapters/cua-driver/adapter.js +224 -13
  36. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  37. package/dist/adapters/cua-driver/client.d.ts +5 -0
  38. package/dist/adapters/cua-driver/client.d.ts.map +1 -1
  39. package/dist/adapters/cua-driver/client.js +31 -0
  40. package/dist/adapters/cua-driver/client.js.map +1 -1
  41. package/dist/adapters/cua-driver/ui-tree.d.ts +1 -0
  42. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  43. package/dist/adapters/cua-driver/ui-tree.js +2 -0
  44. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  45. package/dist/adapters/darwin-ax.d.ts +94 -0
  46. package/dist/adapters/darwin-ax.d.ts.map +1 -0
  47. package/dist/adapters/darwin-ax.js +754 -0
  48. package/dist/adapters/darwin-ax.js.map +1 -0
  49. package/dist/adapters/darwin.d.ts +43 -2
  50. package/dist/adapters/darwin.d.ts.map +1 -1
  51. package/dist/adapters/darwin.js +145 -7
  52. package/dist/adapters/darwin.js.map +1 -1
  53. package/dist/adapters/png.d.ts +6 -0
  54. package/dist/adapters/png.d.ts.map +1 -0
  55. package/dist/adapters/png.js +7 -0
  56. package/dist/adapters/png.js.map +1 -0
  57. package/dist/adapters/types.d.ts +5 -0
  58. package/dist/adapters/types.d.ts.map +1 -1
  59. package/dist/adapters/types.js.map +1 -1
  60. package/dist/adapters/win32-native.d.ts +53 -0
  61. package/dist/adapters/win32-native.d.ts.map +1 -0
  62. package/dist/adapters/win32-native.js +279 -0
  63. package/dist/adapters/win32-native.js.map +1 -0
  64. package/dist/adapters/win32.d.ts +19 -1
  65. package/dist/adapters/win32.d.ts.map +1 -1
  66. package/dist/adapters/win32.js +34 -8
  67. package/dist/adapters/win32.js.map +1 -1
  68. package/dist/foreground/guard.d.ts.map +1 -1
  69. package/dist/foreground/guard.js +2 -0
  70. package/dist/foreground/guard.js.map +1 -1
  71. package/dist/foreground/ladder.d.ts.map +1 -1
  72. package/dist/foreground/ladder.js +5 -1
  73. package/dist/foreground/ladder.js.map +1 -1
  74. package/dist/foreground/types.d.ts +6 -0
  75. package/dist/foreground/types.d.ts.map +1 -1
  76. package/dist/foreground/types.js.map +1 -1
  77. package/dist/foreground/windows.d.ts +2 -0
  78. package/dist/foreground/windows.d.ts.map +1 -1
  79. package/dist/foreground/windows.js +23 -11
  80. package/dist/foreground/windows.js.map +1 -1
  81. package/dist/native/a11y.d.ts +61 -0
  82. package/dist/native/a11y.d.ts.map +1 -0
  83. package/dist/native/a11y.js +197 -0
  84. package/dist/native/a11y.js.map +1 -0
  85. package/dist/native/foreground-monitor.d.ts +51 -0
  86. package/dist/native/foreground-monitor.d.ts.map +1 -0
  87. package/dist/native/foreground-monitor.js +120 -0
  88. package/dist/native/foreground-monitor.js.map +1 -0
  89. package/dist/native/presence.d.ts +24 -0
  90. package/dist/native/presence.d.ts.map +1 -0
  91. package/dist/native/presence.js +47 -0
  92. package/dist/native/presence.js.map +1 -0
  93. package/dist/native/process.d.ts +73 -0
  94. package/dist/native/process.d.ts.map +1 -0
  95. package/dist/native/process.js +292 -0
  96. package/dist/native/process.js.map +1 -0
  97. package/dist/native/protocol.d.ts +408 -0
  98. package/dist/native/protocol.d.ts.map +1 -0
  99. package/dist/native/protocol.js +527 -0
  100. package/dist/native/protocol.js.map +1 -0
  101. package/dist/native/shared.d.ts +16 -0
  102. package/dist/native/shared.d.ts.map +1 -0
  103. package/dist/native/shared.js +62 -0
  104. package/dist/native/shared.js.map +1 -0
  105. package/dist/presence/presence.d.ts +11 -2
  106. package/dist/presence/presence.d.ts.map +1 -1
  107. package/dist/presence/presence.js +15 -0
  108. package/dist/presence/presence.js.map +1 -1
  109. package/dist/presence/windows.d.ts +2 -0
  110. package/dist/presence/windows.d.ts.map +1 -1
  111. package/dist/presence/windows.js +14 -0
  112. package/dist/presence/windows.js.map +1 -1
  113. package/helper-macos/main.swift +1756 -0
  114. package/package.json +3 -2
  115. package/src/SubprocessComputerUseHost.ts +80 -10
  116. package/src/a11y/a11y.ts +36 -11
  117. package/src/a11y/index.ts +28 -1
  118. package/src/a11y/interface.ts +5 -0
  119. package/src/a11y/macos-helper.ts +538 -0
  120. package/src/a11y/macos-signing.ts +280 -0
  121. package/src/a11y/macos.ts +496 -0
  122. package/src/a11y/windows.ts +29 -4
  123. package/src/adapters/cua-driver/adapter.ts +245 -17
  124. package/src/adapters/cua-driver/client.ts +27 -0
  125. package/src/adapters/cua-driver/ui-tree.ts +2 -0
  126. package/src/adapters/darwin-ax.ts +920 -0
  127. package/src/adapters/darwin.ts +184 -4
  128. package/src/adapters/png.ts +5 -0
  129. package/src/adapters/types.ts +5 -0
  130. package/src/adapters/win32-native.ts +328 -0
  131. package/src/adapters/win32.ts +52 -5
  132. package/src/foreground/guard.ts +1 -0
  133. package/src/foreground/ladder.ts +5 -1
  134. package/src/foreground/types.ts +6 -0
  135. package/src/foreground/windows.ts +24 -11
  136. package/src/native/a11y.ts +267 -0
  137. package/src/native/foreground-monitor.ts +165 -0
  138. package/src/native/presence.ts +58 -0
  139. package/src/native/process.ts +335 -0
  140. package/src/native/protocol.ts +963 -0
  141. package/src/native/shared.ts +75 -0
  142. package/src/presence/presence.ts +23 -2
  143. package/src/presence/windows.ts +14 -0
@@ -52,6 +52,7 @@ import { menuAcceleratorOf, translateKeyForCuaDriver } from './keys.js'
52
52
  import {
53
53
  type Observation,
54
54
  type ObservedVerdict,
55
+ changeBetween,
55
56
  judgeEdit,
56
57
  judgeEditBetween,
57
58
  judgeObserved,
@@ -141,11 +142,11 @@ const UI_MAX_ELEMENTS = 5_000
141
142
  */
142
143
  const UI_WALK_CUT_AT = Math.floor(UI_MAX_ELEMENTS * 0.95)
143
144
  /** A window with more shown controls than this is returned as an outline. */
144
- const OUTLINE_THRESHOLD = 220
145
+ const OUTLINE_THRESHOLD = 400
145
146
  /** The most controls an outline shows; the rest are counted, not listed. */
146
- const OUTLINE_BUDGET = 150
147
+ const OUTLINE_BUDGET = 300
147
148
  /** The most children of one element an outline lists; a long list is opened as a region. */
148
- const OUTLINE_PER_PARENT = 12
149
+ const OUTLINE_PER_PARENT = 20
149
150
  /** The children of a region opened by itself that one page lists. */
150
151
  const OUTLINE_PAGE = 60
151
152
  /** A browser tree this small is the window frame alone: the page has not been built yet. */
@@ -154,6 +155,8 @@ const SPARSE_TREE = 12
154
155
  const CHOICE_ROLES = /^(ComboBox|List|ListBox)$/i
155
156
  /** Waits (ms) before each read that looks for an input's effect: at once, then a little later. */
156
157
  const OBSERVE_WAITS_MS = [0, 80, 200, 450] as const
158
+ /** expand and collapse: a first read after the click, and a second one this much later that must agree. */
159
+ const EXPAND_WAITS_MS = [150, 450] as const
157
160
  /**
158
161
  * How old (ms) the window list read just before an input may be and still
159
162
  * stand for the check that the window has not moved. A list takes over a
@@ -376,6 +379,32 @@ function outlineOf(
376
379
  return { root: build(root, basePath), regions, next }
377
380
  }
378
381
 
382
+ /**
383
+ * The controls whose role is one of `roles`, with every element above them.
384
+ * Kept children carry their index in the full tree, as an outline's do, so
385
+ * refs bind to the right places.
386
+ */
387
+ function pruneByRole(root: UiElement, roles: ReadonlySet<string>): UiElement {
388
+ const walk = (element: UiElement): UiElement | undefined => {
389
+ const kept: UiElement[] = []
390
+ ;(element.children ?? []).forEach((child, index) => {
391
+ const built = walk(child)
392
+ if (!built) return
393
+ ORIGINAL_INDEX.set(built, index)
394
+ kept.push(built)
395
+ })
396
+ const matches = roles.has(element.role.toLowerCase())
397
+ if (!matches && kept.length === 0) return undefined
398
+ const { children: _children, ...rest } = element
399
+ return Object.freeze({
400
+ ...rest,
401
+ ...(kept.length > 0 ? { children: Object.freeze(kept) } : {}),
402
+ }) as UiElement
403
+ }
404
+ const { children: _children, ...bare } = root
405
+ return walk(root) ?? (Object.freeze(bare) as UiElement)
406
+ }
407
+
379
408
  /** The paths of the elements a view contains. */
380
409
  function collectShown(element: UiElement, path: readonly number[], into: Set<string>): void {
381
410
  into.add(pathKey(path))
@@ -430,6 +459,8 @@ export class CuaDriverAdapter implements Adapter {
430
459
  private driverCursorOff: boolean | undefined
431
460
  /** cua-driver's screenshot resize registry is per PID, so only this capture may drive input. */
432
461
  private windowFrame: WindowCaptureFrame | undefined
462
+ /** The process count at the last idle release, for a screenshot taken from that process. */
463
+ private releasedStarts: number | undefined
433
464
  /** Capture and scoped input must not race over cua-driver's per-PID resize ratio. */
434
465
  private windowOperation: Promise<void> = Promise.resolve()
435
466
  /** 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. */
@@ -714,6 +745,27 @@ export class CuaDriverAdapter implements Adapter {
714
745
  return this.serializeWindowOperation(() => this.captureWindowInternal(id))
715
746
  }
716
747
 
748
+ /**
749
+ * Read the window again with a screenshot, so the driver can place pixels of `frame` on it.
750
+ * True when that read has the size of the screenshot the model is looking at.
751
+ */
752
+ private async restoreDriverFrame(frame: WindowCaptureFrame): Promise<boolean> {
753
+ const hwnd = parseWindowId(frame.window.id)
754
+ if (hwnd === undefined) return false
755
+ try {
756
+ const result = await this.callTool('get_window_state', {
757
+ pid: frame.window.pid,
758
+ window_id: hwnd,
759
+ include_accessibility_tree: false,
760
+ include_screenshot: true,
761
+ })
762
+ const facts = structured(result, 'get_window_state')
763
+ return facts.screenshot_width === frame.width && facts.screenshot_height === frame.height
764
+ } catch {
765
+ return false
766
+ }
767
+ }
768
+
717
769
  private async captureWindowInternal(id: string): Promise<WindowScreenshotResult> {
718
770
  const target = await this.resolveWindow(id)
719
771
  // A failed or overlapping capture invalidates the old resize ratio even
@@ -884,6 +936,7 @@ export class CuaDriverAdapter implements Adapter {
884
936
  action: WindowInputAction,
885
937
  route: InputRoute,
886
938
  ): Promise<WindowInputResult | undefined> {
939
+ await this.carryFrameOver(captureId)
887
940
  const frame = this.windowFrame
888
941
  const watched =
889
942
  action.type === 'type_text' || action.type === 'key' || action.type === 'mouse_click'
@@ -1100,6 +1153,7 @@ export class CuaDriverAdapter implements Adapter {
1100
1153
  route: InputRoute = { foreground: false, onScreen: false },
1101
1154
  listing?: WindowListing,
1102
1155
  ): Promise<WindowInputResult | undefined> {
1156
+ await this.carryFrameOver(captureId)
1103
1157
  const frame = this.windowFrame
1104
1158
  if (!frame || frame.id !== captureId)
1105
1159
  throw new Error(
@@ -1150,7 +1204,18 @@ export class CuaDriverAdapter implements Adapter {
1150
1204
  )
1151
1205
  this.showPresence(frame, current.bounds, name, args)
1152
1206
  await this.markForSettle(target.window_id as number)
1153
- return this.callTool(name, { ...target, ...args }, undefined, undefined, undefined, frame)
1207
+ const sendOnce = () =>
1208
+ this.callTool(name, { ...target, ...args }, undefined, undefined, undefined, frame)
1209
+ try {
1210
+ return await sendOnce()
1211
+ } catch (error) {
1212
+ // The driver keeps one latest read per window, and a read of the controls (made just before
1213
+ // an input to judge it) replaces a screenshot with one that has none. It then refuses a
1214
+ // pixel input and sends nothing. The window is unchanged (checked above), so the same
1215
+ // screenshot is taken again for the driver and the input goes once more.
1216
+ if (!isNoDriverFrame(error) || !(await this.restoreDriverFrame(frame))) throw error
1217
+ return await sendOnce()
1218
+ }
1154
1219
  }
1155
1220
  // The driver's hotkey finds a shortcut only through an accelerator the window names, and refuses (sending
1156
1221
  // nothing) when there is none; the same combination as a key with modifiers is real input.
@@ -1387,15 +1452,27 @@ export class CuaDriverAdapter implements Adapter {
1387
1452
  }
1388
1453
  const viewRoot = located?.element ?? tree.root
1389
1454
  const basePath = located?.path ?? []
1455
+ const roles = new Set(
1456
+ (options.role ?? '')
1457
+ .split(',')
1458
+ .map((role) => role.trim().toLowerCase())
1459
+ .filter((role) => role.length > 0),
1460
+ )
1390
1461
  const view =
1391
- !query && visibleCount(viewRoot) > OUTLINE_THRESHOLD
1392
- ? outlineOf(
1393
- viewRoot,
1394
- basePath,
1395
- OUTLINE_BUDGET,
1396
- located ? { offset: options.offset ?? 0 } : undefined,
1397
- )
1398
- : { root: viewRoot, regions: new Set<string>(), next: undefined }
1462
+ roles.size > 0
1463
+ ? {
1464
+ root: pruneByRole(viewRoot, roles),
1465
+ regions: new Set<string>(),
1466
+ next: undefined,
1467
+ }
1468
+ : !query && visibleCount(viewRoot) > OUTLINE_THRESHOLD
1469
+ ? outlineOf(
1470
+ viewRoot,
1471
+ basePath,
1472
+ OUTLINE_BUDGET,
1473
+ located ? { offset: options.offset ?? 0 } : undefined,
1474
+ )
1475
+ : { root: viewRoot, regions: new Set<string>(), next: undefined }
1399
1476
  const shownKeys = new Set<string>()
1400
1477
  collectShown(view.root, basePath, shownKeys)
1401
1478
  const refs = this.bindRead(target, read, {
@@ -1409,8 +1486,13 @@ export class CuaDriverAdapter implements Adapter {
1409
1486
  const title = typeof state.window_title === 'string' ? state.window_title : undefined
1410
1487
  const app =
1411
1488
  typeof state.app_name === 'string' ? state.app_name.replace(/\.exe$/i, '') : undefined
1489
+ const selectedText =
1490
+ typeof state.selected_text === 'string' && state.selected_text.trim().length > 0
1491
+ ? state.selected_text.slice(0, 2_000)
1492
+ : undefined
1412
1493
  return {
1413
1494
  windowId: windowIdOf(target.hwnd),
1495
+ ...(selectedText !== undefined ? { selectedText } : {}),
1414
1496
  ...(title !== undefined ? { title } : {}),
1415
1497
  ...(app !== undefined ? { app } : {}),
1416
1498
  root,
@@ -1676,9 +1758,10 @@ export class CuaDriverAdapter implements Adapter {
1676
1758
  )
1677
1759
  try {
1678
1760
  switch (action) {
1679
- case 'invoke':
1680
1761
  case 'expand':
1681
1762
  case 'collapse':
1763
+ return await this.expandAndWatch(facts, uiRef, action)
1764
+ case 'invoke':
1682
1765
  // cua-driver's click on an element token performs the control's
1683
1766
  // own pattern in the background (Invoke, or a posted click at its
1684
1767
  // centre), with no pointer move and no change of foreground.
@@ -1987,10 +2070,7 @@ export class CuaDriverAdapter implements Adapter {
1987
2070
  const windows = await this.windowIdsOf(target.pid)
1988
2071
  // Each read of the window replaces the driver's handles: click through the refreshed one.
1989
2072
  const current = this.uiRefs.get(uiRef.ref) ?? facts
1990
- const sent = await this.clickRef(current, {
1991
- ref: uiRef.ref,
1992
- facts: current,
1993
- })
2073
+ const sent = await this.clickRef(current, { ref: uiRef.ref, facts: current })
1994
2074
  if (!sent.ok || sent.delivery !== 'delivered_unverified' || !before) return sent
1995
2075
  const seen = await this.verifyByReading(target, {
1996
2076
  typed: undefined,
@@ -2008,6 +2088,91 @@ export class CuaDriverAdapter implements Adapter {
2008
2088
  }
2009
2089
  }
2010
2090
 
2091
+ /**
2092
+ * expand or collapse, which the driver sends as a click and cannot read back: the control reports no
2093
+ * expanded state. What counts is what the window shows afterwards, and it has to still be there a
2094
+ * moment later. A menu that opened and closed again is not an expanded menu.
2095
+ */
2096
+ private async expandAndWatch(
2097
+ facts: UiRefEntry,
2098
+ uiRef: { readonly ref: string; readonly facts: UiRefEntry },
2099
+ want: 'expand' | 'collapse',
2100
+ ): Promise<UiActResult> {
2101
+ const target = { hwnd: facts.hwnd, pid: facts.pid }
2102
+ const before = await this.observe(target)
2103
+ const windows = await this.windowIdsOf(target.pid)
2104
+ // Each read of the window replaces the driver's handles: click through the refreshed one.
2105
+ const current = this.uiRefs.get(uiRef.ref) ?? facts
2106
+ const sent = await this.clickRef(current, { ref: uiRef.ref, facts: current })
2107
+ if (!sent.ok || sent.delivery === 'not_delivered') return sent
2108
+ const what = describeEvidence(current)
2109
+ const unverified = (detail: string): UiActResult => ({
2110
+ ok: true,
2111
+ delivery: 'delivered_unverified',
2112
+ retrySafety: 'unsafe',
2113
+ detail,
2114
+ })
2115
+ if (!before)
2116
+ return unverified(
2117
+ `the click on ${what} was sent, but the window could not be read to see whether it ${want === 'expand' ? 'opened' : 'closed'}. Look at the window before repeating it.`,
2118
+ )
2119
+ const readState = async (): Promise<
2120
+ { shown: string | undefined; held: boolean } | undefined
2121
+ > => {
2122
+ const newWindow = windows ? await this.newWindowOf(target.pid, windows) : undefined
2123
+ const after = await this.observe(target)
2124
+ if (!after) return undefined
2125
+ const change = changeBetween(before, after)
2126
+ const gone = windows ? await this.windowGone(target.pid, windows) : false
2127
+ if (want === 'expand') {
2128
+ const shown = newWindow?.title.trim() || change.added[0]
2129
+ return { shown, held: newWindow !== undefined || change.added.length > 0 }
2130
+ }
2131
+ return { shown: change.removed[0], held: gone || change.removed.length > 0 }
2132
+ }
2133
+ await this.settle(EXPAND_WAITS_MS[0])
2134
+ const first = await readState()
2135
+ if (!first)
2136
+ return unverified(
2137
+ `the click on ${what} was sent, but the window could not be read afterwards. Look at the window before repeating it.`,
2138
+ )
2139
+ await this.settle(EXPAND_WAITS_MS[1])
2140
+ const second = await readState()
2141
+ if (first.held && second?.held)
2142
+ return {
2143
+ ok: true,
2144
+ delivery: 'delivered_verified',
2145
+ retrySafety: 'unsafe',
2146
+ ...(second.shown !== undefined ? { readBack: { observed: trimText(second.shown) } } : {}),
2147
+ detail:
2148
+ want === 'expand'
2149
+ ? `${what} is open: the window shows what it opened, and still did a moment later.`
2150
+ : `${what} is closed: what it showed is gone, and stayed gone a moment later.`,
2151
+ }
2152
+ if (first.held && second && !second.held)
2153
+ return unverified(
2154
+ want === 'expand'
2155
+ ? `${what} opened and closed again, so it is not open now. Look at the window; a menu that closes on its own may need the keyboard (alt+letter) or a click in the foreground.`
2156
+ : `${what} looked closed, but what it showed is back. Look at the window before repeating it.`,
2157
+ )
2158
+ return unverified(
2159
+ want === 'expand'
2160
+ ? `the click on ${what} was sent, but no menu or new control showed in the window afterwards, so it may not be open. Look at the window (a window screenshot) before repeating it.`
2161
+ : `the click on ${what} was sent, but nothing in the window changed, so it may still be open. Look at the window before repeating it.`,
2162
+ )
2163
+ }
2164
+
2165
+ /** Whether a window the program had before (a popup that was open) is no longer listed. */
2166
+ private async windowGone(pid: number, known: ReadonlySet<string>): Promise<boolean> {
2167
+ try {
2168
+ const now = new Set((await this.listWindows()).filter((w) => w.pid === pid).map((w) => w.id))
2169
+ for (const id of known) if (!now.has(id)) return true
2170
+ return false
2171
+ } catch {
2172
+ return false
2173
+ }
2174
+ }
2175
+
2011
2176
  /**
2012
2177
  * A click on a control by its driver token, in the background. Where the
2013
2178
  * driver says the window cannot take background input (or is covered) the
@@ -2111,6 +2276,46 @@ export class CuaDriverAdapter implements Adapter {
2111
2276
  await this.client.dispose()
2112
2277
  }
2113
2278
 
2279
+ /**
2280
+ * Let go of the driver process (and the agent cursor it draws) while nobody is using it. The next
2281
+ * call starts it again; every screenshot and ref taken from the old process is then stale, which
2282
+ * the process counter already says.
2283
+ */
2284
+ async release(stillIdle: () => boolean = () => true): Promise<void> {
2285
+ const before = this.client.starts
2286
+ const ended = await this.client.release()
2287
+ // Nothing below runs unless the process really ended and no call began while it wound down;
2288
+ // a call that did started its own process, and its frame and helpers are not ours to clear.
2289
+ if (!ended || this.client.starts !== before || !stillIdle()) return
2290
+ // The refs read from the old process are dead. The window screenshot is kept: the model may
2291
+ // still be looking at it, and the first input on it reads the window again for the new process.
2292
+ this.windowReads.clear()
2293
+ this.releasedStarts = before
2294
+ // The helpers started beside it (the overlay, the accessibility host) are processes too; the
2295
+ // next window list starts them again.
2296
+ this.presence?.release?.()
2297
+ this.a11y?.release?.()
2298
+ }
2299
+
2300
+ /**
2301
+ * After an idle release the screenshot the model took is still the one it acts on. Read the window
2302
+ * again for the new process (the same size is required) and carry the screenshot over to it.
2303
+ */
2304
+ private async carryFrameOver(captureId: string): Promise<void> {
2305
+ const frame = this.windowFrame
2306
+ if (
2307
+ !frame ||
2308
+ frame.id !== captureId ||
2309
+ this.releasedStarts !== frame.processStarts ||
2310
+ frame.generation !== this.sessionGeneration
2311
+ )
2312
+ return
2313
+ if (!(await this.restoreDriverFrame(frame))) return
2314
+ if (this.windowFrame !== frame) return
2315
+ this.windowFrame = { ...frame, processStarts: this.client.starts }
2316
+ this.releasedStarts = undefined
2317
+ }
2318
+
2114
2319
  /** Tells the overlay where the agent is about to act in a window; never waits and never fails the action. */
2115
2320
  private showPresence(
2116
2321
  frame: WindowCaptureFrame,
@@ -2465,6 +2670,12 @@ export function failureDelivery(error: McpToolError): WindowInputResult {
2465
2670
  typeof refusal?.message === 'string' ? refusal.message : error.message,
2466
2671
  )
2467
2672
  }
2673
+ if (isNoDriverFrame(error))
2674
+ return verdict(
2675
+ 'not_delivered',
2676
+ 'safe',
2677
+ 'the driver had no screenshot of this window to place the pixels on, so nothing was sent. Take a new window screenshot and click again.',
2678
+ )
2468
2679
  if (/stale (window|screenshot)/i.test(error.message))
2469
2680
  return verdict('not_delivered', 'safe', trimText(error.message, 300))
2470
2681
  if (/stale/i.test(`${error.message} ${JSON.stringify(facts)}`))
@@ -2482,6 +2693,11 @@ export function failureDelivery(error: McpToolError): WindowInputResult {
2482
2693
  )
2483
2694
  }
2484
2695
 
2696
+ /** The driver refused a pixel input because it holds no screenshot of the window (nothing was sent). */
2697
+ function isNoDriverFrame(error: unknown): boolean {
2698
+ return error instanceof McpToolError && /No screenshot frame for/i.test(error.message)
2699
+ }
2700
+
2485
2701
  /** The driver refused a handle a newer read of its window replaced (nothing was sent). */
2486
2702
  function isStaleHandle(error: McpToolError): boolean {
2487
2703
  if (/stale (window|screenshot)/i.test(error.message)) return false
@@ -2640,6 +2856,18 @@ export function windowIdOf(hwnd: number): string {
2640
2856
  }
2641
2857
 
2642
2858
  export function parseWindowId(value: unknown): number | undefined {
2859
+ // A handle as an object ({ hwnd }, { id }, { window_id } ...) is read by the id inside it.
2860
+ if (typeof value === 'object' && value !== null && !Array.isArray(value)) {
2861
+ const record = value as Record<string, unknown>
2862
+ for (const key of ['window_id', 'windowId', 'hwnd', 'handle', 'id', 'value']) {
2863
+ if (record[key] === undefined || typeof record[key] === 'object') continue
2864
+ const found = parseWindowId(record[key])
2865
+ if (found !== undefined) return found
2866
+ }
2867
+ return undefined
2868
+ }
2869
+ if (typeof value === 'bigint')
2870
+ return value > 0n && value <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(value) : undefined
2643
2871
  if (typeof value === 'number') return Number.isSafeInteger(value) && value > 0 ? value : undefined
2644
2872
  if (typeof value !== 'string') return undefined
2645
2873
  const text = value.trim().toLowerCase()
@@ -199,6 +199,33 @@ export class McpStdioClient {
199
199
  }
200
200
  }
201
201
 
202
+ /**
203
+ * Stop the running process and keep the client: the next call starts a new one (the same path as
204
+ * after a crash). For a client nobody is using, so it holds no process while it waits.
205
+ */
206
+ async release(): Promise<boolean> {
207
+ if (this.inFlight > 0) return false
208
+ const running = this.running ?? (await this.starting?.catch(() => undefined))
209
+ if (!running) return true
210
+ if (running.exited) return true
211
+ if (this.inFlight > 0) return false
212
+ // A call that arrives while it winds down starts a new process; it never meets this one.
213
+ if (this.running === running) this.running = undefined
214
+ running.killedFor = 'dispose'
215
+ running.child.stdin.end()
216
+ let timer: NodeJS.Timeout | undefined
217
+ const late = new Promise<'late'>((resolve) => {
218
+ timer = setTimeout(() => resolve('late'), 2_000)
219
+ })
220
+ const outcome = await Promise.race([running.closed.then(() => 'closed' as const), late])
221
+ clearTimeout(timer)
222
+ if (outcome === 'late') {
223
+ running.child.kill('SIGKILL')
224
+ await running.closed
225
+ }
226
+ return true
227
+ }
228
+
202
229
  private async ensureStarted(): Promise<Running> {
203
230
  if (this.disposed) throw new Error(`${this.options.command}: the client was disposed.`)
204
231
  if (this.running && !this.running.exited) return this.running
@@ -26,6 +26,7 @@ export interface CuaUiElement {
26
26
  readonly value?: unknown
27
27
  readonly enabled?: unknown
28
28
  readonly selected?: unknown
29
+ readonly focused?: unknown
29
30
  readonly actions?: unknown
30
31
  readonly frame?: unknown
31
32
  readonly parent_index?: unknown
@@ -152,6 +153,7 @@ function fromRecord(record: CuaUiElement, automationId: string | undefined): Mut
152
153
  const states: string[] = []
153
154
  if (record.enabled === false) states.push('disabled')
154
155
  if (record.selected === true) states.push('selected')
156
+ if (record.focused === true) states.push('focused')
155
157
  const value = text(record.value)
156
158
  const bounds = boundsOf(record.frame)
157
159
  return {