@namzu/computer-use 4.4.0 → 4.6.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 (139) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/SubprocessComputerUseHost.d.ts +8 -1
  3. package/dist/SubprocessComputerUseHost.d.ts.map +1 -1
  4. package/dist/SubprocessComputerUseHost.js +15 -4
  5. package/dist/SubprocessComputerUseHost.js.map +1 -1
  6. package/dist/a11y/a11y.d.ts +15 -7
  7. package/dist/a11y/a11y.d.ts.map +1 -1
  8. package/dist/a11y/a11y.js +12 -5
  9. package/dist/a11y/a11y.js.map +1 -1
  10. package/dist/a11y/index.d.ts +7 -1
  11. package/dist/a11y/index.d.ts.map +1 -1
  12. package/dist/a11y/index.js +4 -1
  13. package/dist/a11y/index.js.map +1 -1
  14. package/dist/a11y/macos-helper.d.ts +80 -0
  15. package/dist/a11y/macos-helper.d.ts.map +1 -0
  16. package/dist/a11y/macos-helper.js +436 -0
  17. package/dist/a11y/macos-helper.js.map +1 -0
  18. package/dist/a11y/macos-signing.d.ts +56 -0
  19. package/dist/a11y/macos-signing.d.ts.map +1 -0
  20. package/dist/a11y/macos-signing.js +228 -0
  21. package/dist/a11y/macos-signing.js.map +1 -0
  22. package/dist/a11y/macos.d.ts +173 -0
  23. package/dist/a11y/macos.d.ts.map +1 -0
  24. package/dist/a11y/macos.js +271 -0
  25. package/dist/a11y/macos.js.map +1 -0
  26. package/dist/a11y/windows.d.ts +14 -2
  27. package/dist/a11y/windows.d.ts.map +1 -1
  28. package/dist/a11y/windows.js +31 -6
  29. package/dist/a11y/windows.js.map +1 -1
  30. package/dist/adapters/cua-driver/adapter.d.ts.map +1 -1
  31. package/dist/adapters/cua-driver/adapter.js +48 -10
  32. package/dist/adapters/cua-driver/adapter.js.map +1 -1
  33. package/dist/adapters/cua-driver/ui-tree.d.ts +1 -0
  34. package/dist/adapters/cua-driver/ui-tree.d.ts.map +1 -1
  35. package/dist/adapters/cua-driver/ui-tree.js +2 -0
  36. package/dist/adapters/cua-driver/ui-tree.js.map +1 -1
  37. package/dist/adapters/darwin-ax.d.ts +94 -0
  38. package/dist/adapters/darwin-ax.d.ts.map +1 -0
  39. package/dist/adapters/darwin-ax.js +754 -0
  40. package/dist/adapters/darwin-ax.js.map +1 -0
  41. package/dist/adapters/darwin.d.ts +43 -2
  42. package/dist/adapters/darwin.d.ts.map +1 -1
  43. package/dist/adapters/darwin.js +145 -7
  44. package/dist/adapters/darwin.js.map +1 -1
  45. package/dist/adapters/png.d.ts +6 -0
  46. package/dist/adapters/png.d.ts.map +1 -0
  47. package/dist/adapters/png.js +7 -0
  48. package/dist/adapters/png.js.map +1 -0
  49. package/dist/adapters/win32-native.d.ts +53 -0
  50. package/dist/adapters/win32-native.d.ts.map +1 -0
  51. package/dist/adapters/win32-native.js +279 -0
  52. package/dist/adapters/win32-native.js.map +1 -0
  53. package/dist/adapters/win32.d.ts +19 -1
  54. package/dist/adapters/win32.d.ts.map +1 -1
  55. package/dist/adapters/win32.js +35 -8
  56. package/dist/adapters/win32.js.map +1 -1
  57. package/dist/foreground/ladder.d.ts.map +1 -1
  58. package/dist/foreground/ladder.js +5 -1
  59. package/dist/foreground/ladder.js.map +1 -1
  60. package/dist/foreground/types.d.ts +6 -0
  61. package/dist/foreground/types.d.ts.map +1 -1
  62. package/dist/foreground/types.js.map +1 -1
  63. package/dist/foreground/windows.d.ts +2 -0
  64. package/dist/foreground/windows.d.ts.map +1 -1
  65. package/dist/foreground/windows.js +24 -11
  66. package/dist/foreground/windows.js.map +1 -1
  67. package/dist/index.d.ts +9 -0
  68. package/dist/index.d.ts.map +1 -1
  69. package/dist/index.js +7 -0
  70. package/dist/index.js.map +1 -1
  71. package/dist/native/a11y.d.ts +61 -0
  72. package/dist/native/a11y.d.ts.map +1 -0
  73. package/dist/native/a11y.js +197 -0
  74. package/dist/native/a11y.js.map +1 -0
  75. package/dist/native/env.d.ts +19 -0
  76. package/dist/native/env.d.ts.map +1 -0
  77. package/dist/native/env.js +29 -0
  78. package/dist/native/env.js.map +1 -0
  79. package/dist/native/foreground-monitor.d.ts +51 -0
  80. package/dist/native/foreground-monitor.d.ts.map +1 -0
  81. package/dist/native/foreground-monitor.js +120 -0
  82. package/dist/native/foreground-monitor.js.map +1 -0
  83. package/dist/native/presence.d.ts +24 -0
  84. package/dist/native/presence.d.ts.map +1 -0
  85. package/dist/native/presence.js +47 -0
  86. package/dist/native/presence.js.map +1 -0
  87. package/dist/native/process.d.ts +73 -0
  88. package/dist/native/process.d.ts.map +1 -0
  89. package/dist/native/process.js +302 -0
  90. package/dist/native/process.js.map +1 -0
  91. package/dist/native/protocol.d.ts +476 -0
  92. package/dist/native/protocol.d.ts.map +1 -0
  93. package/dist/native/protocol.js +601 -0
  94. package/dist/native/protocol.js.map +1 -0
  95. package/dist/native/shared.d.ts +16 -0
  96. package/dist/native/shared.d.ts.map +1 -0
  97. package/dist/native/shared.js +62 -0
  98. package/dist/native/shared.js.map +1 -0
  99. package/dist/native/watch.d.ts +35 -0
  100. package/dist/native/watch.d.ts.map +1 -0
  101. package/dist/native/watch.js +45 -0
  102. package/dist/native/watch.js.map +1 -0
  103. package/dist/presence/presence.d.ts +3 -2
  104. package/dist/presence/presence.d.ts.map +1 -1
  105. package/dist/presence/presence.js.map +1 -1
  106. package/dist/presence/windows.d.ts +2 -0
  107. package/dist/presence/windows.d.ts.map +1 -1
  108. package/dist/presence/windows.js +15 -0
  109. package/dist/presence/windows.js.map +1 -1
  110. package/helper-macos/main.swift +1756 -0
  111. package/package.json +3 -2
  112. package/src/SubprocessComputerUseHost.ts +26 -2
  113. package/src/a11y/a11y.ts +25 -11
  114. package/src/a11y/index.ts +28 -1
  115. package/src/a11y/macos-helper.ts +538 -0
  116. package/src/a11y/macos-signing.ts +280 -0
  117. package/src/a11y/macos.ts +496 -0
  118. package/src/a11y/windows.ts +31 -4
  119. package/src/adapters/cua-driver/adapter.ts +55 -15
  120. package/src/adapters/cua-driver/ui-tree.ts +2 -0
  121. package/src/adapters/darwin-ax.ts +920 -0
  122. package/src/adapters/darwin.ts +184 -4
  123. package/src/adapters/png.ts +5 -0
  124. package/src/adapters/win32-native.ts +329 -0
  125. package/src/adapters/win32.ts +53 -5
  126. package/src/foreground/ladder.ts +5 -1
  127. package/src/foreground/types.ts +6 -0
  128. package/src/foreground/windows.ts +25 -11
  129. package/src/index.ts +14 -0
  130. package/src/native/a11y.ts +267 -0
  131. package/src/native/env.ts +33 -0
  132. package/src/native/foreground-monitor.ts +165 -0
  133. package/src/native/presence.ts +58 -0
  134. package/src/native/process.ts +347 -0
  135. package/src/native/protocol.ts +1103 -0
  136. package/src/native/shared.ts +75 -0
  137. package/src/native/watch.ts +78 -0
  138. package/src/presence/presence.ts +3 -2
  139. package/src/presence/windows.ts +15 -0
