@namzu/computer-use 4.4.0 → 4.6.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 (139) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/SubprocessComputerUseHost.d.ts +8 -1
  3. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  4. package/dist/SubprocessComputerUseHost.js +15 -4
  5. package/dist/SubprocessComputerUseHost.js.map +1 -1
  6. package/dist/a11y/a11y.d.ts +15 -7
  7. package/dist/a11y/a11y.d.ts.map +1 -1
  8. package/dist/a11y/a11y.js +12 -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/macos-helper.d.ts +80 -0
  15. package/dist/a11y/macos-helper.d.ts.map +1 -0
  16. package/dist/a11y/macos-helper.js +436 -0
  17. package/dist/a11y/macos-helper.js.map +1 -0
  18. package/dist/a11y/macos-signing.d.ts +56 -0
  19. package/dist/a11y/macos-signing.d.ts.map +1 -0
  20. package/dist/a11y/macos-signing.js +228 -0
  21. package/dist/a11y/macos-signing.js.map +1 -0
  22. package/dist/a11y/macos.d.ts +173 -0
  23. package/dist/a11y/macos.d.ts.map +1 -0
  24. package/dist/a11y/macos.js +271 -0
  25. package/dist/a11y/macos.js.map +1 -0
  26. package/dist/a11y/windows.d.ts +14 -2
  27. package/dist/a11y/windows.d.ts.map +1 -1
  28. package/dist/a11y/windows.js +31 -6
  29. package/dist/a11y/windows.js.map +1 -1
  30. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  31. package/dist/adapters/cua-driver/adapter.js +48 -10
  32. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  33. package/dist/adapters/cua-driver/ui-tree.d.ts +1 -0
  34. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  35. package/dist/adapters/cua-driver/ui-tree.js +2 -0
  36. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  37. package/dist/adapters/darwin-ax.d.ts +94 -0
  38. package/dist/adapters/darwin-ax.d.ts.map +1 -0
  39. package/dist/adapters/darwin-ax.js +754 -0
  40. package/dist/adapters/darwin-ax.js.map +1 -0
  41. package/dist/adapters/darwin.d.ts +43 -2
  42. package/dist/adapters/darwin.d.ts.map +1 -1
  43. package/dist/adapters/darwin.js +145 -7
  44. package/dist/adapters/darwin.js.map +1 -1
  45. package/dist/adapters/png.d.ts +6 -0
  46. package/dist/adapters/png.d.ts.map +1 -0
  47. package/dist/adapters/png.js +7 -0
  48. package/dist/adapters/png.js.map +1 -0
  49. package/dist/adapters/win32-native.d.ts +53 -0
  50. package/dist/adapters/win32-native.d.ts.map +1 -0
  51. package/dist/adapters/win32-native.js +279 -0
  52. package/dist/adapters/win32-native.js.map +1 -0
  53. package/dist/adapters/win32.d.ts +19 -1
  54. package/dist/adapters/win32.d.ts.map +1 -1
  55. package/dist/adapters/win32.js +35 -8
  56. package/dist/adapters/win32.js.map +1 -1
  57. package/dist/foreground/ladder.d.ts.map +1 -1
  58. package/dist/foreground/ladder.js +5 -1
  59. package/dist/foreground/ladder.js.map +1 -1
  60. package/dist/foreground/types.d.ts +6 -0
  61. package/dist/foreground/types.d.ts.map +1 -1
  62. package/dist/foreground/types.js.map +1 -1
  63. package/dist/foreground/windows.d.ts +2 -0
  64. package/dist/foreground/windows.d.ts.map +1 -1
  65. package/dist/foreground/windows.js +24 -11
  66. package/dist/foreground/windows.js.map +1 -1
  67. package/dist/index.d.ts +9 -0
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +7 -0
  70. package/dist/index.js.map +1 -1
  71. package/dist/native/a11y.d.ts +61 -0
  72. package/dist/native/a11y.d.ts.map +1 -0
  73. package/dist/native/a11y.js +197 -0
  74. package/dist/native/a11y.js.map +1 -0
  75. package/dist/native/env.d.ts +19 -0
  76. package/dist/native/env.d.ts.map +1 -0
  77. package/dist/native/env.js +29 -0
  78. package/dist/native/env.js.map +1 -0
  79. package/dist/native/foreground-monitor.d.ts +51 -0
  80. package/dist/native/foreground-monitor.d.ts.map +1 -0
  81. package/dist/native/foreground-monitor.js +120 -0
  82. package/dist/native/foreground-monitor.js.map +1 -0
  83. package/dist/native/presence.d.ts +24 -0
  84. package/dist/native/presence.d.ts.map +1 -0
  85. package/dist/native/presence.js +47 -0
  86. package/dist/native/presence.js.map +1 -0
  87. package/dist/native/process.d.ts +73 -0
  88. package/dist/native/process.d.ts.map +1 -0
  89. package/dist/native/process.js +302 -0
  90. package/dist/native/process.js.map +1 -0
  91. package/dist/native/protocol.d.ts +476 -0
  92. package/dist/native/protocol.d.ts.map +1 -0
  93. package/dist/native/protocol.js +601 -0
  94. package/dist/native/protocol.js.map +1 -0
  95. package/dist/native/shared.d.ts +16 -0
  96. package/dist/native/shared.d.ts.map +1 -0
  97. package/dist/native/shared.js +62 -0
  98. package/dist/native/shared.js.map +1 -0
  99. package/dist/native/watch.d.ts +35 -0
  100. package/dist/native/watch.d.ts.map +1 -0
  101. package/dist/native/watch.js +45 -0
  102. package/dist/native/watch.js.map +1 -0
  103. package/dist/presence/presence.d.ts +3 -2
  104. package/dist/presence/presence.d.ts.map +1 -1
  105. package/dist/presence/presence.js.map +1 -1
  106. package/dist/presence/windows.d.ts +2 -0
  107. package/dist/presence/windows.d.ts.map +1 -1
  108. package/dist/presence/windows.js +15 -0
  109. package/dist/presence/windows.js.map +1 -1
  110. package/helper-macos/main.swift +1756 -0
  111. package/package.json +3 -2
  112. package/src/SubprocessComputerUseHost.ts +26 -2
  113. package/src/a11y/a11y.ts +25 -11
  114. package/src/a11y/index.ts +28 -1
  115. package/src/a11y/macos-helper.ts +538 -0
  116. package/src/a11y/macos-signing.ts +280 -0
  117. package/src/a11y/macos.ts +496 -0
  118. package/src/a11y/windows.ts +31 -4
  119. package/src/adapters/cua-driver/adapter.ts +55 -15
  120. package/src/adapters/cua-driver/ui-tree.ts +2 -0
  121. package/src/adapters/darwin-ax.ts +920 -0
  122. package/src/adapters/darwin.ts +184 -4
  123. package/src/adapters/png.ts +5 -0
  124. package/src/adapters/win32-native.ts +329 -0
  125. package/src/adapters/win32.ts +53 -5
  126. package/src/foreground/ladder.ts +5 -1
  127. package/src/foreground/types.ts +6 -0
  128. package/src/foreground/windows.ts +25 -11
  129. package/src/index.ts +14 -0
  130. package/src/native/a11y.ts +267 -0
  131. package/src/native/env.ts +33 -0
  132. package/src/native/foreground-monitor.ts +165 -0
  133. package/src/native/presence.ts +58 -0
  134. package/src/native/process.ts +347 -0
  135. package/src/native/protocol.ts +1103 -0
  136. package/src/native/shared.ts +75 -0
  137. package/src/native/watch.ts +78 -0
  138. package/src/presence/presence.ts +3 -2
  139. package/src/presence/windows.ts +15 -0
