@namzu/computer-use 4.2.1 → 4.3.1

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 (42) hide show
  1. package/CHANGELOG.md +16 -0
  2. package/README.md +5 -1
  3. package/dist/SubprocessComputerUseHost.d.ts +1 -1
  4. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  5. package/dist/adapters/cua-driver/adapter.d.ts +1 -1
  6. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  7. package/dist/adapters/cua-driver/adapter.js +4 -3
  8. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  9. package/dist/adapters/cua-driver/provision.d.ts +20 -0
  10. package/dist/adapters/cua-driver/provision.d.ts.map +1 -1
  11. package/dist/adapters/cua-driver/provision.js +59 -2
  12. package/dist/adapters/cua-driver/provision.js.map +1 -1
  13. package/dist/adapters/win32.d.ts +2 -0
  14. package/dist/adapters/win32.d.ts.map +1 -1
  15. package/dist/adapters/win32.js +1 -0
  16. package/dist/adapters/win32.js.map +1 -1
  17. package/dist/foreground/guard.js +3 -3
  18. package/dist/foreground/guard.js.map +1 -1
  19. package/dist/foreground/ladder.d.ts +15 -1
  20. package/dist/foreground/ladder.d.ts.map +1 -1
  21. package/dist/foreground/ladder.js +131 -33
  22. package/dist/foreground/ladder.js.map +1 -1
  23. package/dist/foreground/types.d.ts +15 -0
  24. package/dist/foreground/types.d.ts.map +1 -1
  25. package/dist/foreground/types.js.map +1 -1
  26. package/dist/foreground/windows-helper-script.d.ts.map +1 -1
  27. package/dist/foreground/windows-helper-script.js +8 -1
  28. package/dist/foreground/windows-helper-script.js.map +1 -1
  29. package/dist/foreground/windows-monitor.d.ts +33 -1
  30. package/dist/foreground/windows-monitor.d.ts.map +1 -1
  31. package/dist/foreground/windows-monitor.js +129 -6
  32. package/dist/foreground/windows-monitor.js.map +1 -1
  33. package/package.json +2 -2
  34. package/src/SubprocessComputerUseHost.ts +1 -1
  35. package/src/adapters/cua-driver/adapter.ts +9 -4
  36. package/src/adapters/cua-driver/provision.ts +72 -2
  37. package/src/adapters/win32.ts +3 -0
  38. package/src/foreground/guard.ts +3 -3
  39. package/src/foreground/ladder.ts +128 -27
  40. package/src/foreground/types.ts +15 -0
  41. package/src/foreground/windows-helper-script.ts +8 -1
  42. package/src/foreground/windows-monitor.ts +150 -7
@@ -17,10 +17,110 @@ import { WINDOWS_HELPER_SCRIPT } from './windows-helper-script.js'
17
17
  export interface HelperProcess {
18
18
  write(line: string): void
19
19
  onLine(handler: (line: string) => void): void
20
- onExit(handler: () => void): void
20
+ /** `info` is absent where the process cannot say how it ended. */
21
+ onExit(handler: (info?: HelperExit) => void): void
22
+ /**
23
+ * The process itself has ended, which can be before its streams close (a
24
+ * child that inherited them keeps them open). Absent where there is no such
25
+ * moment.
26
+ */
27
+ onEnded?(handler: () => void): void
21
28
  kill(): void
22
29
  }
23
30
 
