@namzu/computer-use 1.4.3 → 2.0.2

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 (74) hide show
  1. package/CHANGELOG.md +54 -1
  2. package/README.md +98 -8
  3. package/dist/SubprocessComputerUseHost.d.ts +45 -5
  4. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  5. package/dist/SubprocessComputerUseHost.js +94 -8
  6. package/dist/SubprocessComputerUseHost.js.map +1 -1
  7. package/dist/adapters/cua-driver/adapter.d.ts +100 -0
  8. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -0
  9. package/dist/adapters/cua-driver/adapter.js +459 -0
  10. package/dist/adapters/cua-driver/adapter.js.map +1 -0
  11. package/dist/adapters/cua-driver/client.d.ts +108 -0
  12. package/dist/adapters/cua-driver/client.d.ts.map +1 -0
  13. package/dist/adapters/cua-driver/client.js +316 -0
  14. package/dist/adapters/cua-driver/client.js.map +1 -0
  15. package/dist/adapters/cua-driver/keys.d.ts +24 -0
  16. package/dist/adapters/cua-driver/keys.d.ts.map +1 -0
  17. package/dist/adapters/cua-driver/keys.js +106 -0
  18. package/dist/adapters/cua-driver/keys.js.map +1 -0
  19. package/dist/adapters/cua-driver/provision.d.ts +80 -0
  20. package/dist/adapters/cua-driver/provision.d.ts.map +1 -0
  21. package/dist/adapters/cua-driver/provision.js +147 -0
  22. package/dist/adapters/cua-driver/provision.js.map +1 -0
  23. package/dist/adapters/cua-driver/ui-tree.d.ts +42 -0
  24. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -0
  25. package/dist/adapters/cua-driver/ui-tree.js +187 -0
  26. package/dist/adapters/cua-driver/ui-tree.js.map +1 -0
  27. package/dist/adapters/cua-driver/zip.d.ts +6 -0
  28. package/dist/adapters/cua-driver/zip.d.ts.map +1 -0
  29. package/dist/adapters/cua-driver/zip.js +86 -0
  30. package/dist/adapters/cua-driver/zip.js.map +1 -0
  31. package/dist/adapters/darwin.d.ts +23 -0
  32. package/dist/adapters/darwin.d.ts.map +1 -1
  33. package/dist/adapters/darwin.js +96 -31
  34. package/dist/adapters/darwin.js.map +1 -1
  35. package/dist/adapters/linux-wayland.d.ts.map +1 -1
  36. package/dist/adapters/linux-wayland.js +12 -0
  37. package/dist/adapters/linux-wayland.js.map +1 -1
  38. package/dist/adapters/linux-x11.d.ts.map +1 -1
  39. package/dist/adapters/linux-x11.js +12 -0
  40. package/dist/adapters/linux-x11.js.map +1 -1
  41. package/dist/adapters/types.d.ts +23 -5
  42. package/dist/adapters/types.d.ts.map +1 -1
  43. package/dist/adapters/types.js.map +1 -1
  44. package/dist/adapters/win32-powershell.d.ts +41 -0
  45. package/dist/adapters/win32-powershell.d.ts.map +1 -0
  46. package/dist/adapters/win32-powershell.js +407 -0
  47. package/dist/adapters/win32-powershell.js.map +1 -0
  48. package/dist/adapters/win32.d.ts +39 -11
  49. package/dist/adapters/win32.d.ts.map +1 -1
  50. package/dist/adapters/win32.js +72 -311
  51. package/dist/adapters/win32.js.map +1 -1
  52. package/dist/adapters/wsl.d.ts +46 -0
  53. package/dist/adapters/wsl.d.ts.map +1 -0
  54. package/dist/adapters/wsl.js +130 -0
  55. package/dist/adapters/wsl.js.map +1 -0
  56. package/dist/index.d.ts +2 -1
  57. package/dist/index.d.ts.map +1 -1
  58. package/dist/index.js.map +1 -1
  59. package/package.json +2 -2
  60. package/src/SubprocessComputerUseHost.ts +115 -8
  61. package/src/adapters/cua-driver/adapter.ts +571 -0
  62. package/src/adapters/cua-driver/client.ts +451 -0
  63. package/src/adapters/cua-driver/keys.ts +111 -0
  64. package/src/adapters/cua-driver/provision.ts +208 -0
  65. package/src/adapters/cua-driver/ui-tree.ts +234 -0
  66. package/src/adapters/cua-driver/zip.ts +90 -0
  67. package/src/adapters/darwin.ts +124 -38
  68. package/src/adapters/linux-wayland.ts +13 -0
  69. package/src/adapters/linux-x11.ts +13 -0
  70. package/src/adapters/types.ts +29 -4
  71. package/src/adapters/win32-powershell.ts +482 -0
  72. package/src/adapters/win32.ts +112 -356
  73. package/src/adapters/wsl.ts +150 -0
  74. package/src/index.ts +5 -1
