@namzu/computer-use 1.4.3 → 2.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 (74) hide show
  1. package/CHANGELOG.md +36 -0
  2. package/README.md +96 -5
  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
@@ -1,369 +1,125 @@
1
- import type {
2
- ComputerUseAction,
3
- ComputerUseCapabilities,
4
- ComputerUseResult,
5
- DisplayGeometry,
6
- MouseButton,
7
- Point,
8
- ScrollDirection,
9
- } from '@namzu/sdk'
10
- import { hasExecutable, runCommand, runCommandOrThrow } from '../util/spawn.js'
1
+ import { CuaDriverAdapter } from './cua-driver/adapter.js'
2
+ import {
3
+ CUA_DRIVER_RELEASE,
4
+ type ResolveCuaDriverOptions,
5
+ resolveCuaDriver,
6
+ } from './cua-driver/provision.js'
11
7
  import { type Adapter, AdapterUnavailableError } from './types.js'
8
+ import { Win32PowerShellAdapter } from './win32-powershell.js'
9
+ import { type WslProbes, isWsl, realWslProbes, wslChildEnv } from './wsl.js'
12
10
 
13
- // ---------------------------------------------------------------------------
14
- // Key translation: our input ("ctrl+c") → PowerShell SendKeys format ("^c").
15
- // ---------------------------------------------------------------------------
16
-
17
- const SENDKEYS_MODIFIER: Readonly<Record<string, string>> = {
18
- cmd: '^',
19
- command: '^',
20
- ctrl: '^',
21
- control: '^',
22
- meta: '^',
23
- super: '^',
24
- win: '^',
25
- alt: '%',
26
- option: '%',
27
- opt: '%',
28
- shift: '+',
29
- }
30
-
31
- const SENDKEYS_SPECIAL: Readonly<Record<string, string>> = {
32
- enter: '{ENTER}',
33
- return: '{ENTER}',
34
- escape: '{ESC}',
35
- esc: '{ESC}',
36
- tab: '{TAB}',
37
- backspace: '{BACKSPACE}',
38
- delete: '{DELETE}',
39
- forward_delete: '{DELETE}',
40
- space: ' ',
41
- up: '{UP}',
42
- down: '{DOWN}',
43
- left: '{LEFT}',
44
- right: '{RIGHT}',
45
- home: '{HOME}',
46
- end: '{END}',
47
- page_up: '{PGUP}',
48
- page_down: '{PGDN}',
49
- f1: '{F1}',
50
- f2: '{F2}',
51
- f3: '{F3}',
52
- f4: '{F4}',
53
- f5: '{F5}',
54
- f6: '{F6}',
55
- f7: '{F7}',
56
- f8: '{F8}',
57
- f9: '{F9}',
58
- f10: '{F10}',
59
- f11: '{F11}',
60
- f12: '{F12}',
61
- }
62
-
63
- export function translateKeyToSendKeys(combo: string): string {
64
- const parts = combo
65
- .split('+')
66
- .map((p) => p.trim())
67
- .filter((p) => p.length > 0)
68
- if (parts.length === 0) throw new Error('translateKeyToSendKeys: empty key combo')
69
- const main = parts[parts.length - 1] ?? ''
70
- const mods = parts.slice(0, -1)
71
- const modifierPrefix = mods
72
- .map((m) => {
73
- const prefix = SENDKEYS_MODIFIER[m.toLowerCase()]
74
- if (!prefix) throw new Error(`translateKeyToSendKeys: unknown modifier "${m}"`)
75
- return prefix
76
- })
77
- .join('')
78
- const special = SENDKEYS_SPECIAL[main.toLowerCase()]
79
- if (special) return modifierPrefix + special
80
- // Single printable chars pass through as-is; longer names stay literal and
81
- // SendKeys will fall back to per-character typing.
82
- return modifierPrefix + main
83
- }
84
-
85
- // ---------------------------------------------------------------------------
86
- // Single PowerShell invocation wrapper. We pass the script via `-Command`
87
- // (argv array, not shell) and the action body as a -File-like heredoc. All
88
- // data crosses the boundary as JSON where possible.
89
- // ---------------------------------------------------------------------------
90
-
91
- const POWERSHELL_BASE_ARGS = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass']
92
-
93
- async function runPowerShell(executable: string, script: string): Promise<Buffer> {
94
- const result = await runCommandOrThrow(executable, [...POWERSHELL_BASE_ARGS, '-Command', script])
95
- return result.stdout
96
- }
97
-
98
- // ---------------------------------------------------------------------------
99
- // Script fragments — loaded once, stamped into each invocation.
100
- // ---------------------------------------------------------------------------
101
-
102
- const GEOMETRY_SCRIPT = `
103
- Add-Type -AssemblyName System.Windows.Forms
104
- $b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
105
- [Console]::Out.Write((@{ width = $b.Width; height = $b.Height; scaleFactor = 1 } | ConvertTo-Json -Compress))
106
- `.trim()
107
-
108
- const SCREENSHOT_SCRIPT = `
109
- Add-Type -AssemblyName System.Drawing
110
- Add-Type -AssemblyName System.Windows.Forms
111
- $b = [System.Windows.Forms.Screen]::PrimaryScreen.Bounds
112
- $bmp = New-Object System.Drawing.Bitmap $b.Width, $b.Height
113
- $g = [System.Drawing.Graphics]::FromImage($bmp)
114
- $g.CopyFromScreen($b.Location, [System.Drawing.Point]::Empty, $b.Size)
115
- $ms = New-Object System.IO.MemoryStream
116
- $bmp.Save($ms, [System.Drawing.Imaging.ImageFormat]::Png)
117
- $g.Dispose()
118
- $bmp.Dispose()
119
- [Console]::OpenStandardOutput().Write($ms.ToArray(), 0, $ms.Length)
120
- `.trim()
121
-
122
- const CURSOR_POSITION_SCRIPT = `
123
- Add-Type -AssemblyName System.Windows.Forms
124
- $p = [System.Windows.Forms.Cursor]::Position
125
- [Console]::Out.Write((@{ x = $p.X; y = $p.Y } | ConvertTo-Json -Compress))
126
- `.trim()
11
+ /**
12
+ * Which Windows backend drives the desktop.
13
+ *
14
+ * - `auto` (the default): cua-driver — the pinned build, downloaded and
15
+ * checked on first use — and, when it cannot be had or does not answer,
16
+ * the per-action PowerShell path, with the reason on `fallbackReason`.
17
+ * - `cua-driver`: cua-driver or nothing; its failure is the adapter's.
18
+ * - `powershell`: never cua-driver.
19
+ */
20
+ export type Win32Backend = 'auto' | 'cua-driver' | 'powershell'
21
+
22
+ export interface Win32AdapterOptions {
23
+ readonly backend?: Win32Backend
24
+ /** An existing `cua-driver.exe` to run instead of the pinned build. */
25
+ readonly cuaDriverPath?: string
26
+ /** Where the pinned build is kept. Default `<NAMZU_HOME>/computer-use/cua-driver/<version>`. */
27
+ readonly cacheDir?: string
28
+ /** Download the pinned build when it is missing. Default true. */
29
+ readonly download?: boolean
30
+ readonly env?: NodeJS.ProcessEnv
31
+ readonly platform?: NodeJS.Platform
32
+ /** For tests. */
33
+ readonly wslProbes?: WslProbes
34
+ /** For tests. */
35
+ readonly resolve?: typeof resolveCuaDriver
36
+ /** For tests. */
37
+ readonly createCuaDriverAdapter?: (
38
+ options: ConstructorParameters<typeof CuaDriverAdapter>[0],
39
+ ) => Adapter
40
+ }
41
+
42
+ /** Variables cua-driver reads that this adapter sets for it. */
43
+ const CUA_DRIVER_SETTINGS = {
44
+ // Default-on product telemetry: off.
45
+ CUA_DRIVER_RS_TELEMETRY_ENABLED: '0',
46
+ // The release check against GitHub: off; this package pins the build.
47
+ CUA_DRIVER_RS_UPDATE_CHECK: '0',
48
+ } as const
49
+
50
+ /** Variable names never handed to a third-party program. */
51
+ const SECRET_NAME = /(API_?KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)/i
127
52
 
