@namzu/computer-use 3.0.0 → 4.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 (122) hide show
  1. package/CHANGELOG.md +64 -1
  2. package/README.md +37 -6
  3. package/dist/SubprocessComputerUseHost.d.ts +58 -7
  4. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  5. package/dist/SubprocessComputerUseHost.js +222 -35
  6. package/dist/SubprocessComputerUseHost.js.map +1 -1
  7. package/dist/adapters/cua-driver/adapter.d.ts +182 -13
  8. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  9. package/dist/adapters/cua-driver/adapter.js +1657 -121
  10. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  11. package/dist/adapters/cua-driver/client.d.ts +16 -0
  12. package/dist/adapters/cua-driver/client.d.ts.map +1 -1
  13. package/dist/adapters/cua-driver/client.js +54 -5
  14. package/dist/adapters/cua-driver/client.js.map +1 -1
  15. package/dist/adapters/cua-driver/escalation.d.ts +67 -0
  16. package/dist/adapters/cua-driver/escalation.d.ts.map +1 -0
  17. package/dist/adapters/cua-driver/escalation.js +82 -0
  18. package/dist/adapters/cua-driver/escalation.js.map +1 -0
  19. package/dist/adapters/cua-driver/keys.d.ts +5 -0
  20. package/dist/adapters/cua-driver/keys.d.ts.map +1 -1
  21. package/dist/adapters/cua-driver/keys.js +23 -0
  22. package/dist/adapters/cua-driver/keys.js.map +1 -1
  23. package/dist/adapters/cua-driver/observe.d.ts +99 -0
  24. package/dist/adapters/cua-driver/observe.d.ts.map +1 -0
  25. package/dist/adapters/cua-driver/observe.js +227 -0
  26. package/dist/adapters/cua-driver/observe.js.map +1 -0
  27. package/dist/adapters/cua-driver/ui-tree.d.ts +75 -2
  28. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  29. package/dist/adapters/cua-driver/ui-tree.js +142 -14
  30. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  31. package/dist/adapters/types.d.ts +6 -2
  32. package/dist/adapters/types.d.ts.map +1 -1
  33. package/dist/adapters/types.js.map +1 -1
  34. package/dist/adapters/win32.d.ts +10 -0
  35. package/dist/adapters/win32.d.ts.map +1 -1
  36. package/dist/adapters/win32.js +12 -2
  37. package/dist/adapters/win32.js.map +1 -1
  38. package/dist/errors.d.ts +19 -0
  39. package/dist/errors.d.ts.map +1 -1
  40. package/dist/errors.js +26 -0
  41. package/dist/errors.js.map +1 -1
  42. package/dist/foreground/guard.d.ts +31 -0
  43. package/dist/foreground/guard.d.ts.map +1 -0
  44. package/dist/foreground/guard.js +156 -0
  45. package/dist/foreground/guard.js.map +1 -0
  46. package/dist/foreground/index.d.ts +11 -0
  47. package/dist/foreground/index.d.ts.map +1 -0
  48. package/dist/foreground/index.js +7 -0
  49. package/dist/foreground/index.js.map +1 -0
  50. package/dist/foreground/ladder.d.ts +143 -0
  51. package/dist/foreground/ladder.d.ts.map +1 -0
  52. package/dist/foreground/ladder.js +505 -0
  53. package/dist/foreground/ladder.js.map +1 -0
  54. package/dist/foreground/lease.d.ts +69 -0
  55. package/dist/foreground/lease.d.ts.map +1 -0
  56. package/dist/foreground/lease.js +182 -0
  57. package/dist/foreground/lease.js.map +1 -0
  58. package/dist/foreground/types.d.ts +287 -0
  59. package/dist/foreground/types.d.ts.map +1 -0
  60. package/dist/foreground/types.js +32 -0
  61. package/dist/foreground/types.js.map +1 -0
  62. package/dist/foreground/windows-helper-script.d.ts +19 -0
  63. package/dist/foreground/windows-helper-script.d.ts.map +1 -0
  64. package/dist/foreground/windows-helper-script.js +472 -0
  65. package/dist/foreground/windows-helper-script.js.map +1 -0
  66. package/dist/foreground/windows-monitor.d.ts +75 -0
  67. package/dist/foreground/windows-monitor.d.ts.map +1 -0
  68. package/dist/foreground/windows-monitor.js +216 -0
  69. package/dist/foreground/windows-monitor.js.map +1 -0
  70. package/dist/foreground/windows.d.ts +21 -0
  71. package/dist/foreground/windows.d.ts.map +1 -0
  72. package/dist/foreground/windows.js +54 -0
  73. package/dist/foreground/windows.js.map +1 -0
  74. package/dist/index.d.ts +6 -1
  75. package/dist/index.d.ts.map +1 -1
  76. package/dist/index.js +3 -1
  77. package/dist/index.js.map +1 -1
  78. package/dist/presence/helper-script.d.ts +39 -0
  79. package/dist/presence/helper-script.d.ts.map +1 -0
  80. package/dist/presence/helper-script.js +320 -0
  81. package/dist/presence/helper-script.js.map +1 -0
  82. package/dist/presence/index.d.ts +6 -0
  83. package/dist/presence/index.d.ts.map +1 -0
  84. package/dist/presence/index.js +4 -0
  85. package/dist/presence/index.js.map +1 -0
  86. package/dist/presence/presence.d.ts +70 -0
  87. package/dist/presence/presence.d.ts.map +1 -0
  88. package/dist/presence/presence.js +147 -0
  89. package/dist/presence/presence.js.map +1 -0
  90. package/dist/presence/windows.d.ts +19 -0
  91. package/dist/presence/windows.d.ts.map +1 -0
  92. package/dist/presence/windows.js +39 -0
  93. package/dist/presence/windows.js.map +1 -0
  94. package/dist/util/call-scope.d.ts +34 -0
  95. package/dist/util/call-scope.d.ts.map +1 -0
  96. package/dist/util/call-scope.js +58 -0
  97. package/dist/util/call-scope.js.map +1 -0
  98. package/package.json +2 -2
  99. package/src/SubprocessComputerUseHost.ts +298 -35
  100. package/src/adapters/cua-driver/adapter.ts +1986 -137
  101. package/src/adapters/cua-driver/client.ts +59 -2
  102. package/src/adapters/cua-driver/escalation.ts +137 -0
  103. package/src/adapters/cua-driver/keys.ts +20 -0
  104. package/src/adapters/cua-driver/observe.ts +310 -0
  105. package/src/adapters/cua-driver/ui-tree.ts +219 -15
  106. package/src/adapters/types.ts +12 -1
  107. package/src/adapters/win32.ts +26 -3
  108. package/src/errors.ts +32 -0
  109. package/src/foreground/guard.ts +182 -0
  110. package/src/foreground/index.ts +45 -0
  111. package/src/foreground/ladder.ts +616 -0
  112. package/src/foreground/lease.ts +232 -0
  113. package/src/foreground/types.ts +318 -0
  114. package/src/foreground/windows-helper-script.ts +471 -0
  115. package/src/foreground/windows-monitor.ts +288 -0
  116. package/src/foreground/windows.ts +73 -0
  117. package/src/index.ts +15 -1
  118. package/src/presence/helper-script.ts +323 -0
  119. package/src/presence/index.ts +17 -0
  120. package/src/presence/presence.ts +195 -0
  121. package/src/presence/windows.ts +54 -0
  122. package/src/util/call-scope.ts +73 -0