@@ -0,0 +1,482 @@
1
+ import type {
2
+ ComputerUseAction,
3
+ ComputerUseCapabilities,
4
+ ComputerUseResult,
5
+ DisplayGeometry,
6
+ DisplayInfo,
7
+ MouseButton,
8
+ Point,
9
+ ScrollDirection,
10
+ } from '@namzu/sdk'
11
+ import { hasExecutable, runCommandOrThrow } from '../util/spawn.js'
12
+ import { type Adapter, AdapterUnavailableError } from './types.js'
13
+ import { type WslProbes, isWsl, realWslProbes, wslChildEnv, wslPowerShellPath } from './wsl.js'
14
+
15
+ /**
16
+ * The Windows fallback: one `powershell.exe` per action, as this package has
17
+ * always done. It is used when cua-driver cannot be (see `./win32.ts`), so it
18
+ * keeps the host contract — physical pixels, the captured display described
19
+ * — and nothing more: no window list, and a new process (about 0.3–0.8 s)
20
+ * for every action.
21
+ */
22
+
23
+ // ---------------------------------------------------------------------------
24
+ // Key translation: our input ("ctrl+c") → PowerShell SendKeys format ("^c").
25
+ // ---------------------------------------------------------------------------
26
+
27
+ const SENDKEYS_MODIFIER: Readonly<Record<string, string>> = {
28
+ cmd: '^',
29
+ command: '^',
30
+ ctrl: '^',
31
+ control: '^',
32
+ meta: '^',
33
+ super: '^',
34
+ win: '^',
35
+ alt: '%',
36
+ option: '%',
37
+ opt: '%',
38
+ shift: '+',
39
+ }
40
+
41
+ const SENDKEYS_SPECIAL: Readonly<Record<string, string>> = {
42
+ enter: '{ENTER}',
43
+ return: '{ENTER}',
44
+ escape: '{ESC}',
45
+ esc: '{ESC}',
46
+ tab: '{TAB}',
47
+ backspace: '{BACKSPACE}',
48
+ delete: '{DELETE}',
49
+ forward_delete: '{DELETE}',
50
+ space: ' ',
51
+ up: '{UP}',
52
+ down: '{DOWN}',
53
+ left: '{LEFT}',
54
+ right: '{RIGHT}',
55
+ home: '{HOME}',
56
+ end: '{END}',
57
+ page_up: '{PGUP}',
58
+ page_down: '{PGDN}',
59
+ f1: '{F1}',
60
+ f2: '{F2}',
61
+ f3: '{F3}',
62
+ f4: '{F4}',
63
+ f5: '{F5}',
64
+ f6: '{F6}',
65
+ f7: '{F7}',
66
+ f8: '{F8}',
67
+ f9: '{F9}',
68
+ f10: '{F10}',
69
+ f11: '{F11}',
70
+ f12: '{F12}',
71
+ }
72
+
73
+ export function translateKeyToSendKeys(combo: string): string {
74
+ const parts = combo
75
+ .split('+')
76
+ .map((p) => p.trim())
77
+ .filter((p) => p.length > 0)
78
+ if (parts.length === 0) throw new Error('translateKeyToSendKeys: empty key combo')
79
+ const main = parts[parts.length - 1] ?? ''
80
+ const mods = parts.slice(0, -1)
81
+ const modifierPrefix = mods
82
+ .map((m) => {
83
+ const prefix = SENDKEYS_MODIFIER[m.toLowerCase()]
84
+ if (!prefix) throw new Error(`translateKeyToSendKeys: unknown modifier "${m}"`)
85
+ return prefix
86
+ })
87
+ .join('')
88
+ const special = SENDKEYS_SPECIAL[main.toLowerCase()]
89
+ if (special) return modifierPrefix + special
90
+ // Single printable chars pass through as-is; longer names stay literal and
91
+ // SendKeys will fall back to per-character typing.
92
+ return modifierPrefix + main
93
+ }
94
+
95
+ // ---------------------------------------------------------------------------
96
+ // One PowerShell invocation per action. The script travels as
97
+ // `-EncodedCommand` (UTF-16LE base64), so no character of it — and none of
98
+ // the text being typed — reaches a command-line parser.
99
+ // ---------------------------------------------------------------------------
100
+
101
+ /** PowerShell's `-EncodedCommand` form: the script as UTF-16LE, base64. */
102
+ export function encodePowerShellCommand(script: string): string {
103
+ return Buffer.from(script, 'utf16le').toString('base64')
104
+ }
105
+
106
+ export function powerShellArguments(script: string): string[] {
107
+ return [
108
+ '-NoLogo',
109
+ '-NoProfile',
110
+ '-NonInteractive',
111
+ '-ExecutionPolicy',
112
+ 'Bypass',
113
+ '-EncodedCommand',
114
+ encodePowerShellCommand(`$ProgressPreference = 'SilentlyContinue'\n${script}`),
115
+ ]
116
+ }
117
+
118
+ /**
119
+ * Compiled into every invocation, and the first thing each one runs: the
120
+ * process becomes per-monitor DPI aware (V2, then the Windows 8.1 API, then
121
+ * the Vista one) before it reads a bound, captures or moves anything, so
122
+ * all of those are physical pixels. Without it a display at 150 % reported
123
+ * two thirds of its size and the capture showed only its top-left part.
124
+ */
125
+ const DESKTOP_TYPE = `
126
+ if (-not ([System.Management.Automation.PSTypeName]'Namzu.Desktop').Type) {
127
+ Add-Type -TypeDefinition @"
128
+ using System;
129
+ using System.Runtime.InteropServices;
130
+ namespace Namzu {
131
+ public static class Desktop {
132
+ [DllImport("user32.dll")] static extern bool SetProcessDpiAwarenessContext(IntPtr value);
133
+ [DllImport("shcore.dll")] static extern int SetProcessDpiAwareness(int value);
134
+ [DllImport("user32.dll")] static extern bool SetProcessDPIAware();
135
+ [DllImport("user32.dll")] static extern IntPtr MonitorFromPoint(POINT pt, uint flags);
136
+ [DllImport("shcore.dll")] static extern int GetDpiForMonitor(IntPtr monitor, int type, out uint x, out uint y);
137
+ [StructLayout(LayoutKind.Sequential)] public struct POINT { public int X; public int Y; }
138
+ [StructLayout(LayoutKind.Sequential)]
139
+ public struct MOUSEINPUT { public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
140
+ [StructLayout(LayoutKind.Sequential)]
141
+ public struct KEYBDINPUT { public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo; }
142
+ [StructLayout(LayoutKind.Explicit)]
143
+ public struct INPUTUNION { [FieldOffset(0)] public MOUSEINPUT mi; [FieldOffset(0)] public KEYBDINPUT ki; }
144
+ [StructLayout(LayoutKind.Sequential)]
145
+ public struct INPUT { public uint type; public INPUTUNION u; }
146
+ [DllImport("user32.dll", SetLastError = true)] static extern uint SendInput(uint n, INPUT[] inputs, int size);
147
+ [DllImport("user32.dll")] public static extern bool SetCursorPos(int x, int y);
148
+ public static void MakeDpiAware() {
149
+ try { if (SetProcessDpiAwarenessContext(new IntPtr(-4))) return; } catch (Exception) {}
150
+ try { if (SetProcessDpiAwareness(2) == 0) return; } catch (Exception) {}
151
+ try { SetProcessDPIAware(); } catch (Exception) {}
152
+ }
153
+ public static double PrimaryScale() {
154
+ try {
155
+ uint x, y;
156
+ IntPtr monitor = MonitorFromPoint(new POINT(), 1);
157
+ if (GetDpiForMonitor(monitor, 0, out x, out y) == 0 && x > 0) return x / 96.0;
158
+ } catch (Exception) {}
159
+ return 1.0;
160
+ }
161
+ static INPUT Mouse(uint flags, uint data) {
162
+ INPUT input = new INPUT(); input.type = 0; input.u.mi.dwFlags = flags; input.u.mi.mouseData = data; return input;
163
+ }
164
+ static INPUT Key(ushort vk, ushort scan, uint flags) {
165
+ INPUT input = new INPUT(); input.type = 1; input.u.ki.wVk = vk; input.u.ki.wScan = scan; input.u.ki.dwFlags = flags; return input;
166
+ }
167
+ static void Send(params INPUT[] inputs) {
168
+ SendInput((uint)inputs.Length, inputs, Marshal.SizeOf(typeof(INPUT)));
169
+ }
170
+ public static void MouseEvent(uint flags, uint data) { Send(Mouse(flags, data)); }
171
+ public static void Click(uint down, uint up) { Send(Mouse(down, 0), Mouse(up, 0)); }
172
+ public static void TypeText(string text) {
173
+ for (int i = 0; i < text.Length; i++) {
174
+ char c = text[i];
175
+ if (c == '\\r' && i + 1 < text.Length && text[i + 1] == '\\n') continue;
176
+ if (c == '\\r' || c == '\\n') { Send(Key(0x0D, 0, 0), Key(0x0D, 0, 2)); continue; }
177
+ if (c == '\\t') { Send(Key(0x09, 0, 0), Key(0x09, 0, 2)); continue; }
178
+ // KEYEVENTF_UNICODE: the character itself, whatever the keyboard layout.
179
+ Send(Key(0, c, 4), Key(0, c, 4 | 2));
180
+ }
181
+ }
182
+ }
183
+ }
184
+ "@
185
+ }
186
+ [Namzu.Desktop]::MakeDpiAware()
187
+ `.trim()
188
+
189
+ const MOUSEEVENTF = {
190
+ leftDown: 0x0002,
191
+ leftUp: 0x0004,
192
+ rightDown: 0x0008,
193
+ rightUp: 0x0010,
194
+ middleDown: 0x0020,
195
+ middleUp: 0x0040,
196
+ wheel: 0x0800,
197
+ hwheel: 0x01000,
198
+ } as const
199
+
200
+ const MOUSE_DOWN_UP: Readonly<Record<MouseButton, readonly [number, number]>> = {
201
+ left: [MOUSEEVENTF.leftDown, MOUSEEVENTF.leftUp],
202
+ right: [MOUSEEVENTF.rightDown, MOUSEEVENTF.rightUp],
203
+ middle: [MOUSEEVENTF.middleDown, MOUSEEVENTF.middleUp],
204
+ }
205
+
206
+ /** The primary display, physical. The primary display's origin is (0, 0) by definition. */
207
+ const DISPLAY_JSON = `
208
+ Add-Type -AssemblyName System.Windows.Forms
209
+ $b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
210
+ $display = @{ x = $b.X; y = $b.Y; width = $b.Width; height = $b.Height; scaleFactor = [Namzu.Desktop]::PrimaryScale() }
211
+ `.trim()
212
+
213
+ const GEOMETRY_SCRIPT = `
214
+ ${DESKTOP_TYPE}
215
+ ${DISPLAY_JSON}
216
+ [Console]::Out.Write(($display | ConvertTo-Json -Compress))
217
+ `.trim()
218
+
219
+ const SCREENSHOT_SCRIPT = `
220
+ ${DESKTOP_TYPE}
221
+ ${DISPLAY_JSON}
222
+ Add-Type -AssemblyName System.Drawing
223
+ $bmp = New-Object System.Drawing.Bitmap $b.Width, $b.Height
224
+ $g = [System.Drawing.Graphics]::FromImage($bmp)
225
+ $g.CopyFromScreen($b.Location, [System.Drawing.Point]::Empty, $b.Size)
226
+ $ms = New-Object System.IO.MemoryStream
227
+ $bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
228
+ $g.Dispose()
229
+ $bmp.Dispose()
230
+ $display.png = [Convert]::ToBase64String($ms.ToArray())
231
+ [Console]::Out.Write(($display | ConvertTo-Json -Compress))
232
+ `.trim()
233
+
234
+ const CURSOR_POSITION_SCRIPT = `
235
+ ${DESKTOP_TYPE}
236
+ Add-Type -AssemblyName System.Windows.Forms
237
+ $p = [System.Windows.Forms.Cursor]::Position
238
+ [Console]::Out.Write((@{ x = $p.X; y = $p.Y } | ConvertTo-Json -Compress))
239
+ `.trim()
240
+
241
+ function mouseClickScript(at: Point, button: MouseButton): string {
242
+ const [down, up] = MOUSE_DOWN_UP[button]
243
+ return `
244
+ ${DESKTOP_TYPE}
245
+ [Namzu.Desktop]::SetCursorPos(${at.x}, ${at.y}) | Out-Null
246
+ [Namzu.Desktop]::Click(${down}, ${up})
247
+ `.trim()
248
+ }
249
+
250
+ function mouseMoveScript(to: Point): string {
251
+ return `
252
+ ${DESKTOP_TYPE}
253
+ [Namzu.Desktop]::SetCursorPos(${to.x}, ${to.y}) | Out-Null
254
+ `.trim()
255
+ }
256
+
257
+ /** Press, move through intermediate points, release: many targets ignore a drag that teleports. */
258
+ export function dragPath(from: Point, to: Point, steps = 12): Point[] {
259
+ const path: Point[] = []
260
+ for (let i = 1; i <= steps; i++) {
261
+ path.push({
262
+ x: Math.round(from.x + ((to.x - from.x) * i) / steps),
263
+ y: Math.round(from.y + ((to.y - from.y) * i) / steps),
264
+ })
265
+ }
266
+ return path
267
+ }
268
+
269
+ function mouseDragScript(from: Point, to: Point, button: MouseButton): string {
270
+ const [down, up] = MOUSE_DOWN_UP[button]
271
+ const moves = dragPath(from, to)
272
+ .map(
273
+ (p) =>
274
+ `[Namzu.Desktop]::SetCursorPos(${p.x}, ${p.y}) | Out-Null; Start-Sleep -Milliseconds 15`,
275
+ )
276
+ .join('\n')
277
+ return `
278
+ ${DESKTOP_TYPE}
279
+ [Namzu.Desktop]::SetCursorPos(${from.x}, ${from.y}) | Out-Null
280
+ [Namzu.Desktop]::MouseEvent(${down}, 0)
281
+ ${moves}
282
+ [Namzu.Desktop]::MouseEvent(${up}, 0)
283
+ `.trim()
284
+ }
285
+
286
+ function scrollScript(at: Point, direction: ScrollDirection, amount: number): string {
287
+ const flag = direction === 'up' || direction === 'down' ? MOUSEEVENTF.wheel : MOUSEEVENTF.hwheel
288
+ const sign = direction === 'up' || direction === 'right' ? 1 : -1
289
+ const mouseData = (sign * 120 * amount) >>> 0 // WHEEL_DELTA * amount, as a DWORD
290
+ return `
291
+ ${DESKTOP_TYPE}
292
+ [Namzu.Desktop]::SetCursorPos(${at.x}, ${at.y}) | Out-Null
293
+ [Namzu.Desktop]::MouseEvent(${flag}, ${mouseData})
294
+ `.trim()
295
+ }
296
+
297
+ /** The text crosses as base64 UTF-8 and is typed as Unicode key events, so layout and quoting cannot change it. */
298
+ function typeTextScript(text: string): string {
299
+ const encoded = Buffer.from(text, 'utf8').toString('base64')
300
+ return `
301
+ ${DESKTOP_TYPE}
302
+ [Namzu.Desktop]::TypeText([System.Text.Encoding]::UTF8.GetString([Convert]::FromBase64String('${encoded}')))
303
+ `.trim()
304
+ }
305
+
306
+ function pressKeyScript(combo: string): string {
307
+ const sendKeys = translateKeyToSendKeys(combo)
308
+ return `
309
+ ${DESKTOP_TYPE}
310
+ Add-Type -AssemblyName System.Windows.Forms
311
+ [System.Windows.Forms.SendKeys]::SendWait('${sendKeys.replace(/'/g, "''")}')
312
+ `.trim()
313
+ }
314
+
315
+ // ---------------------------------------------------------------------------
316
+ // Adapter
317
+ // ---------------------------------------------------------------------------
318
+
319
+ const POWERSHELL_CANDIDATES = ['pwsh', 'powershell', 'pwsh.exe', 'powershell.exe'] as const
320
+
321
+ export interface Win32PowerShellAdapterOptions {
322
+ readonly env?: NodeJS.ProcessEnv
323
+ readonly platform?: NodeJS.Platform
324
+ /** Why cua-driver is not being used, when this adapter stands in for it. */
325
+ readonly fallbackReason?: string
326
+ /** For tests. */
327
+ readonly wslProbes?: WslProbes
328
+ }
329
+
330
+ async function findPowerShell(
331
+ env: NodeJS.ProcessEnv,
332
+ platform: NodeJS.Platform,
333
+ probes: WslProbes,
334
+ ): Promise<string | null> {
335
+ // Under WSL the Windows side's absolute path: PATH may not carry the
336
+ // Windows directories (appendWindowsPath=false, a systemd service).
337
+ if (isWsl(env, platform, probes)) {
338
+ const absolute = wslPowerShellPath(probes)
339
+ if (absolute) return absolute
340
+ }
341
+ const present = await Promise.all(POWERSHELL_CANDIDATES.map((name) => hasExecutable(name)))
342
+ return POWERSHELL_CANDIDATES.find((_name, index) => present[index]) ?? null
343
+ }
344
+
345
+ export class Win32PowerShellAdapter implements Adapter {
346
+ readonly capabilities: ComputerUseCapabilities
347
+ readonly backend = 'powershell'
348
+
349
+ private constructor(
350
+ private readonly powershell: string,
351
+ private readonly env: NodeJS.ProcessEnv | undefined,
352
+ readonly fallbackReason: string | undefined,
353
+ ) {
354
+ this.capabilities = Object.freeze({
355
+ displayServer: 'win32',
356
+ screenshot: true,
357
+ mouse: true,
358
+ keyboard: true,
359
+ cursorPosition: true,
360
+ clipboard: true,
361
+ supportedActions: Object.freeze([
362
+ 'screenshot' as const,
363
+ 'cursor_position' as const,
364
+ 'mouse_move' as const,
365
+ 'mouse_click' as const,
366
+ 'mouse_drag' as const,
367
+ 'scroll' as const,
368
+ 'type_text' as const,
369
+ 'key' as const,
370
+ ]),
371
+ })
372
+ }
373
+
374
+ static async create(
375
+ options: Win32PowerShellAdapterOptions = {},
376
+ ): Promise<Win32PowerShellAdapter> {
377
+ const env = options.env ?? process.env
378
+ const platform = options.platform ?? process.platform
379
+ const probes = options.wslProbes ?? realWslProbes
380
+ const powershell = await findPowerShell(env, platform, probes)
381
+ if (!powershell) {
382
+ throw new AdapterUnavailableError(
383
+ `Win32Adapter: neither PowerShell Core nor Windows PowerShell is available on PATH${options.fallbackReason ? `, and cua-driver was not usable: ${options.fallbackReason}` : ''}`,
384
+ [...POWERSHELL_CANDIDATES],
385
+ )
386
+ }
387
+ // Under WSL a systemd service has no working WSL_INTEROP; give it one.
388
+ const childEnv = isWsl(env, platform, probes) ? wslChildEnv(env, [], probes) : undefined
389
+ return new Win32PowerShellAdapter(powershell, childEnv, options.fallbackReason)
390
+ }
391
+
392
+ private async run(script: string): Promise<Buffer> {
393
+ const result = await runCommandOrThrow(
394
+ this.powershell,
395
+ powerShellArguments(script),
396
+ this.env ? { env: this.env } : {},
397
+ )
398
+ return result.stdout
399
+ }
400
+
401
+ async getDisplayGeometry(): Promise<DisplayGeometry> {
402
+ const parsed = JSON.parse((await this.run(GEOMETRY_SCRIPT)).toString('utf8')) as {
403
+ width: number
404
+ height: number
405
+ scaleFactor: number
406
+ }
407
+ return { width: parsed.width, height: parsed.height, scaleFactor: parsed.scaleFactor }
408
+ }
409
+
410
+ async execute(action: ComputerUseAction): Promise<ComputerUseResult> {
411
+ switch (action.type) {
412
+ case 'screenshot': {
413
+ const parsed = JSON.parse((await this.run(SCREENSHOT_SCRIPT)).toString('utf8')) as {
414
+ x: number
415
+ y: number
416
+ width: number
417
+ height: number
418
+ scaleFactor: number
419
+ png: string
420
+ }
421
+ const data = Buffer.from(parsed.png, 'base64')
422
+ const dims = decodePngDims(data)
423
+ const display: DisplayInfo = {
424
+ id: 'primary',
425
+ x: parsed.x,
426
+ y: parsed.y,
427
+ width: parsed.width,
428
+ height: parsed.height,
429
+ scaleFactor: parsed.scaleFactor,
430
+ primary: true,
431
+ }
432
+ return {
433
+ type: 'screenshot',
434
+ result: { data, mimeType: 'image/png', width: dims.width, height: dims.height, display },
435
+ }
436
+ }
437
+ case 'cursor_position': {
438
+ const parsed = JSON.parse((await this.run(CURSOR_POSITION_SCRIPT)).toString('utf8')) as {
439
+ x: number
440
+ y: number
441
+ }
442
+ return { type: 'cursor_position', point: { x: parsed.x, y: parsed.y } }
443
+ }
444
+ case 'mouse_move':
445
+ await this.run(mouseMoveScript(action.to))
446
+ return { type: 'ok' }
447
+ case 'mouse_click':
448
+ await this.run(mouseClickScript(action.at, action.button))
449
+ return { type: 'ok' }
450
+ case 'mouse_drag':
451
+ await this.run(mouseDragScript(action.from, action.to, action.button))
452
+ return { type: 'ok' }
453
+ case 'scroll':
454
+ await this.run(scrollScript(action.at, action.direction, action.amount))
455
+ return { type: 'ok' }
456
+ case 'type_text':
457
+ await this.run(typeTextScript(action.text))
458
+ return { type: 'ok' }
459
+ case 'key':
460
+ await this.run(pressKeyScript(action.keys))
461
+ return { type: 'ok' }
462
+ }
463
+ }
464
+ }
465
+
466
+ function decodePngDims(buffer: Buffer): { width: number; height: number } {
467
+ if (buffer.length < 24) {
468
+ throw new Error('Win32Adapter: screenshot buffer too small to contain PNG header')
469
+ }
470
+ return {
471
+ width: buffer.readUInt32BE(16),
472
+ height: buffer.readUInt32BE(20),
473
+ }
474
+ }
475
+
476
+ /** For tests: the scripts as they are sent. */
477
+ export const _scripts = {
478
+ typeText: typeTextScript,
479
+ mouseDrag: mouseDragScript,
480
+ screenshot: SCREENSHOT_SCRIPT,
481
+ geometry: GEOMETRY_SCRIPT,
482
+ }