31
+ /** How the helper process ended. */
32
+ export interface HelperExit {
33
+ readonly code?: number | null
34
+ readonly signal?: string | null
35
+ /** The tail of what it wrote to its error stream (about 2 KB). */
36
+ readonly stderr?: string
37
+ /** The process could not be started at all. */
38
+ readonly spawnError?: Error
39
+ }
40
+
41
+ /** Most of the helper's error stream that is kept. */
42
+ const STDERR_KEEP = 2_048
43
+ /** How long after the process ends its streams get to close before the exit is reported anyway, ms. */
44
+ const EXIT_GRACE_MS = 500
45
+ /** Longest cause line put in a reason. */
46
+ const CAUSE_MAX = 200
47
+
48
+ function xmlText(text: string): string {
49
+ return text
50
+ .replace(/_x([0-9A-Fa-f]{4})_/g, (_, hex: string) =>
51
+ String.fromCharCode(Number.parseInt(hex, 16)),
52
+ )
53
+ .replace(/&lt;/g, '<')
54
+ .replace(/&gt;/g, '>')
55
+ .replace(/&quot;/g, '"')
56
+ .replace(/&apos;/g, "'")
57
+ .replace(/&amp;/g, '&')
58
+ }
59
+
60
+ /** Lines of a PowerShell error record that are location and category detail, not the message. */
61
+ function isRecordDetail(line: string): boolean {
62
+ return line.startsWith('+ ') || line.startsWith('At line:')
63
+ }
64
+
65
+ /**
66
+ * What the helper wrote to its error stream, reduced to its cause, or
67
+ * undefined. PowerShell wraps non-interactive output in a CLIXML envelope; its
68
+ * progress records ("Preparing modules for first use") are noise, its error
69
+ * records are the cause. The kept tail may begin in the middle of the envelope,
70
+ * so a fragment of it counts as CLIXML too. Of an error record the message
71
+ * (its first line) is reported, not the `+ CategoryInfo` lines after it.
72
+ */
73
+ export function stderrCause(stderr: string | undefined): string | undefined {
74
+ if (!stderr) return undefined
75
+ let text = stderr
76
+ let clixml = false
77
+ if (/CLIXML|<Objs[\s>]|<\/Objs>|<Obj |S="progress"/.test(text)) {
78
+ const errors: string[] = []
79
+ for (const match of text.matchAll(/<S S="Error">([\s\S]*?)<\/S>/g))
80
+ errors.push(xmlText(match[1] ?? ''))
81
+ // What is outside the error records is progress; none of it is a cause.
82
+ text = errors.join('')
83
+ clixml = true
84
+ }
85
+ const lines = text
86
+ .split(/\r?\n/)
87
+ .map((line) => line.trim())
88
+ .filter((line) => line && !line.startsWith('<'))
89
+ let cause: string | undefined
90
+ if (!clixml) {
91
+ cause = lines.filter((line) => !isRecordDetail(line)).pop()
92
+ } else {
93
+ cause = lastRecordMessage(lines)
94
+ }
95
+ if (!cause) return undefined
96
+ return cause.length > CAUSE_MAX ? `${cause.slice(0, CAUSE_MAX - 1)}…` : cause
97
+ }
98
+
99
+ /** An error record ends at its FullyQualifiedErrorId line; the message of the last one. */
100
+ function lastRecordMessage(lines: string[]): string | undefined {
101
+ const records: string[][] = [[]]
102
+ for (const line of lines) {
103
+ const current = records[records.length - 1] as string[]
104
+ if (!isRecordDetail(line)) current.push(line)
105
+ if (line.startsWith('+ FullyQualifiedErrorId')) records.push([])
106
+ }
107
+ return [...records].reverse().find((r) => r.length > 0)?.[0]
108
+ }
109
+
110
+ /** Why the helper is gone, in words the model can pass on. */
111
+ export function describeHelperExit(info: HelperExit | undefined, greeted: boolean): string {
112
+ if (!info) return 'the Windows helper exited'
113
+ if (info.spawnError) return `could not start Windows PowerShell (${info.spawnError.message})`
114
+ const how =
115
+ info.code !== null && info.code !== undefined
116
+ ? `exit code ${info.code}`
117
+ : info.signal
118
+ ? `signal ${info.signal}`
119
+ : undefined
120
+ const cause = stderrCause(info.stderr)
121
+ return `${greeted ? 'the Windows helper stopped' : 'the Windows helper stopped while starting'}${how ? ` (${how})` : ''}${cause ? `: ${cause}` : ''}`
122
+ }
123
+
24
124
  export interface WindowsMonitorOptions {
25
125
  /** Windows PowerShell, as this process starts it. */
26
126
  readonly powershell: string
@@ -43,6 +143,8 @@ interface Reply {
43
143
  readonly error?: string
44
144
  readonly hooks?: boolean
45
145
  readonly hookError?: string
146
+ /** PowerShell's language mode, sent when the helper could not compile its hook library. */
147
+ readonly languageMode?: string
46
148
  }
47
149
 
48
150
  /**
@@ -75,8 +177,15 @@ function spawnPowerShell(options: WindowsMonitorOptions): HelperProcess {
75
177
  '-EncodedCommand',
76
178
  encodeHelperCommand(),
77
179
  ],
78
- { env: options.env, stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true },
180
+ { env: options.env, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true },
79
181
  )
182
+ // Only the tail is kept, and the stream is always drained so a chatty helper cannot block.
183
+ let stderr = ''
184
+ child.stderr.setEncoding('utf8')
185
+ child.stderr.on('data', (chunk: string) => {
186
+ stderr = (stderr + chunk).slice(-STDERR_KEEP)
187
+ })
188
+ child.stderr.on('error', () => undefined)
80
189
  // Without a listener a helper that exits first turns a write into an uncaught error.
81
190
  child.stdin.on('error', () => undefined)
82
191
  child.stdin.write(`${helperScriptLine()}\n`)
@@ -86,8 +195,23 @@ function spawnPowerShell(options: WindowsMonitorOptions): HelperProcess {
86
195
  },
87
196
  onLine: (handler) => createInterface({ input: child.stdout }).on('line', handler),
88
197
  onExit: (handler) => {
198
+ let done = false
199
+ const finish = (info: HelperExit) => {
200
+ if (done) return
201
+ done = true
202
+ handler(info)
203
+ }
204
+ // `close` follows the end of the error stream, so its tail is complete.
205
+ child.once('close', (code, signal) => finish({ code, signal, stderr }))
206
+ // A grandchild holding the pipes can keep `close` from coming: after the
207
+ // process has ended, what was read so far is the answer.
208
+ child.once('exit', (code, signal) => {
209
+ setTimeout(() => finish({ code, signal, stderr }), EXIT_GRACE_MS).unref()
210
+ })
211
+ child.once('error', (spawnError) => finish({ spawnError, stderr }))
212
+ },
213
+ onEnded: (handler) => {
89
214
  child.once('exit', handler)
90
- child.once('error', handler)
91
215
  },
92
216
  kill: () => {
93
217
  try {
@@ -115,6 +239,14 @@ export class WindowsInputMonitor implements ForegroundMonitor {
115
239
  timer: ReturnType<typeof setTimeout>
116
240
  }> = []
117
241
  private exited = false
242
+ private exitReason: string | undefined
243
+ /** The helper has sent its first line. */
244
+ private greeted = false
245
+
246
+ /** The helper process is started and has not ended. */
247
+ get running(): boolean {
248
+ return this.proc !== undefined && !this.exited
249
+ }
118
250
 
119
251
  constructor(private readonly options: WindowsMonitorOptions) {}
120
252
 
@@ -125,18 +257,27 @@ export class WindowsInputMonitor implements ForegroundMonitor {
125
257
  )
126
258
  this.proc = proc
127
259
  proc.onLine((line) => this.onLine(line))
128
- proc.onExit(() => {
260
+ // Not running from the moment the process ends; the reason follows when its streams close.
261
+ proc.onEnded?.(() => {
262
+ this.exited = true
263
+ })
264
+ proc.onExit((info) => {
129
265
  this.exited = true
266
+ const reason = describeHelperExit(info, this.greeted)
267
+ if (info) this.exitReason = reason
130
268
  for (const waiter of this.waiting.splice(0)) {
131
269
  clearTimeout(waiter.timer)
132
- waiter.resolve({ ok: false, error: 'the Windows helper exited' })
270
+ waiter.resolve({ ok: false, error: reason })
133
271
  }
134
272
  })
135
273
  const hello = await this.expect(this.options.startTimeoutMs ?? 60_000)
136
274
  if (!hello.ok || hello.hooks !== true) {
137
275
  await this.dispose()
276
+ const why = hello.hookError || hello.error || 'the keyboard and mouse hooks did not start'
138
277
  throw new Error(
139
- hello.hookError || hello.error || 'the keyboard and mouse hooks did not start',
278
+ hello.languageMode && hello.languageMode !== 'FullLanguage'
279
+ ? `${why} (PowerShell language mode: ${hello.languageMode})`
280
+ : why,
140
281
  )
141
282
  }
142
283
  }
@@ -252,6 +393,7 @@ export class WindowsInputMonitor implements ForegroundMonitor {
252
393
  })
253
394
  return
254
395
  }
396
+ if (reply.id == null) this.greeted = true
255
397
  // A reply to a request that already timed out must not answer the next one.
256
398
  const index = reply.id == null ? 0 : this.waiting.findIndex((w) => w.id === reply.id)
257
399
  if (index < 0) return
@@ -277,7 +419,8 @@ export class WindowsInputMonitor implements ForegroundMonitor {
277
419
 
278
420
  private async call<T>(command: Record<string, unknown>): Promise<T> {
279
421
  const proc = this.proc
280
- if (!proc || this.exited) throw new Error('the Windows helper is not running')
422
+ if (!proc || this.exited)
423
+ throw new Error(this.exitReason ?? 'the Windows helper is not running')
281
424
  const id = this.nextId++
282
425
  const reply = this.expect(this.options.requestTimeoutMs ?? 10_000, id)
283
426
  proc.write(JSON.stringify({ ...command, id }))