@@ -0,0 +1,165 @@
1
+ import { readFileSync, unlinkSync } from 'node:fs'
2
+ import type { ForegroundMonitor, MonitorBurstEnd, MonitorState } from '../foreground/types.js'
3
+ import type { NativeWinProcessOptions } from './process.js'
4
+ import type { NativeForegroundState, NativeMonitorPollReply } from './protocol.js'
5
+ import { type NativeHelper, shareNativeProcess } from './shared.js'
6
+
7
+ /**
8
+ * The foreground monitor on the native helper: it watches for a person's use
9
+ * of keyboard and mouse and for the window in front, without a global hook.
10
+ *
11
+ * The helper learns of input through Raw Input headers, which say that a
12
+ * device class sent something and when, never which key or button; what comes
13
+ * back here is a count. `escapes` is therefore always 0: the helper does not
14
+ * read keys, so it cannot tell Escape from any other key. A person who wants
15
+ * to stop a burst by using the machine does so by input, which the count sees.
16
+ *
17
+ * It replaces the PowerShell monitor (`WindowsInputMonitor`), which installed
18
+ * system-wide low-level keyboard and mouse hooks.
19
+ */
20
+ export interface NativeForegroundMonitorOptions extends NativeWinProcessOptions {
21
+ /** The path as the helper reads it (under WSL a Linux path goes through the distro's share). Default: unchanged. */
22
+ readonly toHelperPath?: (path: string) => string
23
+ }
24
+
25
+ const REQUEST_MS = 5_000
26
+
27
+ /** `0x1a2b` and `w:000000000000_1a2b` name the same window. */
28
+ function windowIdOf(hwnd: string): string {
29
+ const hex = hwnd.replace(/^0x/i, '').toLowerCase()
30
+ return `w:${hex.padStart(16, '0')}`
31
+ }
32
+
33
+ function hwndOf(windowId: string): string {
34
+ const m = /^w:([0-9a-f]+)/i.exec(windowId)
35
+ return `0x${(m?.[1] ?? '0').replace(/^0+(?=.)/, '').toUpperCase()}`
36
+ }
37
+
38
+ export class NativeForegroundMonitor implements ForegroundMonitor {
39
+ private readonly process: NativeHelper
40
+ private started = false
41
+
42
+ constructor(private readonly options: NativeForegroundMonitorOptions) {
43
+ this.process = shareNativeProcess(options)
44
+ }
45
+
46
+ get running(): boolean {
47
+ return this.started && this.process.isUp
48
+ }
49
+
50
+ async start(): Promise<void> {
51
+ if (this.started && this.process.isUp) return
52
+ if (!(await this.process.ready())) throw new Error('the native Windows helper did not start')
53
+ const caps = this.process.hello?.caps ?? []
54
+ if (!caps.includes('monitor')) {
55
+ throw new Error('the native Windows helper in use cannot watch for a person at the keyboard')
56
+ }
57
+ const watching = await this.process.request({ op: 'monitor.start' }, REQUEST_MS)
58
+ if (!watching.input) {
59
+ throw new Error('the native Windows helper could not register for keyboard and mouse use')
60
+ }
61
+ this.started = true
62
+ }
63
+
64
+ async state(query: { readonly pid?: number } = {}): Promise<MonitorState> {
65
+ const [fg, poll] = await Promise.all([
66
+ this.process.request(
67
+ { op: 'foreground.get', ...(query.pid !== undefined ? { processId: query.pid } : {}) },
68
+ REQUEST_MS,
69
+ ),
70
+ this.process.request({ op: 'monitor.poll' }, REQUEST_MS),
71
+ ])
72
+ return stateOf(fg, poll)
73
+ }
74
+
75
+ async begin(args: {
76
+ readonly leasePath: string
77
+ readonly token: string
78
+ readonly raise?: string
79
+ readonly watch?: string
80
+ readonly idleMs?: number
81
+ }): Promise<MonitorState & { readonly raised?: boolean; readonly refused?: boolean }> {
82
+ const to = this.options.toHelperPath ?? ((p: string) => p)
83
+ const reply = await this.process.request(
84
+ {
85
+ op: 'lease.begin',
86
+ ...(args.raise !== undefined
87
+ ? { windowId: windowIdOf(args.raise), raise: true }
88
+ : args.watch !== undefined
89
+ ? { windowId: windowIdOf(args.watch) }
90
+ : {}),
91
+ ...(args.idleMs !== undefined ? { idleMs: args.idleMs } : {}),
92
+ leasePath: to(args.leasePath),
93
+ token: args.token,
94
+ },
95
+ REQUEST_MS,
96
+ )
97
+ const poll = await this.process.request({ op: 'monitor.poll' }, REQUEST_MS)
98
+ return {
99
+ ...stateOf(reply, poll),
100
+ refused: reply.refused,
101
+ ...(reply.raised !== undefined ? { raised: reply.raised } : {}),
102
+ }
103
+ }
104
+
105
+ async end(args: {
106
+ readonly restore: boolean
107
+ readonly keepCursor?: boolean
108
+ }): Promise<MonitorBurstEnd> {
109
+ const reply = await this.process.request(
110
+ {
111
+ op: 'lease.end',
112
+ restore: args.restore,
113
+ ...(args.keepCursor ? { keepCursor: true } : {}),
114
+ },
115
+ REQUEST_MS,
116
+ )
117
+ return {
118
+ inputsDuring: reply.inputsDuring ?? 0,
119
+ escapesDuring: 0,
120
+ restoredForeground: reply.restoredForeground,
121
+ restoredCursor: reply.restoredCursor,
122
+ ...(reply.restoreNote !== undefined ? { restoreNote: reply.restoreNote } : {}),
123
+ inputMoved: reply.inputMoved,
124
+ frontElevated: reply.frontElevated,
125
+ }
126
+ }
127
+
128
+ /** Deletes the lease file when its token still matches. */
129
+ async release(args: { readonly leasePath: string; readonly token: string }): Promise<void> {
130
+ try {
131
+ const record = JSON.parse(readFileSync(args.leasePath, 'utf8')) as { token?: unknown }
132
+ if (record.token === args.token) unlinkSync(args.leasePath)
133
+ } catch {
134
+ // No file, or not ours: nothing to release.
135
+ }
136
+ }
137
+
138
+ async dispose(): Promise<void> {
139
+ this.started = false
140
+ await this.process.close()
141
+ }
142
+ }
143
+
144
+ function stateOf(fg: NativeForegroundState, poll: NativeMonitorPollReply): MonitorState {
145
+ return {
146
+ userIdleMs: fg.userIdleMs,
147
+ userInputs: poll.inputs,
148
+ escapes: 0,
149
+ foreground: fg.foreground
150
+ ? {
151
+ hwnd: hwndOf(fg.foreground.windowId),
152
+ pid: fg.foreground.processId,
153
+ exe: fg.foreground.exe,
154
+ elevated: fg.foreground.elevated,
155
+ integrity: fg.foreground.integrity,
156
+ }
157
+ : null,
158
+ cursor: fg.cursor,
159
+ desktop: fg.desktop,
160
+ selfElevated: fg.selfElevated,
161
+ selfIntegrity: fg.selfIntegrity,
162
+ inputTick: fg.inputTick,
163
+ ...(fg.target ? { target: fg.target } : {}),
164
+ }
165
+ }
@@ -0,0 +1,58 @@
1
+ import type { Presence, PresenceMark } from '../presence/presence.js'
2
+ import { NativeWinProcess, type NativeWinProcessOptions } from './process.js'
3
+
4
+ /**
5
+ * The presence overlay drawn by the native helper: the agent's cursor and a
6
+ * frame round the operated window, in two layered, click-through windows the
7
+ * helper owns. It takes no input and never changes the foreground window.
8
+ *
9
+ * The overlay is not excluded from screen capture. A screenshot may show it,
10
+ * and that is honest: the picture shows where the agent pointed. (The
11
+ * PowerShell overlay this replaces hid itself from capture, which together
12
+ * with a topmost transparent window reads as evasion.)
13
+ *
14
+ * A failure to show it never fails an action.
15
+ */
16
+ export class NativePresence implements Presence {
17
+ private readonly process: NativeWinProcess
18
+
19
+ constructor(options: NativeWinProcessOptions) {
20
+ this.process = new NativeWinProcess(options)
21
+ }
22
+
23
+ mark(mark: PresenceMark): void {
24
+ void this.process
25
+ .request(
26
+ {
27
+ op: 'presence.act',
28
+ windowId: windowIdOf(mark.hwnd),
29
+ kind: mark.kind,
30
+ ...(mark.at ? { at: { x: Math.round(mark.at.x), y: Math.round(mark.at.y) } } : {}),
31
+ },
32
+ 4_000,
33
+ )
34
+ .catch(() => undefined)
35
+ }
36
+
37
+ warm(): void {
38
+ this.process.warm()
39
+ }
40
+
41
+ hide(): void {
42
+ // Only a helper that is running has anything to hide.
43
+ if (this.process.isUp)
44
+ void this.process.request({ op: 'presence.hide' }, 4_000).catch(() => undefined)
45
+ }
46
+
47
+ release(): void {
48
+ this.process.release()
49
+ }
50
+
51
+ async dispose(): Promise<void> {
52
+ await this.process.close()
53
+ }
54
+ }
55
+
56
+ function windowIdOf(hwnd: number): string {
57
+ return `w:${hwnd.toString(16).padStart(16, '0')}`
58
+ }
@@ -0,0 +1,347 @@
1
+ /**
2
+ * The helper as a process: start it, greet it, send it requests as lines and
3
+ * match the replies to them by id.
4
+ *
5
+ * The helper is the compiled `namzu-native` executable. It is started directly,
6
+ * with no shell and no script engine, and answers JSON lines on its standard
7
+ * output. Everything the TypeScript side asks of it goes through
8
+ * {@link NativeWinProcess.request}, which gives a reply body or throws an
9
+ * {@link A11yError} carrying the helper's own error code.
10
+ */
11
+
12
+ import { spawn } from 'node:child_process'
13
+ import { createInterface } from 'node:readline'
14
+ import { A11yError } from '../a11y/interface.js'
15
+ import {
16
+ LEGACY_NATIVE_PROTOCOL,
17
+ NATIVE_PROTOCOL,
18
+ type NativeHello,
19
+ type NativeOp,
20
+ NativeProtocolError,
21
+ type NativeReplyBodies,
22
+ type NativeRequest,
23
+ decodeReply,
24
+ encodeRequest,
25
+ } from './protocol.js'
26
+
27
+ /** The ends of a started helper; the real one is a child process. */
28
+ export interface NativeChannel {
29
+ write(line: string): void
30
+ onLine(handler: (line: string) => void): void
31
+ onExit(handler: () => void): void
32
+ kill(): void
33
+ }
34
+
35
+ export interface NativeWinProcessOptions {
36
+ /** The path of `namzu-native.exe`. */
37
+ readonly executable: string
38
+ /** Sent in `hello`, so the helper's log can say who asked. */
39
+ readonly cliVersion?: string
40
+ readonly env?: NodeJS.ProcessEnv
41
+ /** For tests. */
42
+ readonly spawnHelper?: () => NativeChannel
43
+ /** Waiting for the greeting, ms. Default 10 000. */
44
+ readonly startTimeoutMs?: number
45
+ /** How many times a helper that ended mid-session is started again. Default 3. */
46
+ readonly maxRestarts?: number
47
+ /** A helper that ran this long before ending was healthy: the restart count starts again. Default 60 000. */
48
+ readonly stableAfterMs?: number
49
+ }
50
+
51
+ /** The client gives up on a reply this long after the helper should have sent it, ms. */
52
+ const BACKSTOP_MS = 1_500
53
+
54
+ function spawnHelperProcess(options: NativeWinProcessOptions): NativeChannel {
55
+ // The executable alone: no shell, no arguments, no window.
56
+ const child = spawn(options.executable, [], {
57
+ env: options.env,
58
+ stdio: ['pipe', 'pipe', 'ignore'],
59
+ windowsHide: true,
60
+ shell: false,
61
+ })
62
+ child.stdin.on('error', () => undefined)
63
+ child.on('error', () => undefined)
64
+ return {
65
+ write: (line) => {
66
+ child.stdin.write(`${line}\n`)
67
+ },
68
+ onLine: (handler) => createInterface({ input: child.stdout }).on('line', handler),
69
+ onExit: (handler) => {
70
+ child.once('exit', handler)
71
+ child.once('error', handler)
72
+ },
73
+ kill: () => {
74
+ try {
75
+ // Closing the input ends the helper by itself.
76
+ child.stdin.end()
77
+ } catch {
78
+ // Already closed.
79
+ }
80
+ setTimeout(() => child.kill(), 2_000).unref()
81
+ },
82
+ }
83
+ }
84
+
85
+ interface Pending {
86
+ readonly op: NativeOp
87
+ readonly resolve: (body: unknown) => void
88
+ readonly reject: (error: A11yError) => void
89
+ readonly timer: NodeJS.Timeout
90
+ readonly cleanup: () => void
91
+ }
92
+
93
+ export class NativeWinProcess {
94
+ private channel: NativeChannel | undefined
95
+ private starting: Promise<boolean> | undefined
96
+ private up = false
97
+ private dead = false
98
+ private closed = false
99
+ private restarts = 0
100
+ private runs = 0
101
+ private nextId = 1
102
+ private greeting: NativeHello | undefined
103
+ private readonly pending = new Map<number, Pending>()
104
+
105
+ constructor(private readonly options: NativeWinProcessOptions) {}
106
+
107
+ /** True once the helper greeted and has not ended since. */
108
+ get isUp(): boolean {
109
+ return this.up && !this.dead && !this.closed
110
+ }
111
+
112
+ /** Counts the helper's starts: a marker taken before a restart is stale. */
113
+ get epoch(): number {
114
+ return this.runs
115
+ }
116
+
117
+ /** What the helper said in `hello`, once it has. */
118
+ get hello(): NativeHello | undefined {
119
+ return this.greeting
120
+ }
121
+
122
+ warm(): void {
123
+ if (!this.dead && !this.closed) void this.start()
124
+ }
125
+
126
+ /** Ends the helper while nobody uses it; the next question starts it again. */
127
+ release(): void {
128
+ const channel = this.channel
129
+ if (!channel) return
130
+ // Replaced, not ended: its exit is not a crash (see the exit handler).
131
+ this.channel = undefined
132
+ this.starting = undefined
133
+ this.up = false
134
+ this.failAll(new A11yError('helper_exited', 'the native helper was released'))
135
+ this.sendQuit(channel)
136
+ }
137
+
138
+ ready(): Promise<boolean> {
139
+ if (this.dead || this.closed) return Promise.resolve(false)
140
+ return this.start()
141
+ }
142
+
143
+ async close(): Promise<void> {
144
+ this.closed = true
145
+ const channel = this.channel
146
+ this.channel = undefined
147
+ this.up = false
148
+ this.failAll(new A11yError('closed', 'the native helper was closed'))
149
+ if (channel) this.sendQuit(channel)
150
+ }
151
+
152
+ /**
153
+ * One request, one reply. `limitMs` is how long the helper has to answer
154
+ * (it is also what the request's own timeout says); a little more is
155
+ * allowed before the client gives up on a helper that says nothing.
156
+ */
157
+ async request<K extends NativeOp>(
158
+ request: NativeRequest & { readonly op: K },
159
+ limitMs: number,
160
+ signal?: AbortSignal,
161
+ ): Promise<NativeReplyBodies[K]> {
162
+ if (signal?.aborted) throw new A11yError('aborted', 'cancelled')
163
+ if (!(await this.ready())) throw new A11yError('unavailable', 'the native helper is off')
164
+ const channel = this.channel
165
+ if (!channel || !this.up) throw new A11yError('helper_exited', 'the native helper ended')
166
+ const id = this.nextId++
167
+ return new Promise<NativeReplyBodies[K]>((resolve, reject) => {
168
+ const settle = (): void => {
169
+ signal?.removeEventListener('abort', onAbort)
170
+ }
171
+ const onAbort = (): void => {
172
+ if (!this.pending.delete(id)) return
173
+ clearTimeout(timer)
174
+ this.cancelAtHelper(id)
175
+ reject(new A11yError('aborted', 'cancelled'))
176
+ }
177
+ const timer = setTimeout(() => {
178
+ if (!this.pending.delete(id)) return
179
+ settle()
180
+ this.cancelAtHelper(id)
181
+ reject(new A11yError('timeout', `the native helper did not answer ${request.op}`))
182
+ }, limitMs + BACKSTOP_MS)
183
+ timer.unref?.()
184
+ signal?.addEventListener('abort', onAbort, { once: true })
185
+ this.pending.set(id, {
186
+ op: request.op,
187
+ resolve: resolve as (body: unknown) => void,
188
+ reject,
189
+ timer,
190
+ cleanup: settle,
191
+ })
192
+ try {
193
+ channel.write(encodeRequest(id, request))
194
+ } catch {
195
+ this.pending.delete(id)
196
+ clearTimeout(timer)
197
+ settle()
198
+ reject(new A11yError('helper_exited', 'the native helper ended'))
199
+ }
200
+ })
201
+ }
202
+
203
+ private sendQuit(channel: NativeChannel): void {
204
+ try {
205
+ channel.write(encodeRequest(this.nextId++, { op: 'quit' }))
206
+ } catch {
207
+ // Already gone.
208
+ }
209
+ channel.kill()
210
+ }
211
+
212
+ /** Tells the helper to stop work nobody waits for any more. Never throws. */
213
+ private cancelAtHelper(target: number): void {
214
+ try {
215
+ this.channel?.write(encodeRequest(this.nextId++, { op: 'cancel', target }))
216
+ } catch {
217
+ // The helper is gone; there is nothing to cancel.
218
+ }
219
+ }
220
+
221
+ private failAll(error: A11yError): void {
222
+ for (const [id, entry] of [...this.pending]) {
223
+ this.pending.delete(id)
224
+ clearTimeout(entry.timer)
225
+ entry.cleanup()
226
+ entry.reject(error)
227
+ }
228
+ }
229
+
230
+ private onReply(line: string): void {
231
+ let id: number
232
+ try {
233
+ const parsed = JSON.parse(line) as { id?: unknown }
234
+ if (typeof parsed.id !== 'number') return
235
+ id = parsed.id
236
+ } catch {
237
+ return
238
+ }
239
+ const entry = this.pending.get(id)
240
+ // An answer to a request nobody awaits (a cancel, a quit, one that timed out).
241
+ if (!entry) return
242
+ this.pending.delete(id)
243
+ clearTimeout(entry.timer)
244
+ entry.cleanup()
245
+ try {
246
+ const reply = decodeReply(entry.op, line)
247
+ if (reply.ok) entry.resolve(reply.body)
248
+ else entry.reject(new A11yError(reply.code, reply.message))
249
+ } catch (error) {
250
+ entry.reject(
251
+ new A11yError(
252
+ 'bad_reply',
253
+ error instanceof NativeProtocolError
254
+ ? error.message
255
+ : 'the native helper sent a bad line',
256
+ ),
257
+ )
258
+ }
259
+ }
260
+
261
+ private start(): Promise<boolean> {
262
+ this.starting ??= new Promise<boolean>((resolve) => {
263
+ let channel: NativeChannel
264
+ try {
265
+ channel = (this.options.spawnHelper ?? (() => spawnHelperProcess(this.options)))()
266
+ } catch {
267
+ this.dead = true
268
+ resolve(false)
269
+ return
270
+ }
271
+ this.channel = channel
272
+ this.runs += 1
273
+ let greeted = false
274
+ let greetedAt = 0
275
+ let triedLegacy = false
276
+ const hello = (protocol: string): void =>
277
+ channel.write(
278
+ encodeRequest(this.nextId++, {
279
+ op: 'hello',
280
+ protocol,
281
+ cliVersion: this.options.cliVersion ?? '0.0.0',
282
+ }),
283
+ )
284
+ const fail = (): void => {
285
+ this.dead = true
286
+ this.up = false
287
+ resolve(false)
288
+ channel.kill()
289
+ }
290
+ const timer = setTimeout(fail, this.options.startTimeoutMs ?? 10_000)
291
+ timer.unref?.()
292
+ channel.onExit(() => {
293
+ clearTimeout(timer)
294
+ // Closed, or already replaced: nothing left to do for this one.
295
+ if (this.channel !== channel) {
296
+ resolve(false)
297
+ return
298
+ }
299
+ this.up = false
300
+ this.failAll(new A11yError('helper_exited', 'the native helper ended'))
301
+ // A helper that was running and ended is started again by the next question,
302
+ // a few times; one that never came up stays off.
303
+ // A long, healthy run does not count against the few restarts a session gets.
304
+ if (greeted && Date.now() - greetedAt >= (this.options.stableAfterMs ?? 60_000))
305
+ this.restarts = 0
306
+ if (greeted && !this.closed && this.restarts < (this.options.maxRestarts ?? 3)) {
307
+ this.restarts++
308
+ this.channel = undefined
309
+ this.starting = undefined
310
+ } else this.dead = true
311
+ resolve(false)
312
+ })
313
+ channel.onLine((line) => {
314
+ if (greeted) {
315
+ this.onReply(line)
316
+ return
317
+ }
318
+ try {
319
+ const reply = decodeReply('hello', line)
320
+ // A helper built before the rename knows only the old protocol name.
321
+ if (!reply.ok && reply.code === 'protocol_mismatch' && !triedLegacy) {
322
+ triedLegacy = true
323
+ hello(LEGACY_NATIVE_PROTOCOL)
324
+ return
325
+ }
326
+ greeted = true
327
+ clearTimeout(timer)
328
+ if (!reply.ok) {
329
+ fail()
330
+ return
331
+ }
332
+ this.greeting = reply.body
333
+ this.up = true
334
+ greetedAt = Date.now()
335
+ resolve(true)
336
+ } catch {
337
+ greeted = true
338
+ clearTimeout(timer)
339
+ fail()
340
+ }
341
+ })
342
+ // The helper ids start at 1 and the greeting is the first of them.
343
+ hello(NATIVE_PROTOCOL)
344
+ })
345
+ return this.starting
346
+ }
347
+ }