@@ -8,10 +8,21 @@ import type {
8
8
  ComputerUseResult,
9
9
  DisplayGeometry,
10
10
  DisplayInfo,
11
+ FocusWindowResult,
11
12
  Point,
12
13
  ScreenshotResult,
14
+ UiActResult,
15
+ UiElementAction,
16
+ UiSnapshot,
17
+ UiSnapshotOptions,
18
+ WindowInfo,
19
+ WindowInputAction,
20
+ WindowInputResult,
21
+ WindowScreenshotResult,
13
22
  } from '@namzu/sdk'
23
+ import type { MacA11yHandle } from '../a11y/macos.js'
14
24
  import { hasExecutable, runCommand, runCommandOrThrow } from '../util/spawn.js'
25
+ import { MacAxSurface, type PickFileResult } from './darwin-ax.js'
15
26
  import { ActionCapabilityError, type Adapter, AdapterUnavailableError } from './types.js'
16
27
 
17
28
  // ---------------------------------------------------------------------------
@@ -66,6 +77,57 @@ const MODIFIER_ALIASES: Readonly<Record<string, 'command' | 'control' | 'option'
66
77
  shift: 'shift',
67
78
  }
68
79
 
80
+ /** Virtual key codes of the printable keys on a US layout, for shortcuts (`cmd+a`). */
81
+ const ANSI_KEY_CODES: Readonly<Record<string, number>> = {
82
+ a: 0,
83
+ s: 1,
84
+ d: 2,
85
+ f: 3,
86
+ h: 4,
87
+ g: 5,
88
+ z: 6,
89
+ x: 7,
90
+ c: 8,
91
+ v: 9,
92
+ b: 11,
93
+ q: 12,
94
+ w: 13,
95
+ e: 14,
96
+ r: 15,
97
+ y: 16,
98
+ t: 17,
99
+ '1': 18,
100
+ '2': 19,
101
+ '3': 20,
102
+ '4': 21,
103
+ '6': 22,
104
+ '5': 23,
105
+ '=': 24,
106
+ '9': 25,
107
+ '7': 26,
108
+ '-': 27,
109
+ '8': 28,
110
+ '0': 29,
111
+ ']': 30,
112
+ o: 31,
113
+ u: 32,
114
+ '[': 33,
115
+ i: 34,
116
+ p: 35,
117
+ l: 37,
118
+ j: 38,
119
+ "'": 39,
120
+ k: 40,
121
+ ';': 41,
122
+ '\\': 42,
123
+ ',': 43,
124
+ '/': 44,
125
+ n: 45,
126
+ m: 46,
127
+ '.': 47,
128
+ '`': 50,
129
+ }
130
+
69
131
  interface ParsedKeyCombo {
70
132
  readonly modifiers: readonly ('command' | 'control' | 'option' | 'shift')[]
71
133
  readonly mainKey: string
@@ -89,6 +151,14 @@ export function parseKeyCombo(input: string): ParsedKeyCombo {
89
151
  return { modifiers: mods, mainKey }
90
152
  }
91
153
 
154
+ /** A key combination as a virtual key code and modifier names, for events posted to a window. */
155
+ export function keyEventOf(input: string): { code: number; flags: readonly string[] } {
156
+ const { modifiers, mainKey } = parseKeyCombo(input)
157
+ const code = KEY_CODES[mainKey.toLowerCase()] ?? ANSI_KEY_CODES[mainKey.toLowerCase()]
158
+ if (code === undefined) throw new Error(`DarwinAdapter: unknown key "${mainKey}"`)
159
+ return { code, flags: modifiers }
160
+ }
161
+
92
162
  function modifiersClause(mods: readonly ('command' | 'control' | 'option' | 'shift')[]): string {
93
163
  if (mods.length === 0) return ''
94
164
  const items = mods.map((m) => `${m} down`)
@@ -125,6 +195,13 @@ async function probe(): Promise<ProbeResult> {
125
195
  // Adapter
126
196
  // ---------------------------------------------------------------------------
127
197
 
198
+ export interface DarwinAdapterOptions {
199
+ /** The accessibility helper; absent, windows, the tree and scroll are not offered. */
200
+ readonly ax?: MacA11yHandle
201
+ /** For tests: pixels per point instead of the display's. */
202
+ readonly scale?: () => Promise<number>
203
+ }
204
+
128
205
  /**
129
206
  * Units: the host contract is physical pixels. `screencapture` writes the
130
207
  * backing store (2880x1800 on a 1440x900-point Retina panel), while
@@ -145,9 +222,25 @@ export class DarwinAdapter implements Adapter {
145
222
  /** Captured pixels per point on the main display, from the latest capture. */
146
223
  private pixelsPerPoint: number | undefined
147
224
 
148
- private constructor(probeResult: ProbeResult) {
225
+ private readonly ax: MacAxSurface | undefined
226
+ readonly backend: string
227
+ readonly fallbackReason: string | undefined
228
+
229
+ private constructor(probeResult: ProbeResult, ax?: MacAxSurface, note?: string) {
149
230
  this.hasCliclick = probeResult.hasCliclick
231
+ this.ax = ax
232
+ this.backend = ax ? 'osascript + namzu-helper' : 'osascript'
233
+ this.fallbackReason = note
150
234
  this.capabilities = Object.freeze({
235
+ ...(ax
236
+ ? {
237
+ windows: true,
238
+ windowCapture: true,
239
+ windowScroll: true,
240
+ uiTree: true,
241
+ maxClickCount: 3 as const,
242
+ }
243
+ : {}),
151
244
  displayServer: 'darwin',
152
245
  screenshot: probeResult.hasScreencapture,
153
246
  mouse: probeResult.hasOsascript,
@@ -162,6 +255,7 @@ export class DarwinAdapter implements Adapter {
162
255
  ...(probeResult.hasCliclick
163
256
  ? ['cursor_position' as const, 'mouse_move' as const, 'mouse_drag' as const]
164
257
  : []),
258
+ ...(ax ? ['scroll' as const] : []),
165
259
  ]),
166
260
  mouseClickButtons: Object.freeze(
167
261
  probeResult.hasCliclick ? ['left' as const, 'right' as const] : ['left' as const],
@@ -170,7 +264,11 @@ export class DarwinAdapter implements Adapter {
170
264
  })
171
265
  }
172
266
 
173
- static async create(): Promise<DarwinAdapter> {
267
+ /**
268
+ * `options.ax` is the accessibility helper's host (see `createMacA11yHost`); it is built and started
269
+ * here, and when it cannot be the adapter works as before, with `fallbackReason` saying why.
270
+ */
271
+ static async create(options: DarwinAdapterOptions = {}): Promise<DarwinAdapter> {
174
272
  const probeResult = await probe()
175
273
  const missing: string[] = []
176
274
  if (!probeResult.hasScreencapture) missing.push('screencapture')
@@ -181,7 +279,85 @@ export class DarwinAdapter implements Adapter {
181
279
  missing,
182
280
  )
183
281
  }
184
- return new DarwinAdapter(probeResult)
282
+ let surface: MacAxSurface | undefined
283
+ let note: string | undefined
284
+ if (options.ax) {
285
+ const prepared = await options.ax.prepare()
286
+ if (prepared.ok) {
287
+ const adapterScale = options.scale
288
+ surface = new MacAxSurface({
289
+ host: options.ax.host,
290
+ scale: adapterScale ?? (async () => (await readMainDisplay()).scaleFactor),
291
+ keyEvent: keyEventOf,
292
+ })
293
+ const perms = await options.ax.host.permissions().catch(() => undefined)
294
+ if (perms && perms.steps.length > 0)
295
+ note = `${perms.app} still needs permission: ${perms.steps.join(' ')}`
296
+ } else {
297
+ note = `the macOS accessibility helper is not in use: ${prepared.reason}`
298
+ }
299
+ }
300
+ const adapter = new DarwinAdapter(probeResult, surface, note)
301
+ if (surface && !options.scale) surface.bindScale(() => adapter.scale())
302
+ return adapter
303
+ }
304
+
305
+ async dispose(): Promise<void> {
306
+ await this.ax?.close()
307
+ }
308
+
309
+ async release(): Promise<void> {
310
+ this.ax?.release()
311
+ }
312
+
313
+ async listWindows(): Promise<readonly WindowInfo[]> {
314
+ return this.requireAx().listWindows()
315
+ }
316
+
317
+ async focusWindow(id: string): Promise<FocusWindowResult> {
318
+ return this.requireAx().focusWindow(id)
319
+ }
320
+
321
+ async captureWindow(id: string): Promise<WindowScreenshotResult> {
322
+ return this.requireAx().captureWindow(id)
323
+ }
324
+
325
+ async executeWindow(
326
+ captureId: string,
327
+ action: WindowInputAction,
328
+ ): Promise<WindowInputResult | undefined> {
329
+ return this.requireAx().executeWindow(captureId, action)
330
+ }
331
+
332
+ async settleAfterInput(
333
+ request: { readonly windowId?: string; readonly budgetMs: number },
334
+ signal?: AbortSignal,
335
+ ): Promise<{ readonly waitedMs: number; readonly changed: boolean } | undefined> {
336
+ return this.ax?.settleAfterInput(request, signal)
337
+ }
338
+
339
+ async uiSnapshot(windowId?: string | number, options?: UiSnapshotOptions): Promise<UiSnapshot> {
340
+ return this.requireAx().uiSnapshot(windowId, options)
341
+ }
342
+
343
+ async uiAct(ref: string, action: UiElementAction, value?: string): Promise<UiActResult> {
344
+ return this.requireAx().uiAct(ref, action, value)
345
+ }
346
+
347
+ /** Picks a file in the open or save panel in front, through its accessibility tree. macOS only. */
348
+ async uiPickFile(
349
+ path: string,
350
+ options?: { readonly windowId?: string | number; readonly confirm?: boolean },
351
+ ): Promise<PickFileResult> {
352
+ return this.requireAx().pickFile(path, options)
353
+ }
354
+
355
+ private requireAx(): MacAxSurface {
356
+ if (!this.ax)
357
+ throw new AdapterUnavailableError(
358
+ this.fallbackReason ?? 'the macOS accessibility helper is not running',
359
+ )
360
+ return this.ax
185
361
  }
186
362
 
187
363
  /** The main display in physical pixels (the capture's), with pixels per point. */
@@ -243,10 +419,14 @@ export class DarwinAdapter implements Adapter {
243
419
  await this.mouseDrag(action.from, action.to)
244
420
  return { type: 'ok' }
245
421
  case 'scroll':
422
+ if (this.ax) {
423
+ await this.ax.scrollAt(action.at, action.direction, action.amount)
424
+ return { type: 'ok' }
425
+ }
246
426
  throw new ActionCapabilityError(
247
427
  action.type,
248
428
  'mouse',
249
- 'scroll is not supported on macOS without a native CoreGraphics binding; use keyboard page navigation instead',
429
+ 'scroll is not supported on macOS without the Namzu helper (it builds with the Xcode Command Line Tools); use keyboard page navigation instead',
250
430
  )
251
431
  case 'type_text':
252
432
  await this.typeText(action.text)
@@ -0,0 +1,5 @@
1
+ /** The pixel size in a PNG's header, or undefined when the bytes are not one. */
2
+ export function decodePngSize(data: Buffer): { width: number; height: number } | undefined {
3
+ if (data.length < 24 || data.readUInt32BE(0) !== 0x89504e47) return undefined
4
+ return { width: data.readUInt32BE(16), height: data.readUInt32BE(20) }
5
+ }
@@ -0,0 +1,329 @@
1
+ import { mkdirSync, mkdtempSync, readFileSync, rmSync, unlinkSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import type {
5
+ ComputerUseAction,
6
+ ComputerUseCapabilities,
7
+ ComputerUseResult,
8
+ DisplayGeometry,
9
+ DisplayInfo,
10
+ Point,
11
+ Rect,
12
+ ScreenshotResult,
13
+ } from '@namzu/sdk'
14
+ import { type A11yDisplay, A11yError } from '../a11y/interface.js'
15
+ import type { NativeWinProcessOptions } from '../native/process.js'
16
+ import type { NativeCaptureTarget, NativeInputRequest } from '../native/protocol.js'
17
+ import { type NativeHelper, shareNativeProcess } from '../native/shared.js'
18
+ import { SpawnError } from '../util/spawn.js'
19
+ import { type Adapter, AdapterUnavailableError } from './types.js'
20
+
21
+ /**
22
+ * The Windows display adapter when the native helper (`namzu-native`) is
23
+ * configured: screenshot, zoom region, click, drag, scroll, type, key,
24
+ * cursor and display geometry, each one request to a helper that is already
25
+ * running. It keeps the host contract the PowerShell adapter keeps (physical
26
+ * pixels, points relative to the display of the last capture) and replaces its
27
+ * process-per-action cost and its scripts with `SendInput` and
28
+ * Windows.Graphics.Capture calls made by a compiled program.
29
+ *
30
+ * There is no PowerShell here, and no fallback to it: when the helper cannot
31
+ * start the adapter does not exist, and the caller is told why.
32
+ */
33
+
34
+ /** What the helper must report in `hello` for this adapter to use it. */
35
+ const REQUIRED_CAPS = ['capture', 'input', 'foreground'] as const
36
+
37
+ /** How long a helper may take over one display call, ms. */
38
+ const REQUEST_MS = 8_000
39
+
40
+ /** Errors after which the input may already have reached the desktop. */
41
+ const OUTCOME_UNKNOWN = new Set(['timeout', 'helper_exited', 'bad_reply', 'input_blocked'])
42
+
43
+ export interface NativeWin32AdapterOptions extends NativeWinProcessOptions {
44
+ /**
45
+ * A directory the helper writes pictures into, made when missing. Default:
46
+ * a new private directory under the system's temporary one, removed on dispose.
47
+ */
48
+ readonly captureDir?: string
49
+ /**
50
+ * The path as the helper reads it: under WSL a Linux path goes through the
51
+ * distro's share. Default: the path as it is.
52
+ */
53
+ readonly toHelperPath?: (path: string) => string
54
+ }
55
+
56
+ function toDisplayInfo(d: A11yDisplay): DisplayInfo {
57
+ return {
58
+ id: d.id,
59
+ x: d.bounds.x,
60
+ y: d.bounds.y,
61
+ width: d.bounds.width,
62
+ height: d.bounds.height,
63
+ scaleFactor: d.scale,
64
+ primary: d.primary,
65
+ }
66
+ }
67
+
68
+ /** The last part of a path written with either separator. */
69
+ function baseName(path: string): string {
70
+ return path.split(/[\\/]/).pop() ?? path
71
+ }
72
+
73
+ export class NativeWin32Adapter implements Adapter {
74
+ readonly capabilities: ComputerUseCapabilities
75
+ readonly backend: string
76
+ private readonly ownsDir: boolean
77
+ /** The display points are relative to: the one of the last capture. */
78
+ private display: DisplayInfo | undefined
79
+
80
+ private constructor(
81
+ private readonly process: NativeHelper,
82
+ private readonly dir: string,
83
+ private readonly helperDir: string,
84
+ ownsDir: boolean,
85
+ private readonly executable: string,
86
+ ) {
87
+ this.ownsDir = ownsDir
88
+ this.backend = `namzu-native ${process.hello?.version ?? ''}`.trim()
89
+ this.capabilities = Object.freeze({
90
+ displayServer: 'win32',
91
+ screenshot: true,
92
+ mouse: true,
93
+ keyboard: true,
94
+ cursorPosition: true,
95
+ clipboard: false,
96
+ supportedActions: Object.freeze([
97
+ 'screenshot' as const,
98
+ 'cursor_position' as const,
99
+ 'mouse_move' as const,
100
+ 'mouse_click' as const,
101
+ 'mouse_drag' as const,
102
+ 'scroll' as const,
103
+ 'type_text' as const,
104
+ 'key' as const,
105
+ ]),
106
+ mouseClickButtons: Object.freeze(['left', 'right', 'middle'] as const),
107
+ mouseDragButtons: Object.freeze(['left', 'right', 'middle'] as const),
108
+ maxClickCount: 3,
109
+ regionCapture: true,
110
+ })
111
+ }
112
+
113
+ /**
114
+ * Starts the helper and checks it can do what this adapter needs. Throws
115
+ * {@link AdapterUnavailableError} when it cannot.
116
+ */
117
+ static async create(options: NativeWin32AdapterOptions): Promise<NativeWin32Adapter> {
118
+ const process = shareNativeProcess(options)
119
+ if (!(await process.ready())) {
120
+ throw new AdapterUnavailableError(
121
+ `Win32Adapter: the native helper did not start (${options.executable})`,
122
+ )
123
+ }
124
+ const caps = process.hello?.caps ?? []
125
+ const missing = REQUIRED_CAPS.filter((c) => !caps.includes(c))
126
+ if (missing.length > 0) {
127
+ await process.close()
128
+ throw new AdapterUnavailableError(
129
+ `Win32Adapter: the native helper cannot ${missing.join(', ')}; it is older than this program`,
130
+ [...missing],
131
+ )
132
+ }
133
+ const ownsDir = options.captureDir === undefined
134
+ const dir = options.captureDir ?? mkdtempSync(join(tmpdir(), 'namzu-native-'))
135
+ if (!ownsDir) mkdirSync(dir, { recursive: true })
136
+ const helperDir = (options.toHelperPath ?? ((p: string) => p))(dir)
137
+ return new NativeWin32Adapter(process, dir, helperDir, ownsDir, options.executable)
138
+ }
139
+
140
+ /**
141
+ * One input. A helper that stopped answering after it was sent leaves the
142
+ * desktop in a state nobody knows, which the host reports as an unknown
143
+ * outcome (the same `SpawnError` the script path throws), never as a
144
+ * failure that is safe to repeat.
145
+ */
146
+ private async sendInput(request: NativeInputRequest): Promise<void> {
147
+ try {
148
+ await this.process.request(request, REQUEST_MS)
149
+ } catch (error) {
150
+ if (error instanceof A11yError && OUTCOME_UNKNOWN.has(error.code)) {
151
+ throw new SpawnError(
152
+ `namzu-native input: ${error.message}`,
153
+ {
154
+ exitCode: -1,
155
+ stdout: Buffer.alloc(0),
156
+ stderr: error.message,
157
+ timedOut: error.code === 'timeout',
158
+ signal: null,
159
+ },
160
+ this.executable,
161
+ ['input'],
162
+ )
163
+ }
164
+ if (error instanceof A11yError) throw new Error(`namzu-native input: ${error.message}`)
165
+ throw error
166
+ }
167
+ }
168
+
169
+ private async displays(): Promise<readonly DisplayInfo[]> {
170
+ const reply = await this.process.request({ op: 'displays' }, REQUEST_MS)
171
+ return reply.displays.map(toDisplayInfo)
172
+ }
173
+
174
+ private async primary(): Promise<DisplayInfo> {
175
+ const all = await this.displays()
176
+ const found = all.find((d) => d.primary) ?? all[0]
177
+ if (!found) throw new Error('namzu-native: the helper lists no display')
178
+ return found
179
+ }
180
+
181
+ /** The display points are relative to; the primary one before any capture. */
182
+ private async origin(): Promise<DisplayInfo> {
183
+ this.display ??= await this.primary()
184
+ return this.display
185
+ }
186
+
187
+ async getDisplayGeometry(): Promise<DisplayGeometry> {
188
+ const d = await this.primary()
189
+ this.display = d
190
+ return { width: d.width, height: d.height, scaleFactor: d.scaleFactor }
191
+ }
192
+
193
+ /** Takes the picture the helper wrote and removes its file. */
194
+ private takePicture(path: string): Buffer {
195
+ const local = join(this.dir, baseName(path))
196
+ try {
197
+ return readFileSync(local)
198
+ } finally {
199
+ try {
200
+ unlinkSync(local)
201
+ } catch {
202
+ // Already gone.
203
+ }
204
+ }
205
+ }
206
+
207
+ private async shot(target: NativeCaptureTarget, region?: Rect): Promise<ScreenshotResult> {
208
+ const picture = await this.process.request(
209
+ { op: 'capture', target, into: this.helperDir },
210
+ REQUEST_MS,
211
+ )
212
+ if (picture.path === undefined)
213
+ throw new Error('namzu-native capture: the helper sent no picture')
214
+ const data = this.takePicture(picture.path)
215
+ const all = await this.displays()
216
+ const shown = all.find((d) => d.id === picture.display) ?? all.find((d) => d.primary) ?? all[0]
217
+ if (!shown) throw new Error('namzu-native: the helper lists no display')
218
+ if (!region) this.display = shown
219
+ return {
220
+ data,
221
+ mimeType: 'image/png',
222
+ width: picture.width,
223
+ height: picture.height,
224
+ display: shown,
225
+ }
226
+ }
227
+
228
+ async captureRegion(rect: Rect): Promise<ScreenshotResult> {
229
+ // The rectangle is relative to the display of the last capture.
230
+ const origin = await this.origin()
231
+ return this.shot(
232
+ {
233
+ kind: 'region',
234
+ x: origin.x + rect.x,
235
+ y: origin.y + rect.y,
236
+ width: rect.width,
237
+ height: rect.height,
238
+ },
239
+ rect,
240
+ )
241
+ }
242
+
243
+ private async absolute(p: Point): Promise<Point> {
244
+ const origin = await this.origin()
245
+ return { x: p.x + origin.x, y: p.y + origin.y }
246
+ }
247
+
248
+ async execute(action: ComputerUseAction): Promise<ComputerUseResult> {
249
+ switch (action.type) {
250
+ case 'screenshot': {
251
+ const primary = await this.primary()
252
+ const result = await this.shot({ kind: 'display', id: primary.id })
253
+ return { type: 'screenshot', result }
254
+ }
255
+ case 'cursor_position': {
256
+ const state = await this.process.request({ op: 'foreground.get' }, REQUEST_MS)
257
+ const origin = await this.origin()
258
+ return {
259
+ type: 'cursor_position',
260
+ point: { x: state.cursor.x - origin.x, y: state.cursor.y - origin.y },
261
+ }
262
+ }
263
+ case 'mouse_move': {
264
+ const to = await this.absolute(action.to)
265
+ await this.sendInput({ op: 'input', kind: 'move', x: to.x, y: to.y })
266
+ return { type: 'ok' }
267
+ }
268
+ case 'mouse_click': {
269
+ const at = await this.absolute(action.at)
270
+ await this.sendInput({
271
+ op: 'input',
272
+ kind: 'click',
273
+ x: at.x,
274
+ y: at.y,
275
+ button: action.button,
276
+ ...(action.count !== undefined ? { count: action.count } : {}),
277
+ })
278
+ return { type: 'ok' }
279
+ }
280
+ case 'mouse_drag': {
281
+ const from = await this.absolute(action.from)
282
+ const to = await this.absolute(action.to)
283
+ await this.sendInput({
284
+ op: 'input',
285
+ kind: 'drag',
286
+ x: from.x,
287
+ y: from.y,
288
+ toX: to.x,
289
+ toY: to.y,
290
+ button: action.button,
291
+ })
292
+ return { type: 'ok' }
293
+ }
294
+ case 'scroll': {
295
+ const at = await this.absolute(action.at)
296
+ await this.sendInput({
297
+ op: 'input',
298
+ kind: 'scroll',
299
+ x: at.x,
300
+ y: at.y,
301
+ direction: action.direction,
302
+ amount: action.amount,
303
+ })
304
+ return { type: 'ok' }
305
+ }
306
+ case 'type_text':
307
+ await this.sendInput({ op: 'input', kind: 'type', text: action.text })
308
+ return { type: 'ok' }
309
+ case 'key':
310
+ await this.sendInput({ op: 'input', kind: 'key', keys: action.keys })
311
+ return { type: 'ok' }
312
+ }
313
+ }
314
+
315
+ async release(): Promise<void> {
316
+ this.process.release()
317
+ }
318
+
319
+ async dispose(): Promise<void> {
320
+ await this.process.close()
321
+ if (this.ownsDir) {
322
+ try {
323
+ rmSync(this.dir, { recursive: true, force: true })
324
+ } catch {
325
+ // Left for the system's temporary-file cleanup.
326
+ }
327
+ }
328
+ }
329
+ }