128
53
  /**
129
- * Inline C# P/Invoke block for SendInput. Loaded via Add-Type inside each
130
- * PowerShell invocation. Defines SendInput, INPUT, MOUSEINPUT, KEYBDINPUT;
131
- * exposes static helpers for mouse down/up, move, scroll, and key press.
54
+ * The environment cua-driver runs with: the caller's minus anything named
55
+ * like a secret, plus {@link CUA_DRIVER_SETTINGS}; under WSL, with a working
56
+ * `WSL_INTEROP` and the settings forwarded through `WSLENV`.
132
57
  */
133
- const USER32_TYPE = `
134
- if (-not ([System.Management.Automation.PSTypeName]'Namzu.User32').Type) {
135
- Add-Type -TypeDefinition @"
136
- using System;
137
- using System.Runtime.InteropServices;
138
- namespace Namzu {
139
- public static class User32 {
140
- [StructLayout(LayoutKind.Sequential)]
141
- public struct MOUSEINPUT {
142
- public int dx; public int dy; public uint mouseData; public uint dwFlags; public uint time; public IntPtr dwExtraInfo;
143
- }
144
- [StructLayout(LayoutKind.Sequential)]
145
- public struct KEYBDINPUT {
146
- public ushort wVk; public ushort wScan; public uint dwFlags; public uint time; public IntPtr dwExtraInfo;
147
- }
148
- [StructLayout(LayoutKind.Explicit)]
149
- public struct INPUTUNION {
150
- [FieldOffset(0)] public MOUSEINPUT mi;
151
- [FieldOffset(0)] public KEYBDINPUT ki;
152
- }
153
- [StructLayout(LayoutKind.Sequential)]
154
- public struct INPUT { public uint type; public INPUTUNION u; }
155
- [DllImport("user32.dll", SetLastError = true)]
156
- public static extern uint SendInput(uint nInputs, INPUT[] pInputs, int cbSize);
157
- [DllImport("user32.dll")]
158
- public static extern bool SetCursorPos(int X, int Y);
159
- public const uint INPUT_MOUSE = 0;
160
- public const uint MOUSEEVENTF_LEFTDOWN = 0x0002, MOUSEEVENTF_LEFTUP = 0x0004;
161
- public const uint MOUSEEVENTF_RIGHTDOWN = 0x0008, MOUSEEVENTF_RIGHTUP = 0x0010;
162
- public const uint MOUSEEVENTF_MIDDLEDOWN = 0x0020, MOUSEEVENTF_MIDDLEUP = 0x0040;
163
- public const uint MOUSEEVENTF_WHEEL = 0x0800, MOUSEEVENTF_HWHEEL = 0x01000;
164
- }
58
+ export function cuaDriverEnvironment(
59
+ env: NodeJS.ProcessEnv,
60
+ wsl: boolean,
61
+ probes: WslProbes = realWslProbes,
62
+ ): NodeJS.ProcessEnv {
63
+ const base: NodeJS.ProcessEnv = {}
64
+ for (const [name, value] of Object.entries(env)) {
65
+ if (!SECRET_NAME.test(name)) base[name] = value
165
66
  }
166
- "@
167
- }
168
- `.trim()
169
-
170
- function mouseClickScript(at: Point, button: MouseButton): string {
171
- const [downFlag, upFlag] = MOUSE_DOWN_UP_FLAGS[button]
172
- return `
173
- ${USER32_TYPE}
174
- [Namzu.User32]::SetCursorPos(${at.x}, ${at.y}) | Out-Null
175
- $down = New-Object Namzu.User32+INPUT
176
- $down.type = [Namzu.User32]::INPUT_MOUSE
177
- $down.u.mi.dwFlags = ${downFlag}
178
- $up = New-Object Namzu.User32+INPUT
179
- $up.type = [Namzu.User32]::INPUT_MOUSE
180
- $up.u.mi.dwFlags = ${upFlag}
181
- [Namzu.User32]::SendInput(2, @($down, $up), [System.Runtime.InteropServices.Marshal]::SizeOf($down)) | Out-Null
182
- `.trim()
183
- }
184
-
185
- function mouseMoveScript(to: Point): string {
186
- return `
187
- ${USER32_TYPE}
188
- [Namzu.User32]::SetCursorPos(${to.x}, ${to.y}) | Out-Null
189
- `.trim()
190
- }
191
-
192
- function mouseDragScript(from: Point, to: Point, button: MouseButton): string {
193
- const [downFlag, upFlag] = MOUSE_DOWN_UP_FLAGS[button]
194
- return `
195
- ${USER32_TYPE}
196
- [Namzu.User32]::SetCursorPos(${from.x}, ${from.y}) | Out-Null
197
- $down = New-Object Namzu.User32+INPUT
198
- $down.type = [Namzu.User32]::INPUT_MOUSE
199
- $down.u.mi.dwFlags = ${downFlag}
200
- [Namzu.User32]::SendInput(1, @($down), [System.Runtime.InteropServices.Marshal]::SizeOf($down)) | Out-Null
201
- [Namzu.User32]::SetCursorPos(${to.x}, ${to.y}) | Out-Null
202
- $up = New-Object Namzu.User32+INPUT
203
- $up.type = [Namzu.User32]::INPUT_MOUSE
204
- $up.u.mi.dwFlags = ${upFlag}
205
- [Namzu.User32]::SendInput(1, @($up), [System.Runtime.InteropServices.Marshal]::SizeOf($up)) | Out-Null
206
- `.trim()
207
- }
208
-
209
- function scrollScript(at: Point, direction: ScrollDirection, amount: number): string {
210
- const wheelFlag =
211
- direction === 'up' || direction === 'down' ? 'MOUSEEVENTF_WHEEL' : 'MOUSEEVENTF_HWHEEL'
212
- const sign = direction === 'up' || direction === 'right' ? 1 : -1
213
- const mouseData = sign * 120 * amount // WHEEL_DELTA * amount
214
- return `
215
- ${USER32_TYPE}
216
- [Namzu.User32]::SetCursorPos(${at.x}, ${at.y}) | Out-Null
217
- $scroll = New-Object Namzu.User32+INPUT
218
- $scroll.type = [Namzu.User32]::INPUT_MOUSE
219
- $scroll.u.mi.dwFlags = [Namzu.User32]::${wheelFlag}
220
- $scroll.u.mi.mouseData = ${mouseData >>> 0}
221
- [Namzu.User32]::SendInput(1, @($scroll), [System.Runtime.InteropServices.Marshal]::SizeOf($scroll)) | Out-Null
222
- `.trim()
223
- }
224
-
225
- function typeTextScript(text: string): string {
226
- const escaped = escapePowerShellString(text)
227
- return `
228
- Add-Type -AssemblyName System.Windows.Forms
229
- [System.Windows.Forms.SendKeys]::SendWait(${quoted(escaped)})
230
- `.trim()
67
+ Object.assign(base, CUA_DRIVER_SETTINGS)
68
+ return wsl ? wslChildEnv(base, Object.keys(CUA_DRIVER_SETTINGS), probes) : base
231
69
  }