@@ -0,0 +1,288 @@
1
+ import { spawn } from 'node:child_process'
2
+ import { createInterface } from 'node:readline'
3
+ import type {
4
+ EditTextRequest,
5
+ EditTextResult,
6
+ ForegroundMonitor,
7
+ MenuCommandRequest,
8
+ MenuCommandResult,
9
+ MonitorBurstEnd,
10
+ MonitorState,
11
+ SelectItemRequest,
12
+ SelectItemResult,
13
+ } from './types.js'
14
+ import { WINDOWS_HELPER_SCRIPT } from './windows-helper-script.js'
15
+
16
+ /** The ends of a started helper; the real one is a child process. */
17
+ export interface HelperProcess {
18
+ write(line: string): void
19
+ onLine(handler: (line: string) => void): void
20
+ onExit(handler: () => void): void
21
+ kill(): void
22
+ }
23
+
24
+ export interface WindowsMonitorOptions {
25
+ /** Windows PowerShell, as this process starts it. */
26
+ readonly powershell: string
27
+ readonly env?: NodeJS.ProcessEnv
28
+ /** Waiting for the first answer (compiling the helper), ms. Default 60 000. */
29
+ readonly startTimeoutMs?: number
30
+ /** Waiting for each later answer, ms. Default 10 000. */
31
+ readonly requestTimeoutMs?: number
32
+ /** How Windows names a path this process knows (the lease file). Default: unchanged. */
33
+ readonly toWindowsPath?: (path: string) => string
34
+ /** For tests. */
35
+ readonly spawnHelper?: (script: string) => HelperProcess
36
+ }
37
+
38
+ interface Reply {
39
+ /** Echo of the request's id; the first greeting has none. */
40
+ readonly id?: number
41
+ readonly ok: boolean
42
+ readonly r?: unknown
43
+ readonly error?: string
44
+ readonly hooks?: boolean
45
+ readonly hookError?: string
46
+ }
47
+
48
+ /**
49
+ * What PowerShell is started with: a bootstrap that reads the helper script
50
+ * from the first line of its input (UTF-8, base64) and runs it, so the script
51
+ * can grow past the 32 767 characters a command line allows. The line protocol
52
+ * follows on the same stream.
53
+ */
54
+ export const HELPER_BOOTSTRAP =
55
+ '$s=[Console]::In.ReadLine();Invoke-Expression ([Text.Encoding]::UTF8.GetString([Convert]::FromBase64String($s)))'
56
+
57
+ /** The bootstrap as PowerShell's `-EncodedCommand` takes it. */
58
+ export function encodeHelperCommand(script: string = HELPER_BOOTSTRAP): string {
59
+ return Buffer.from(script, 'utf16le').toString('base64')
60
+ }
61
+
62
+ /** The first line written to a helper started with {@link HELPER_BOOTSTRAP}. */
63
+ export function helperScriptLine(script: string = WINDOWS_HELPER_SCRIPT): string {
64
+ return Buffer.from(script, 'utf8').toString('base64')
65
+ }
66
+
67
+ function spawnPowerShell(options: WindowsMonitorOptions): HelperProcess {
68
+ const child = spawn(
69
+ options.powershell,
70
+ [
71
+ '-NoProfile',
72
+ '-NonInteractive',
73
+ '-ExecutionPolicy',
74
+ 'Bypass',
75
+ '-EncodedCommand',
76
+ encodeHelperCommand(),
77
+ ],
78
+ { env: options.env, stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true },
79
+ )
80
+ // Without a listener a helper that exits first turns a write into an uncaught error.
81
+ child.stdin.on('error', () => undefined)
82
+ child.stdin.write(`${helperScriptLine()}\n`)
83
+ return {
84
+ write: (line) => {
85
+ child.stdin.write(`${line}\n`)
86
+ },
87
+ onLine: (handler) => createInterface({ input: child.stdout }).on('line', handler),
88
+ onExit: (handler) => {
89
+ child.once('exit', handler)
90
+ child.once('error', handler)
91
+ },
92
+ kill: () => {
93
+ try {
94
+ // Closing stdin lets the helper put back what a burst moved before it exits.
95
+ child.stdin.end()
96
+ } catch {
97
+ // Already closed.
98
+ }
99
+ setTimeout(() => child.kill(), 3_000).unref()
100
+ },
101
+ }
102
+ }
103
+
104
+ /**
105
+ * A {@link ForegroundMonitor} backed by the long-lived PowerShell helper.
106
+ * One poll answers in well under a millisecond once it runs; starting it
107
+ * compiles a small hook library and takes about half a second warm.
108
+ */
109
+ export class WindowsInputMonitor implements ForegroundMonitor {
110
+ private proc: HelperProcess | undefined
111
+ private nextId = 1
112
+ private waiting: Array<{
113
+ id: number
114
+ resolve: (reply: Reply) => void
115
+ timer: ReturnType<typeof setTimeout>
116
+ }> = []
117
+ private exited = false
118
+
119
+ constructor(private readonly options: WindowsMonitorOptions) {}
120
+
121
+ async start(): Promise<void> {
122
+ if (this.proc) return
123
+ const proc = (this.options.spawnHelper ?? (() => spawnPowerShell(this.options)))(
124
+ WINDOWS_HELPER_SCRIPT,
125
+ )
126
+ this.proc = proc
127
+ proc.onLine((line) => this.onLine(line))
128
+ proc.onExit(() => {
129
+ this.exited = true
130
+ for (const waiter of this.waiting.splice(0)) {
131
+ clearTimeout(waiter.timer)
132
+ waiter.resolve({ ok: false, error: 'the Windows helper exited' })
133
+ }
134
+ })
135
+ const hello = await this.expect(this.options.startTimeoutMs ?? 60_000)
136
+ if (!hello.ok || hello.hooks !== true) {
137
+ await this.dispose()
138
+ throw new Error(
139
+ hello.hookError || hello.error || 'the keyboard and mouse hooks did not start',
140
+ )
141
+ }
142
+ }
143
+
144
+ state(query: { readonly pid?: number } = {}): Promise<MonitorState> {
145
+ return this.call<MonitorState>({
146
+ cmd: 'state',
147
+ ...(query.pid !== undefined ? { pid: query.pid } : {}),
148
+ })
149
+ }
150
+
151
+ begin(args: {
152
+ readonly leasePath: string
153
+ readonly token: string
154
+ readonly raise?: string
155
+ readonly idleMs?: number
156
+ }): Promise<MonitorState & { readonly raised?: boolean; readonly refused?: boolean }> {
157
+ return this.call<MonitorState & { readonly raised?: boolean; readonly refused?: boolean }>({
158
+ cmd: 'begin',
159
+ lease: this.winPath(args.leasePath),
160
+ token: args.token,
161
+ ...(args.raise !== undefined ? { raise: args.raise } : {}),
162
+ ...(args.idleMs !== undefined ? { idleMs: args.idleMs } : {}),
163
+ })
164
+ }
165
+
166
+ end(args: {
167
+ readonly restore: boolean
168
+ readonly keepCursor?: boolean
169
+ }): Promise<MonitorBurstEnd> {
170
+ return this.call<MonitorBurstEnd>({
171
+ cmd: 'end',
172
+ restore: args.restore,
173
+ keepCursor: args.keepCursor === true,
174
+ })
175
+ }
176
+
177
+ editText(request: EditTextRequest): Promise<EditTextResult> {
178
+ return this.call<EditTextResult>({
179
+ cmd: 'edit',
180
+ hwnd: request.hwnd,
181
+ op: request.op,
182
+ pick: request.pick,
183
+ ...(request.text !== undefined ? { text: request.text } : {}),
184
+ ...(request.at ? { x: Math.round(request.at.x), y: Math.round(request.at.y) } : {}),
185
+ })
186
+ }
187
+
188
+ menuCommand(request: MenuCommandRequest): Promise<MenuCommandResult> {
189
+ return this.call<MenuCommandResult>({
190
+ cmd: 'menu',
191
+ hwnd: request.hwnd,
192
+ accel: request.accelerator,
193
+ })
194
+ }
195
+
196
+ selectItem(request: SelectItemRequest): Promise<SelectItemResult> {
197
+ return this.call<SelectItemResult>({
198
+ cmd: 'select',
199
+ hwnd: request.hwnd,
200
+ role: request.role,
201
+ name: request.name,
202
+ ...(request.automationId ? { autoId: request.automationId } : {}),
203
+ ...(request.bounds
204
+ ? {
205
+ x: Math.round(request.bounds.x),
206
+ y: Math.round(request.bounds.y),
207
+ w: Math.round(request.bounds.width),
208
+ h: Math.round(request.bounds.height),
209
+ }
210
+ : {}),
211
+ })
212
+ }
213
+
214
+ async release(args: {
215
+ readonly leasePath: string
216
+ readonly token: string
217
+ }): Promise<void> {
218
+ await this.call({
219
+ cmd: 'release',
220
+ lease: this.winPath(args.leasePath),
221
+ token: args.token,
222
+ })
223
+ }
224
+
225
+ async dispose(): Promise<void> {
226
+ const proc = this.proc
227
+ this.proc = undefined
228
+ if (!proc) return
229
+ for (const waiter of this.waiting.splice(0)) {
230
+ clearTimeout(waiter.timer)
231
+ waiter.resolve({ ok: false, error: 'the Windows helper was stopped' })
232
+ }
233
+ proc.kill()
234
+ }
235
+
236
+ private winPath(path: string): string {
237
+ return this.options.toWindowsPath ? this.options.toWindowsPath(path) : path
238
+ }
239
+
240
+ private onLine(line: string): void {
241
+ let reply: Reply
242
+ try {
243
+ reply = JSON.parse(line) as Reply
244
+ } catch {
245
+ // Cannot tell whose it was: the oldest request is the likeliest.
246
+ const waiter = this.waiting.shift()
247
+ if (!waiter) return
248
+ clearTimeout(waiter.timer)
249
+ waiter.resolve({
250
+ ok: false,
251
+ error: `unreadable helper reply: ${line.slice(0, 120)}`,
252
+ })
253
+ return
254
+ }
255
+ // A reply to a request that already timed out must not answer the next one.
256
+ const index = reply.id == null ? 0 : this.waiting.findIndex((w) => w.id === reply.id)
257
+ if (index < 0) return
258
+ const [waiter] = this.waiting.splice(index, 1)
259
+ if (!waiter) return
260
+ clearTimeout(waiter.timer)
261
+ waiter.resolve(reply)
262
+ }
263
+
264
+ private expect(timeoutMs: number, id = 0): Promise<Reply> {
265
+ return new Promise<Reply>((resolve) => {
266
+ const timer = setTimeout(() => {
267
+ const index = this.waiting.findIndex((waiter) => waiter.resolve === resolve)
268
+ if (index >= 0) this.waiting.splice(index, 1)
269
+ resolve({
270
+ ok: false,
271
+ error: 'the Windows helper did not answer in time',
272
+ })
273
+ }, timeoutMs)
274
+ this.waiting.push({ id, resolve, timer })
275
+ })
276
+ }
277
+
278
+ private async call<T>(command: Record<string, unknown>): Promise<T> {
279
+ const proc = this.proc
280
+ if (!proc || this.exited) throw new Error('the Windows helper is not running')
281
+ const id = this.nextId++
282
+ const reply = this.expect(this.options.requestTimeoutMs ?? 10_000, id)
283
+ proc.write(JSON.stringify({ ...command, id }))
284
+ const answer = await reply
285
+ if (!answer.ok) throw new Error(answer.error ?? 'the Windows helper failed')
286
+ return answer.r as T
287
+ }
288
+ }
@@ -0,0 +1,73 @@
1
+ import { homedir } from 'node:os'
2
+ import { join } from 'node:path'
3
+ import {
4
+ type WslProbes,
5
+ isWsl,
6
+ realWslProbes,
7
+ wslChildEnv,
8
+ wslPowerShellPath,
9
+ } from '../adapters/wsl.js'
10
+ import { ForegroundLadder, type LadderTiming } from './ladder.js'
11
+ import type { ForegroundApprover } from './types.js'
12
+ import { WindowsInputMonitor } from './windows-monitor.js'
13
+
14
+ /** Variable names never handed to a helper process. */
15
+ const SECRET_NAME = /(API_?KEY|TOKEN|SECRET|PASSWORD|PASSWD|CREDENTIAL)/i
16
+
17
+ export interface WindowsLadderOptions {
18
+ readonly env?: NodeJS.ProcessEnv
19
+ readonly platform?: NodeJS.Platform
20
+ readonly wslProbes?: WslProbes
21
+ readonly approve?: ForegroundApprover
22
+ readonly session?: string
23
+ readonly timing?: Partial<LadderTiming>
24
+ }
25
+
26
+ /** `<NAMZU_HOME>/computer-use/screen.lease`, `NAMZU_HOME` defaulting to `~/.namzu`. */
27
+ export function screenLeasePath(env: NodeJS.ProcessEnv = process.env): string {
28
+ const home =
29
+ env.NAMZU_HOME && env.NAMZU_HOME.length > 0 ? env.NAMZU_HOME : join(homedir(), '.namzu')
30
+ return join(home, 'computer-use', 'screen.lease')
31
+ }
32
+
33
+ /** A path as Windows names it: a Linux path under WSL goes through the distro's share. */
34
+ export function windowsPathFor(path: string, env: NodeJS.ProcessEnv): string {
35
+ const distro = env.WSL_DISTRO_NAME
36
+ if (!path.startsWith('/') || !distro) return path
37
+ return `\\\\wsl.localhost\\${distro}${path.replace(/\//g, '\\')}`
38
+ }
39
+
40
+ /**
41
+ * The foreground ladder for this machine's Windows desktop (WSL included), or
42
+ * undefined where there is no Windows PowerShell to run the helper in.
43
+ */
44
+ export function createWindowsForegroundLadder(
45
+ options: WindowsLadderOptions = {},
46
+ ): ForegroundLadder | undefined {
47
+ const env = options.env ?? process.env
48
+ const platform = options.platform ?? process.platform
49
+ const probes = options.wslProbes ?? realWslProbes
50
+ const wsl = isWsl(env, platform, probes)
51
+ const powershell = wsl
52
+ ? wslPowerShellPath(probes)
53
+ : platform === 'win32'
54
+ ? 'powershell.exe'
55
+ : undefined
56
+ if (!powershell) return undefined
57
+ const clean: NodeJS.ProcessEnv = {}
58
+ for (const [name, value] of Object.entries(env)) if (!SECRET_NAME.test(name)) clean[name] = value
59
+ const helperEnv = wsl ? wslChildEnv(clean, [], probes) : clean
60
+ const leasePath = screenLeasePath(env)
61
+ return new ForegroundLadder({
62
+ leasePath,
63
+ createMonitor: () =>
64
+ new WindowsInputMonitor({
65
+ powershell,
66
+ env: helperEnv,
67
+ toWindowsPath: (path) => windowsPathFor(path, env),
68
+ }),
69
+ ...(options.approve ? { approve: options.approve } : {}),
70
+ ...(options.session ? { session: options.session } : {}),
71
+ ...(options.timing ? { timing: options.timing } : {}),
72
+ })
73
+ }
package/src/index.ts CHANGED
@@ -5,7 +5,19 @@ export type {
5
5
  } from './SubprocessComputerUseHost.js'
