@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,451 @@
1
+ import { type ChildProcessWithoutNullStreams, spawn } from 'node:child_process'
2
+ import { SpawnError } from '../../util/spawn.js'
3
+
4
+ /**
5
+ * A client for one MCP server spoken to over a child process's standard
6
+ * streams: newline-delimited JSON-RPC 2.0, as the MCP stdio transport
7
+ * defines it. It owns the process:
8
+ *
9
+ * - started lazily on the first call, with the `initialize` handshake;
10
+ * - restarted by the next call after it exits or is killed;
11
+ * - killed when a request outlives its timeout, because a server that has
12
+ * stopped answering one request cannot be trusted with the next;
13
+ * - asked to exit (stdin closed) and then killed on {@link dispose}.
14
+ *
15
+ * A request that was written and then lost to an exit or a timeout rejects
16
+ * with {@link SpawnError}, the same "it started and did not finish cleanly"
17
+ * signal the one-shot subprocess adapters give; the host turns that into an
18
+ * unknown outcome for actions that change the desktop. A failure before
19
+ * anything was sent — the process would not start, the handshake failed —
20
+ * is an ordinary `Error`.
21
+ */
22
+
23
+ export type McpContent =
24
+ | { readonly type: 'text'; readonly text: string }
25
+ | { readonly type: 'image'; readonly data: string; readonly mimeType: string }
26
+ | { readonly type: string; readonly [key: string]: unknown }
27
+
28
+ export interface McpToolResult {
29
+ readonly content: readonly McpContent[]
30
+ readonly structuredContent?: Record<string, unknown>
31
+ }
32
+
33
+ /** The server ran the tool and reported that it failed (`isError: true`). */
34
+ export class McpToolError extends Error {
35
+ override readonly name = 'McpToolError'
36
+
37
+ constructor(
38
+ readonly tool: string,
39
+ message: string,
40
+ readonly structuredContent?: Record<string, unknown>,
41
+ ) {
42
+ super(message)
43
+ }
44
+ }
45
+
46
+ /** The server answered a request with a JSON-RPC error. */
47
+ export class McpProtocolError extends Error {
48
+ override readonly name = 'McpProtocolError'
49
+
50
+ constructor(
51
+ readonly method: string,
52
+ readonly code: number,
53
+ message: string,
54
+ ) {
55
+ super(`${method} failed (${code}): ${message}`)
56
+ }
57
+ }
58
+
59
+ export type McpToolCaller = (
60
+ name: string,
61
+ args?: Record<string, unknown>,
62
+ timeoutMs?: number,
63
+ ) => Promise<McpToolResult>
64
+
65
+ export interface McpStdioClientOptions {
66
+ readonly command: string
67
+ readonly args: readonly string[]
68
+ readonly env?: NodeJS.ProcessEnv
69
+ readonly cwd?: string
70
+ readonly clientName?: string
71
+ readonly clientVersion?: string
72
+ /** Default `2025-06-18`. */
73
+ readonly protocolVersion?: string
74
+ /** Spawn plus `initialize`. Default 20 s. */
75
+ readonly startTimeoutMs?: number
76
+ /** Default per-request timeout. Default 15 s. */
77
+ readonly requestTimeoutMs?: number
78
+ /** Runs once per started process, after `initialize`, before any caller's request. */
79
+ readonly afterStart?: (call: McpToolCaller) => Promise<void>
80
+ /** For tests: start something other than `command`. */
81
+ readonly spawnProcess?: (
82
+ command: string,
83
+ args: readonly string[],
84
+ options: { readonly env?: NodeJS.ProcessEnv; readonly cwd?: string },
85
+ ) => ChildProcessWithoutNullStreams
86
+ }
87
+
88
+ interface Pending {
89
+ readonly method: string
90
+ readonly resolve: (value: unknown) => void
91
+ readonly reject: (error: Error) => void
92
+ readonly timer: NodeJS.Timeout
93
+ }
94
+
95
+ interface Running {
96
+ readonly child: ChildProcessWithoutNullStreams
97
+ readonly pending: Map<number, Pending>
98
+ readonly stderr: string[]
99
+ exited: boolean
100
+ /** Set when this client killed it, so the rejection says why. */
101
+ killedFor?: 'timeout' | 'dispose'
102
+ readonly closed: Promise<void>
103
+ }
104
+
105
+ const STDERR_TAIL_BYTES = 4_000
106
+
107
+ export class McpStdioClient {
108
+ private running: Running | undefined
109
+ private starting: Promise<Running> | undefined
110
+ private nextId = 1
111
+ private disposed = false
112
+ private startCount = 0
113
+
114
+ constructor(private readonly options: McpStdioClientOptions) {}
115
+
116
+ /** How many processes this client has started; a restart counts again. */
117
+ get starts(): number {
118
+ return this.startCount
119
+ }
120
+
121
+ /** The running process's id on this side, if one is running. */
122
+ get pid(): number | undefined {
123
+ return this.running && !this.running.exited ? this.running.child.pid : undefined
124
+ }
125
+
126
+ /** Start the server now, rather than on the first call. */
127
+ async start(): Promise<void> {
128
+ await this.ensureStarted()
129
+ }
130
+
131
+ /** Call one tool. Rejects with {@link McpToolError} when the server says the tool failed. */
132
+ async callTool(
133
+ name: string,
134
+ args: Record<string, unknown> = {},
135
+ timeoutMs?: number,
136
+ ): Promise<McpToolResult> {
137
+ const running = await this.ensureStarted()
138
+ return this.callOn(running, name, args, timeoutMs)
139
+ }
140
+
141
+ async dispose(): Promise<void> {
142
+ this.disposed = true
143
+ const running = this.running ?? (await this.starting?.catch(() => undefined))
144
+ if (!running || running.exited) return
145
+ running.killedFor = 'dispose'
146
+ running.child.stdin.end()
147
+ let timer: NodeJS.Timeout | undefined
148
+ const late = new Promise<'late'>((resolve) => {
149
+ timer = setTimeout(() => resolve('late'), 2_000)
150
+ })
151
+ const outcome = await Promise.race([running.closed.then(() => 'closed' as const), late])
152
+ clearTimeout(timer)
153
+ if (outcome === 'late') {
154
+ running.child.kill('SIGKILL')
155
+ await running.closed
156
+ }
157
+ }
158
+
159
+ private async ensureStarted(): Promise<Running> {
160
+ if (this.disposed) throw new Error(`${this.options.command}: the client was disposed.`)
161
+ if (this.running && !this.running.exited) return this.running
162
+ if (!this.starting) {
163
+ this.starting = this.startProcess().finally(() => {
164
+ this.starting = undefined
165
+ })
166
+ }
167
+ return this.starting
168
+ }
169
+
170
+ private async startProcess(): Promise<Running> {
171
+ const { command, args, env, cwd } = this.options
172
+ let child: ChildProcessWithoutNullStreams
173
+ try {
174
+ child = this.options.spawnProcess
175
+ ? this.options.spawnProcess(command, args, { env, cwd })
176
+ : spawn(command, args as string[], {
177
+ env,
178
+ cwd,
179
+ stdio: ['pipe', 'pipe', 'pipe'],
180
+ windowsHide: true,
181
+ })
182
+ } catch (error) {
183
+ throw new Error(
184
+ `Could not start ${command}: ${error instanceof Error ? error.message : String(error)}`,
185
+ )
186
+ }
187
+ this.startCount++
188
+ let markClosed: () => void = () => undefined
189
+ const running: Running = {
190
+ child,
191
+ pending: new Map(),
192
+ stderr: [],
193
+ exited: false,
194
+ closed: new Promise<void>((resolve) => {
195
+ markClosed = resolve
196
+ }),
197
+ }
198
+ let spawnError: Error | undefined
199
+ child.stdin.on('error', () => undefined)
200
+ child.stderr.setEncoding('utf8')
201
+ child.stderr.on('data', (text: string) => {
202
+ running.stderr.push(text)
203
+ let total = running.stderr.reduce((sum, part) => sum + part.length, 0)
204
+ while (total > STDERR_TAIL_BYTES && running.stderr.length > 1) {
205
+ total -= running.stderr.shift()?.length ?? 0
206
+ }
207
+ })
208
+ const splitter = new LineSplitter((line) => this.onLine(running, line))
209
+ child.stdout.on('data', (chunk: Buffer) => splitter.push(chunk))
210
+ const onGone = (exitCode: number | null, signal: NodeJS.Signals | null) => {
211
+ if (running.exited) return
212
+ running.exited = true
213
+ if (this.running === running) this.running = undefined
214
+ const timedOut = running.killedFor === 'timeout'
215
+ for (const [id, pending] of running.pending) {
216
+ clearTimeout(pending.timer)
217
+ running.pending.delete(id)
218
+ pending.reject(
219
+ this.lostRequest(running, pending.method, exitCode, signal, timedOut, spawnError),
220
+ )
221
+ }
222
+ markClosed()
223
+ }
224
+ child.once('error', (error) => {
225
+ spawnError = error
226
+ onGone(null, null)
227
+ })
228
+ child.once('close', (code, signal) => onGone(code, signal))
229
+
230
+ try {
231
+ await this.request(
232
+ running,
233
+ 'initialize',
234
+ {
235
+ protocolVersion: this.options.protocolVersion ?? '2025-06-18',
236
+ capabilities: {},
237
+ clientInfo: {
238
+ name: this.options.clientName ?? 'namzu-computer-use',
239
+ version: this.options.clientVersion ?? '0',
240
+ },
241
+ },
242
+ this.options.startTimeoutMs ?? 20_000,
243
+ )
244
+ this.notify(running, 'notifications/initialized')
245
+ if (this.options.afterStart) {
246
+ await this.options.afterStart((name, toolArgs, timeoutMs) =>
247
+ this.callOn(running, name, toolArgs ?? {}, timeoutMs),
248
+ )
249
+ }
250
+ } catch (error) {
251
+ if (!running.exited) {
252
+ running.child.kill('SIGKILL')
253
+ await running.closed
254
+ }
255
+ const reason = error instanceof Error ? error.message : String(error)
256
+ throw new Error(`${command} did not start: ${reason}${tail(running.stderr)}`)
257
+ }
258
+ if (this.disposed) {
259
+ running.child.kill('SIGKILL')
260
+ throw new Error(`${command}: the client was disposed.`)
261
+ }
262
+ this.running = running
263
+ return running
264
+ }
265
+
266
+ private async callOn(
267
+ running: Running,
268
+ name: string,
269
+ args: Record<string, unknown>,
270
+ timeoutMs?: number,
271
+ ): Promise<McpToolResult> {
272
+ const raw = (await this.request(
273
+ running,
274
+ 'tools/call',
275
+ { name, arguments: args },
276
+ timeoutMs ?? this.options.requestTimeoutMs ?? 15_000,
277
+ )) as {
278
+ content?: unknown
279
+ structuredContent?: unknown
280
+ isError?: unknown
281
+ } | null
282
+ const content = Array.isArray(raw?.content) ? (raw.content as McpContent[]) : []
283
+ const structuredContent =
284
+ raw?.structuredContent && typeof raw.structuredContent === 'object'
285
+ ? (raw.structuredContent as Record<string, unknown>)
286
+ : undefined
287
+ if (raw?.isError === true) {
288
+ const text = content
289
+ .filter((part): part is { type: 'text'; text: string } => part.type === 'text')
290
+ .map((part) => part.text)
291
+ .join('\n')
292
+ .trim()
293
+ throw new McpToolError(name, text || `${name} failed without saying why.`, structuredContent)
294
+ }
295
+ return structuredContent === undefined ? { content } : { content, structuredContent }
296
+ }
297
+
298
+ private request(
299
+ running: Running,
300
+ method: string,
301
+ params: unknown,
302
+ timeoutMs: number,
303
+ ): Promise<unknown> {
304
+ if (running.exited) {
305
+ return Promise.reject(new Error(`${this.options.command} is not running.`))
306
+ }
307
+ if (this.disposed && running.killedFor === 'dispose') {
308
+ return Promise.reject(new Error(`${this.options.command}: the client was disposed.`))
309
+ }
310
+ const id = this.nextId++
311
+ return new Promise((resolve, reject) => {
312
+ const timer = setTimeout(() => {
313
+ if (!running.pending.has(id)) return
314
+ // Unresponsive: kill it. The close handler rejects this request
315
+ // (and any other in flight) as timed out; the next call restarts.
316
+ running.killedFor = 'timeout'
317
+ running.child.kill('SIGKILL')
318
+ }, timeoutMs)
319
+ running.pending.set(id, { method, resolve, reject, timer })
320
+ running.child.stdin.write(`${JSON.stringify({ jsonrpc: '2.0', id, method, params })}\n`)
321
+ })
322
+ }
323
+
324
+ private notify(running: Running, method: string, params?: unknown): void {
325
+ if (running.exited) return
326
+ const message =
327
+ params === undefined ? { jsonrpc: '2.0', method } : { jsonrpc: '2.0', method, params }
328
+ running.child.stdin.write(`${JSON.stringify(message)}\n`)
329
+ }
330
+
331
+ private onLine(running: Running, line: Buffer): void {
332
+ if (line.length === 0) return
333
+ let message: {
334
+ id?: unknown
335
+ method?: unknown
336
+ result?: unknown
337
+ error?: { code?: unknown; message?: unknown }
338
+ }
339
+ try {
340
+ message = JSON.parse(line.toString('utf8'))
341
+ } catch {
342
+ return // Not protocol: a stray line a server printed to stdout.
343
+ }
344
+ if (typeof message !== 'object' || message === null) return
345
+ if (typeof message.method === 'string') {
346
+ // A request from the server (it has an id) gets an answer so it does
347
+ // not wait; nothing this client offers is ever asked for, except ping.
348
+ if (message.id !== undefined && message.id !== null && !running.exited) {
349
+ const reply =
350
+ message.method === 'ping'
351
+ ? { jsonrpc: '2.0', id: message.id, result: {} }
352
+ : {
353
+ jsonrpc: '2.0',
354
+ id: message.id,
355
+ error: { code: -32601, message: `Method not found: ${message.method}` },
356
+ }
357
+ running.child.stdin.write(`${JSON.stringify(reply)}\n`)
358
+ }
359
+ return
360
+ }
361
+ if (typeof message.id !== 'number') return
362
+ const pending = running.pending.get(message.id)
363
+ if (!pending) return
364
+ running.pending.delete(message.id)
365
+ clearTimeout(pending.timer)
366
+ if (message.error) {
367
+ pending.reject(
368
+ new McpProtocolError(
369
+ pending.method,
370
+ typeof message.error.code === 'number' ? message.error.code : -32603,
371
+ typeof message.error.message === 'string' ? message.error.message : 'unknown error',
372
+ ),
373
+ )
374
+ return
375
+ }
376
+ pending.resolve(message.result)
377
+ }
378
+
379
+ private lostRequest(
380
+ running: Running,
381
+ method: string,
382
+ exitCode: number | null,
383
+ signal: NodeJS.Signals | null,
384
+ timedOut: boolean,
385
+ spawnError: Error | undefined,
386
+ ): Error {
387
+ const { command, args } = this.options
388
+ const stderr = running.stderr.join('')
389
+ if (spawnError) return new Error(`Could not start ${command}: ${spawnError.message}`)
390
+ const message = timedOut
391
+ ? `${command} did not answer ${method} in time and was stopped.${tail(running.stderr)}`
392
+ : running.killedFor === 'dispose'
393
+ ? `${command} was stopped before it answered ${method}.`
394
+ : `${command} exited (code ${exitCode ?? 'none'}${signal ? `, ${signal}` : ''}) before it answered ${method}.${tail(running.stderr)}`
395
+ return new SpawnError(
396
+ message,
397
+ { exitCode: exitCode ?? -1, stdout: Buffer.alloc(0), stderr, timedOut, signal },
398
+ command,
399
+ args,
400
+ )
401
+ }
402
+ }
403
+
404
+ function tail(parts: readonly string[]): string {
405
+ const text = parts.join('').trim()
406
+ if (text.length === 0) return ''
407
+ return ` It said: ${text.length > 600 ? `…${text.slice(-600)}` : text}`
408
+ }
409
+
410
+ const NEWLINE = 0x0a
411
+ const CARRIAGE_RETURN = 0x0d
412
+
413
+ /**
414
+ * Cuts a byte stream into lines at `\n` (a trailing `\r` is dropped). Chunks
415
+ * are kept as they arrive and joined once per line, so a screenshot's
416
+ * multi-megabyte line costs one copy.
417
+ */
418
+ export class LineSplitter {
419
+ private pending: Buffer[] = []
420
+ private pendingBytes = 0
421
+
422
+ constructor(private readonly onLine: (line: Buffer) => void) {}
423
+
424
+ push(chunk: Buffer): void {
425
+ let start = 0
426
+ for (;;) {
427
+ const at = chunk.indexOf(NEWLINE, start)
428
+ if (at === -1) break
429
+ let line: Buffer
430
+ const part = chunk.subarray(start, at)
431
+ if (this.pendingBytes > 0) {
432
+ this.pending.push(part)
433
+ line = Buffer.concat(this.pending, this.pendingBytes + part.length)
434
+ this.pending = []
435
+ this.pendingBytes = 0
436
+ } else {
437
+ line = part
438
+ }
439
+ if (line.length > 0 && line[line.length - 1] === CARRIAGE_RETURN) {
440
+ line = line.subarray(0, line.length - 1)
441
+ }
442
+ this.onLine(line)
443
+ start = at + 1
444
+ }
445
+ if (start < chunk.length) {
446
+ const rest = chunk.subarray(start)
447
+ this.pending.push(rest)
448
+ this.pendingBytes += rest.length
449
+ }
450
+ }
451
+ }
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Our key input (`ctrl+c`, `ENTER`, `alt+F4`, `/`) → the cua-driver call that
3
+ * presses it.
4
+ *
5
+ * cua-driver's key vocabulary is `return`, `tab`, `escape`, `backspace`,
6
+ * `delete`, `insert`, arrows, `space`, `home`, `end`, `pageup`, `pagedown`,
7
+ * `f1`–`f12`, letters and digits, with modifiers `ctrl`, `shift`, `alt` and
8
+ * `win`. A single printable character pressed on its own is sent as text
9
+ * instead: cua-driver resolves a punctuation key to a virtual key without its
10
+ * shift state, so on a Turkish layout `/` (Shift+7) arrived as `7`. Text goes
11
+ * through the layout-independent Unicode path and arrives as written.
12
+ */
13
+
14
+ export type CuaKeyPlan =
15
+ | { readonly tool: 'press_key'; readonly key: string }
16
+ | { readonly tool: 'hotkey'; readonly keys: readonly string[] }
17
+ | { readonly tool: 'type_text'; readonly text: string }
18
+
19
+ const MODIFIERS: Readonly<Record<string, string>> = {
20
+ ctrl: 'ctrl',
21
+ control: 'ctrl',
22
+ // A model trained on macOS shortcuts asks for cmd+c; on Windows that is ctrl+c.
23
+ cmd: 'ctrl',
24
+ command: 'ctrl',
25
+ meta: 'ctrl',
26
+ alt: 'alt',
27
+ option: 'alt',
28
+ opt: 'alt',
29
+ shift: 'shift',
30
+ win: 'win',
31
+ windows: 'win',
32
+ super: 'win',
33
+ }
34
+
35
+ const NAMED_KEYS: Readonly<Record<string, string>> = {
36
+ enter: 'return',
37
+ return: 'return',
38
+ esc: 'escape',
39
+ escape: 'escape',
40
+ tab: 'tab',
41
+ backspace: 'backspace',
42
+ back_space: 'backspace',
43
+ delete: 'delete',
44
+ del: 'delete',
45
+ forward_delete: 'delete',
46
+ insert: 'insert',
47
+ ins: 'insert',
48
+ space: 'space',
49
+ spacebar: 'space',
50
+ up: 'up',
51
+ down: 'down',
52
+ left: 'left',
53
+ right: 'right',
54
+ arrowup: 'up',
55
+ arrowdown: 'down',
56
+ arrowleft: 'left',
57
+ arrowright: 'right',
58
+ arrow_up: 'up',
59
+ arrow_down: 'down',
60
+ arrow_left: 'left',
61
+ arrow_right: 'right',
62
+ home: 'home',
63
+ end: 'end',
64
+ page_up: 'pageup',
65
+ pageup: 'pageup',
66
+ pgup: 'pageup',
67
+ page_down: 'pagedown',
68
+ pagedown: 'pagedown',
69
+ pgdn: 'pagedown',
70
+ plus: '+',
71
+ minus: '-',
72
+ }
73
+
74
+ /** Splits `ctrl++` and `+` correctly: a `+` is a key when it has nothing after it. */
75
+ function splitCombo(combo: string): string[] {
76
+ const trimmed = combo.trim()
77
+ if (trimmed === '+') return ['+']
78
+ const parts = trimmed.split('+').map((part) => part.trim())
79
+ if (trimmed.endsWith('++')) {
80
+ // "ctrl++" splits to ["ctrl", "", ""]: the last key is "+".
81
+ return [...parts.slice(0, -2).filter((part) => part.length > 0), '+']
82
+ }
83
+ return parts.filter((part) => part.length > 0)
84
+ }
85
+
86
+ export function translateKeyForCuaDriver(combo: string): CuaKeyPlan {
87
+ const parts = splitCombo(combo)
88
+ if (parts.length === 0) throw new Error('computer-use: empty key combo')
89
+ const main = parts[parts.length - 1] as string
90
+ const modifiers = parts.slice(0, -1).map((part) => {
91
+ const modifier = MODIFIERS[part.toLowerCase()]
92
+ if (!modifier) throw new Error(`computer-use: unknown modifier "${part}" in "${combo}"`)
93
+ return modifier
94
+ })
95
+ const lower = main.toLowerCase()
96
+ const mainAsModifier = MODIFIERS[lower]
97
+ const named = NAMED_KEYS[lower]
98
+ const key =
99
+ named ?? mainAsModifier ?? (/^f([1-9]|1[0-9]|2[0-4])$/.test(lower) ? lower : undefined)
100
+
101
+ if (modifiers.length === 0) {
102
+ if (key !== undefined && key.length > 1) return { tool: 'press_key', key }
103
+ // One printable character, pressed alone: send it as text so the layout
104
+ // cannot change it (and an uppercase letter stays uppercase).
105
+ const character = key ?? main
106
+ if ([...character].length === 1) return { tool: 'type_text', text: character }
107
+ return { tool: 'press_key', key: lower }
108
+ }
109
+ const finalKey = key ?? ([...main].length === 1 ? main.toLowerCase() : lower)
110
+ return { tool: 'hotkey', keys: [...new Set(modifiers), finalKey] }
111
+ }