232
70
 
233
- function pressKeyScript(combo: string): string {
234
- const sendKeys = translateKeyToSendKeys(combo)
235
- return `
236
- Add-Type -AssemblyName System.Windows.Forms
237
- [System.Windows.Forms.SendKeys]::SendWait(${quoted(sendKeys)})
238
- `.trim()
239
- }
240
-
241
- function escapePowerShellString(s: string): string {
242
- // For SendKeys we must also escape its control chars: + ^ % ~ ( ) { }.
243
- // Those are only interpreted when not inside SendKeys — for literal text
244
- // they need to be wrapped in braces.
245
- return s.replace(/([+^%~(){}])/g, '{$1}')
246
- }
247
-
248
- function quoted(s: string): string {
249
- return `'${s.replace(/'/g, "''")}'`
250
- }
251
-
252
- const MOUSE_DOWN_UP_FLAGS: Readonly<Record<MouseButton, readonly [string, string]>> = {
253
- left: ['[Namzu.User32]::MOUSEEVENTF_LEFTDOWN', '[Namzu.User32]::MOUSEEVENTF_LEFTUP'],
254
- right: ['[Namzu.User32]::MOUSEEVENTF_RIGHTDOWN', '[Namzu.User32]::MOUSEEVENTF_RIGHTUP'],
255
- middle: ['[Namzu.User32]::MOUSEEVENTF_MIDDLEDOWN', '[Namzu.User32]::MOUSEEVENTF_MIDDLEUP'],
256
- }
257
-
258
- // ---------------------------------------------------------------------------
259
- // Adapter
260
- // ---------------------------------------------------------------------------
261
-
262
- const POWERSHELL_CANDIDATES = ['pwsh', 'powershell', 'pwsh.exe', 'powershell.exe'] as const
263
-
264
- async function findPowerShell(): Promise<string | null> {
265
- const present = await Promise.all(POWERSHELL_CANDIDATES.map((name) => hasExecutable(name)))
266
- return POWERSHELL_CANDIDATES.find((_name, index) => present[index]) ?? null
267
- }
268
-
269
- export class Win32Adapter implements Adapter {
270
- readonly capabilities: ComputerUseCapabilities
271
-
272
- private constructor(private readonly powershell: string) {
273
- this.capabilities = Object.freeze({
274
- displayServer: 'win32',
275
- screenshot: true,
276
- mouse: true,
277
- keyboard: true,
278
- cursorPosition: true,
279
- clipboard: true,
280
- supportedActions: Object.freeze([
281
- 'screenshot' as const,
282
- 'cursor_position' as const,
283
- 'mouse_move' as const,
284
- 'mouse_click' as const,
285
- 'mouse_drag' as const,
286
- 'scroll' as const,
287
- 'type_text' as const,
288
- 'key' as const,
289
- ]),
290
- })
291
- }
292
-
293
- static async create(): Promise<Win32Adapter> {
294
- const powershell = await findPowerShell()
295
- if (!powershell) {
296
- throw new AdapterUnavailableError(
297
- 'Win32Adapter: neither PowerShell Core nor Windows PowerShell is available on PATH',
298
- [...POWERSHELL_CANDIDATES],
299
- )
300
- }
301
- return new Win32Adapter(powershell)
302
- }
303
-
304
- async getDisplayGeometry(): Promise<DisplayGeometry> {
305
- const stdout = await runPowerShell(this.powershell, GEOMETRY_SCRIPT)
306
- const parsed = JSON.parse(stdout.toString('utf8')) as {
307
- width: number
308
- height: number
309
- scaleFactor: number
310
- }
311
- return { width: parsed.width, height: parsed.height, scaleFactor: parsed.scaleFactor }
312
- }
313
-
314
- async execute(action: ComputerUseAction): Promise<ComputerUseResult> {
315
- switch (action.type) {
316
- case 'screenshot': {
317
- const data = await runPowerShell(this.powershell, SCREENSHOT_SCRIPT)
318
- const dims = decodePngDims(data)
319
- return {
320
- type: 'screenshot',
321
- result: {
322
- data,
323
- mimeType: 'image/png',
324
- width: dims.width,
325
- height: dims.height,
326
- },
327
- }
71
+ /**
72
+ * `NAMZU_CUA_DRIVER`: `off` keeps cua-driver out (the PowerShell path);
73
+ * a path names the `cua-driver.exe` to run instead of the pinned build.
74
+ */
75
+ function fromEnvironment(env: NodeJS.ProcessEnv): { off: boolean; path?: string } {
76
+ const value = env.NAMZU_CUA_DRIVER?.trim()
77
+ if (!value) return { off: false }
78
+ if (/^(off|0|false|no|none)$/i.test(value)) return { off: true }
79
+ return { off: false, path: value }
80
+ }
81
+
82
+ export class Win32Adapter {
83
+ /** The Windows adapter for this host; see {@link Win32Backend}. */
84
+ static async create(options: Win32AdapterOptions = {}): Promise<Adapter> {
85
+ const env = options.env ?? process.env
86
+ const platform = options.platform ?? process.platform
87
+ const probes = options.wslProbes ?? realWslProbes
88
+ const configured = fromEnvironment(env)
89
+ const backend: Win32Backend = options.backend ?? (configured.off ? 'powershell' : 'auto')
90
+ const powershell = (fallbackReason?: string) =>
91
+ Win32PowerShellAdapter.create({ env, platform, wslProbes: probes, fallbackReason })
92
+ if (backend === 'powershell') return powershell()
93
+
94
+ const cuaDriverPath = options.cuaDriverPath ?? configured.path
95
+ let adapter: Adapter | undefined
96
+ try {
97
+ const resolveOptions: ResolveCuaDriverOptions = {
98
+ env,
99
+ ...(cuaDriverPath !== undefined ? { path: cuaDriverPath } : {}),
100
+ ...(options.cacheDir !== undefined ? { cacheDir: options.cacheDir } : {}),
101
+ ...(options.download !== undefined ? { download: options.download } : {}),
102
+ }
103
+ const resolved = await (options.resolve ?? resolveCuaDriver)(resolveOptions)
104
+ const wsl = isWsl(env, platform, probes)
105
+ const adapterOptions = {
106
+ executable: resolved.path,
107
+ env: cuaDriverEnvironment(env, wsl, probes),
108
+ ...(resolved.source === 'configured' ? {} : { version: CUA_DRIVER_RELEASE.version }),
328
109
  }
329
- case 'cursor_position': {
330
- const stdout = await runPowerShell(this.powershell, CURSOR_POSITION_SCRIPT)
331
- const parsed = JSON.parse(stdout.toString('utf8')) as { x: number; y: number }
332
- return { type: 'cursor_position', point: parsed }
110
+ adapter = options.createCuaDriverAdapter
111
+ ? options.createCuaDriverAdapter(adapterOptions)
112
+ : new CuaDriverAdapter(adapterOptions)
113
+ // Starts the driver and proves it reaches the desktop.
114
+ await adapter.getDisplayGeometry()
115
+ return adapter
116
+ } catch (error) {
117
+ await adapter?.dispose?.().catch(() => undefined)
118
+ const reason = error instanceof Error ? error.message : String(error)
119
+ if (backend === 'cua-driver') {
120
+ throw new AdapterUnavailableError(`Win32Adapter: cua-driver is not usable: ${reason}`)
333
121
  }
334
- case 'mouse_move':
335
- await runPowerShell(this.powershell, mouseMoveScript(action.to))
336
- return { type: 'ok' }
337
- case 'mouse_click':
338
- await runPowerShell(this.powershell, mouseClickScript(action.at, action.button))
339
- return { type: 'ok' }
340
- case 'mouse_drag':
341
- await runPowerShell(this.powershell, mouseDragScript(action.from, action.to, action.button))
342
- return { type: 'ok' }
343
- case 'scroll':
344
- await runPowerShell(
345
- this.powershell,
346
- scrollScript(action.at, action.direction, action.amount),
347
- )
348
- return { type: 'ok' }
349
- case 'type_text':
350
- await runPowerShell(this.powershell, typeTextScript(action.text))
351
- return { type: 'ok' }
352
- case 'key':
353
- await runPowerShell(this.powershell, pressKeyScript(action.keys))
354
- return { type: 'ok' }
122
+ return powershell(reason)
355
123
  }
356
124
  }
357
125
  }
358
-
359
- function decodePngDims(buffer: Buffer): { width: number; height: number } {
360
- if (buffer.length < 24) {
361
- throw new Error('Win32Adapter: screenshot buffer too small to contain PNG header')
362
- }
363
- return {
364
- width: buffer.readUInt32BE(16),
365
- height: buffer.readUInt32BE(20),
366
- }
367
- }
368
-
369
- export { runCommand as _runCommand }
@@ -0,0 +1,150 @@
1
+ import { existsSync, readFileSync, readdirSync, statSync } from 'node:fs'
2
+ import { join } from 'node:path'
3
+
4
+ /**
5
+ * The WSL facts the Windows adapter needs: is this WSL, where the Windows
6
+ * drives are mounted, which interop socket a process without a working
7
+ * `WSL_INTEROP` (a systemd service) can use to start a Windows program, and
8
+ * how to forward variables to one.
9
+ *
10
+ * A minimal copy of `@namzu/browser`'s `wsl.ts` and `detect.ts`: leaf
11
+ * packages do not import one another.
12
+ */
13
+
14
+ /** What the helpers read from the machine; replaced in tests. */
15
+ export interface WslProbes {
16
+ readFile(path: string): string | undefined
17
+ exists(path: string): boolean
18
+ /** Interop sockets under `/run/WSL`, with modification times. */
19
+ interopSockets(): readonly { readonly path: string; readonly mtimeMs: number }[]
20
+ }
21
+
22
+ export const WSL_RUN_DIR = '/run/WSL'
23
+ export const DEFAULT_WSL_MOUNT_ROOT = '/mnt/'
24
+ const WSL_POWERSHELL_TAIL = 'c/Windows/System32/WindowsPowerShell/v1.0/powershell.exe'
25
+
26
+ export const realWslProbes: WslProbes = {
27
+ readFile(path) {
28
+ try {
29
+ return readFileSync(path, 'utf8')
30
+ } catch {
31
+ return undefined
32
+ }
33
+ },
34
+ exists(path) {
35
+ return existsSync(path)
36
+ },
37
+ interopSockets() {
38
+ let names: string[]
39
+ try {
40
+ names = readdirSync(WSL_RUN_DIR)
41
+ } catch {
42
+ return []
43
+ }
44
+ const sockets: { path: string; mtimeMs: number }[] = []
45
+ for (const name of names) {
46
+ if (!/^\d+_interop$/.test(name)) continue
47
+ const path = join(WSL_RUN_DIR, name)
48
+ try {
49
+ const stat = statSync(path)
50
+ if (stat.isSocket()) sockets.push({ path, mtimeMs: stat.mtimeMs })
51
+ } catch {
52
+ // Gone between the listing and the stat: a session that just ended.
53
+ }
54
+ }
55
+ return sockets
56
+ },
57
+ }
58
+
59
+ /** Is this Linux kernel WSL's? The variables are absent under a systemd service. */
60
+ export function isWsl(
61
+ env: NodeJS.ProcessEnv,
62
+ platform: NodeJS.Platform,
63
+ probes: WslProbes = realWslProbes,
64
+ ): boolean {
65
+ if (platform !== 'linux') return false
66
+ if (env.WSL_DISTRO_NAME || env.WSL_INTEROP) return true
67
+ return /microsoft|wsl/i.test(probes.readFile('/proc/sys/kernel/osrelease') ?? '')
68
+ }
69
+
70
+ /** The `[automount] root` of `/etc/wsl.conf`, with a trailing slash; `/mnt/` by default. */
71
+ export function parseWslMountRoot(wslConf: string | undefined): string {
72
+ if (!wslConf) return DEFAULT_WSL_MOUNT_ROOT
73
+ let section = ''
74
+ for (const raw of wslConf.replace(/^/, '').split(/\r?\n/)) {
75
+ const line = raw.trim()
76
+ if (line.length === 0 || line.startsWith('#') || line.startsWith(';')) continue
77
+ const header = /^\[([^\]]+)\]$/.exec(line)
78
+ if (header) {
79
+ section = (header[1] ?? '').trim().toLowerCase()
80
+ continue
81
+ }
82
+ const eq = line.indexOf('=')
83
+ if (section !== 'automount' || eq <= 0) continue
84
+ if (line.slice(0, eq).trim().toLowerCase() !== 'root') continue
85
+ let value = line
86
+ .slice(eq + 1)
87
+ .replace(/\s[#;].*$/, '')
88
+ .trim()
89
+ if (/^(["']).*\1$/.test(value)) value = value.slice(1, -1)
90
+ if (!value.startsWith('/')) return DEFAULT_WSL_MOUNT_ROOT
91
+ return value.endsWith('/') ? value : `${value}/`
92
+ }
93
+ return DEFAULT_WSL_MOUNT_ROOT
94
+ }
95
+
96
+ /** Windows PowerShell 5.1, absolute, as WSL sees it; `undefined` when it is not there. */
97
+ export function wslPowerShellPath(probes: WslProbes = realWslProbes): string | undefined {
98
+ const path = `${parseWslMountRoot(probes.readFile('/etc/wsl.conf'))}${WSL_POWERSHELL_TAIL}`
99
+ return probes.exists(path) ? path : undefined
100
+ }
101
+
102
+ /**
103
+ * The interop socket to give a Windows program: `WSL_INTEROP` when it
104
+ * exists; else `1_interop`, which WSL links for systemd to the distro's own
105
+ * init and so lives as long as the distro; else the newest session's.
106
+ */
107
+ export function wslInteropSocket(
108
+ env: NodeJS.ProcessEnv,
109
+ probes: WslProbes = realWslProbes,
110
+ ): string | undefined {
111
+ if (env.WSL_INTEROP && probes.exists(env.WSL_INTEROP)) return env.WSL_INTEROP
112
+ const sockets = probes.interopSockets()
113
+ const stable = sockets.find((socket) => socket.path === `${WSL_RUN_DIR}/1_interop`)
114
+ if (stable) return stable.path
115
+ return [...sockets].sort((a, b) => b.mtimeMs - a.mtimeMs)[0]?.path
116
+ }
117
+
118
+ /**
119
+ * `WSLENV` with `entries` appended once each. An entry is a variable name
120
+ * with optional flags (`NAME/p` translates a Linux path to a Windows one).
121
+ */
122
+ export function mergeWslenv(existing: string | undefined, entries: readonly string[]): string {
123
+ const present = (existing ?? '').split(':').filter((entry) => entry.length > 0)
124
+ const names = new Set(present.map((entry) => entry.split('/')[0]))
125
+ for (const entry of entries) {
126
+ const name = entry.split('/')[0]
127
+ if (names.has(name)) continue
128
+ names.add(name)
129
+ present.push(entry)
130
+ }
131
+ return present.join(':')
132
+ }
133
+
134
+ /**
135
+ * The environment a Windows program started from WSL needs: the caller's,
136
+ * with a working `WSL_INTEROP` (a systemd service has none, or a stale one)
137
+ * and `forward` added to `WSLENV` so those variables cross the boundary.
138
+ */
139
+ export function wslChildEnv(
140
+ env: NodeJS.ProcessEnv,
141
+ forward: readonly string[],
142
+ probes: WslProbes = realWslProbes,
143
+ ): NodeJS.ProcessEnv {
144
+ const socket = wslInteropSocket(env, probes)
145
+ return {
146
+ ...env,
147
+ ...(socket !== undefined ? { WSL_INTEROP: socket } : {}),
148
+ WSLENV: mergeWslenv(env.WSLENV, forward),
149
+ }
150
+ }
package/src/index.ts CHANGED
@@ -1,5 +1,9 @@
1
1
  export { SubprocessComputerUseHost } from './SubprocessComputerUseHost.js'
2
- export type { SubprocessComputerUseHostOptions } from './SubprocessComputerUseHost.js'
2
+ export type {
3
+ SubprocessComputerUseHostOptions,
4
+ SubprocessComputerUseHostWindowsOptions,
5
+ } from './SubprocessComputerUseHost.js'
6
+ export type { Win32Backend } from './adapters/win32.js'
3
7
  export { detectDisplayServer } from './detect/index.js'
4
8
  export { ComputerUseOutcomeUnknownError } from './errors.js'
5
9