6
6
  export type { Win32Backend } from './adapters/win32.js'
7
7
  export { detectDisplayServer } from './detect/index.js'
8
- export { ComputerUseOutcomeUnknownError } from './errors.js'
8
+ export {
9
+ ComputerUseOutcomeUnknownError,
10
+ ComputerUseLockedError,
11
+ ComputerUseStoppedError,
12
+ } from './errors.js'
13
+ export type { SubprocessComputerUseHostForegroundOptions } from './SubprocessComputerUseHost.js'
14
+ export { DEFAULT_TIMING as FOREGROUND_DEFAULT_TIMING } from './foreground/index.js'
15
+ export type {
16
+ ForegroundAnswer,
17
+ ForegroundApprover,
18
+ ForegroundSubject,
19
+ LadderTiming,
20
+ } from './foreground/index.js'
9
21
 
10
22
  /**
11
23
  * The three failures a caller has to tell apart.
@@ -25,3 +37,5 @@ export {
25
37
  } from './adapters/types.js'
26
38
  export { SpawnError } from './util/spawn.js'
27
39
  export type { SpawnOptions, SpawnResult } from './util/spawn.js'
40
+ export { PRESENCE_ENV } from './presence/index.js'
41
+ export type { Presence, PresenceKind, PresenceMark } from './presence/index.js'