@namzu/computer-use 4.4.0 → 4.5.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 (124) hide show
  1. package/CHANGELOG.md +16 -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 +13 -2
  27. package/dist/a11y/windows.d.ts.map +1 -1
  28. package/dist/a11y/windows.js +29 -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 +34 -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 +23 -11
  66. package/dist/foreground/windows.js.map +1 -1
  67. package/dist/native/a11y.d.ts +61 -0
  68. package/dist/native/a11y.d.ts.map +1 -0
  69. package/dist/native/a11y.js +197 -0
  70. package/dist/native/a11y.js.map +1 -0
  71. package/dist/native/foreground-monitor.d.ts +51 -0
  72. package/dist/native/foreground-monitor.d.ts.map +1 -0
  73. package/dist/native/foreground-monitor.js +120 -0
  74. package/dist/native/foreground-monitor.js.map +1 -0
  75. package/dist/native/presence.d.ts +24 -0
  76. package/dist/native/presence.d.ts.map +1 -0
  77. package/dist/native/presence.js +47 -0
  78. package/dist/native/presence.js.map +1 -0
  79. package/dist/native/process.d.ts +73 -0
  80. package/dist/native/process.d.ts.map +1 -0
  81. package/dist/native/process.js +292 -0
  82. package/dist/native/process.js.map +1 -0
  83. package/dist/native/protocol.d.ts +408 -0
  84. package/dist/native/protocol.d.ts.map +1 -0
  85. package/dist/native/protocol.js +527 -0
  86. package/dist/native/protocol.js.map +1 -0
  87. package/dist/native/shared.d.ts +16 -0
  88. package/dist/native/shared.d.ts.map +1 -0
  89. package/dist/native/shared.js +62 -0
  90. package/dist/native/shared.js.map +1 -0
  91. package/dist/presence/presence.d.ts +3 -2
  92. package/dist/presence/presence.d.ts.map +1 -1
  93. package/dist/presence/presence.js.map +1 -1
  94. package/dist/presence/windows.d.ts +2 -0
  95. package/dist/presence/windows.d.ts.map +1 -1
  96. package/dist/presence/windows.js +14 -0
  97. package/dist/presence/windows.js.map +1 -1
  98. package/helper-macos/main.swift +1756 -0
  99. package/package.json +3 -2
  100. package/src/SubprocessComputerUseHost.ts +26 -2
  101. package/src/a11y/a11y.ts +25 -11
  102. package/src/a11y/index.ts +28 -1
  103. package/src/a11y/macos-helper.ts +538 -0
  104. package/src/a11y/macos-signing.ts +280 -0
  105. package/src/a11y/macos.ts +496 -0
  106. package/src/a11y/windows.ts +29 -4
  107. package/src/adapters/cua-driver/adapter.ts +55 -15
  108. package/src/adapters/cua-driver/ui-tree.ts +2 -0
  109. package/src/adapters/darwin-ax.ts +920 -0
  110. package/src/adapters/darwin.ts +184 -4
  111. package/src/adapters/png.ts +5 -0
  112. package/src/adapters/win32-native.ts +328 -0
  113. package/src/adapters/win32.ts +52 -5
  114. package/src/foreground/ladder.ts +5 -1
  115. package/src/foreground/types.ts +6 -0
  116. package/src/foreground/windows.ts +24 -11
  117. package/src/native/a11y.ts +267 -0
  118. package/src/native/foreground-monitor.ts +165 -0
  119. package/src/native/presence.ts +58 -0
  120. package/src/native/process.ts +335 -0
  121. package/src/native/protocol.ts +963 -0
  122. package/src/native/shared.ts +75 -0
  123. package/src/presence/presence.ts +3 -2
  124. package/src/presence/windows.ts +14 -0
@@ -0,0 +1,963 @@
1
+ /**
2
+ * The `namzu-win/1` line codec: how this package talks to the native Windows
3
+ * helper (`crates/namzu-win`), one JSON object per line over stdio.
4
+ *
5
+ * Only the codec lives here: a request is written with {@link encodeRequest},
6
+ * a reply is read with {@link decodeReply}, which refuses a line that is not
7
+ * the shape the op promises. The Rust side (`crates/namzu-win-core`) reads and
8
+ * writes the same lines; `conformance/namzu-win/` is the list both are held to.
9
+ */
10
+
11
+ import type {
12
+ A11yAction,
13
+ A11yChangeKind,
14
+ A11yDisplay,
15
+ A11yFingerprint,
16
+ A11yNode,
17
+ A11yRect,
18
+ A11yWindow,
19
+ } from '../a11y/interface.js'
20
+
21
+ export const NATIVE_PROTOCOL = 'namzu-win/1'
22
+
23
+ /** The largest id or revision either side writes: a JavaScript number holds it exactly. */
24
+ export const MAX_SAFE_ID = Number.MAX_SAFE_INTEGER
25
+
26
+ export type NativeOp =
27
+ | 'hello'
28
+ | 'windows'
29
+ | 'displays'
30
+ | 'snapshot'
31
+ | 'identity'
32
+ | 'resolve'
33
+ | 'seq'
34
+ | 'wait_change'
35
+ | 'act'
36
+ | 'input'
37
+ | 'capture'
38
+ | 'foreground.get'
39
+ | 'foreground.set'
40
+ | 'lease.begin'
41
+ | 'lease.end'
42
+ | 'monitor.start'
43
+ | 'monitor.stop'
44
+ | 'monitor.poll'
45
+ | 'presence.act'
46
+ | 'presence.hide'
47
+ | 'cancel'
48
+ | 'quit'
49
+
50
+ // --- requests ---------------------------------------------------------------
51
+
52
+ export type NativeRequest =
53
+ | { readonly op: 'hello'; readonly protocol: string; readonly cliVersion: string }
54
+ | { readonly op: 'windows'; readonly includeOwned?: boolean }
55
+ | { readonly op: 'displays' }
56
+ | {
57
+ readonly op: 'snapshot'
58
+ readonly windowId: string
59
+ readonly maxNodes?: number
60
+ readonly maxDepth?: number
61
+ readonly skeleton?: boolean
62
+ readonly allowChromium?: boolean
63
+ readonly timeoutMs?: number
64
+ }
65
+ | {
66
+ readonly op: 'identity'
67
+ readonly windowId: string
68
+ readonly index: number
69
+ readonly revision?: number
70
+ }
71
+ | { readonly op: 'resolve'; readonly windowId: string; readonly fingerprint: A11yFingerprint }
72
+ | { readonly op: 'seq'; readonly windowId?: string }
73
+ | {
74
+ readonly op: 'wait_change'
75
+ readonly windowId: string
76
+ readonly since?: number
77
+ readonly quietMs?: number
78
+ readonly timeoutMs?: number
79
+ readonly kinds?: readonly A11yChangeKind[]
80
+ }
81
+ | NativeActRequest
82
+ | NativeInputRequest
83
+ | NativeCaptureRequest
84
+ | { readonly op: 'foreground.get'; readonly windowId?: string; readonly processId?: number }
85
+ | { readonly op: 'foreground.set'; readonly windowId: string }
86
+ | NativeLeaseBeginRequest
87
+ | {
88
+ readonly op: 'lease.end'
89
+ readonly restore: boolean
90
+ readonly keepCursor?: boolean
91
+ readonly release?: boolean
92
+ }
93
+ | NativeMonitorStartRequest
94
+ | { readonly op: 'monitor.stop' }
95
+ | { readonly op: 'monitor.poll'; readonly since?: number }
96
+ | NativePresenceActRequest
97
+ | { readonly op: 'presence.hide' }
98
+ | { readonly op: 'cancel'; readonly target: number }
99
+ | { readonly op: 'quit' }
100
+
101
+ /** What `act` does to a control, through the pattern it offers. */
102
+ export type NativeActKind =
103
+ | 'invoke'
104
+ | 'setValue'
105
+ | 'toggle'
106
+ | 'expand'
107
+ | 'collapse'
108
+ | 'select'
109
+ | 'scrollIntoView'
110
+ | 'scroll'
111
+ | 'focus'
112
+
113
+ /** One of `ref` and `fingerprint` names the control. */
114
+ export interface NativeActRequest {
115
+ readonly op: 'act'
116
+ readonly windowId: string
117
+ readonly ref?: string
118
+ readonly fingerprint?: A11yFingerprint
119
+ readonly action: NativeActKind
120
+ /** For `setValue`. */
121
+ readonly text?: string
122
+ /** For `scroll`: steps right and down are positive. */
123
+ readonly dx?: number
124
+ readonly dy?: number
125
+ readonly timeoutMs?: number
126
+ }
127
+
128
+ export type NativeMouseButton = 'left' | 'right' | 'middle'
129
+ export type NativeScrollDirection = 'up' | 'down' | 'left' | 'right'
130
+
131
+ /** Points are virtual-desktop physical pixels. */
132
+ export type NativeInputRequest = { readonly op: 'input' } & (
133
+ | {
134
+ readonly kind: 'click'
135
+ readonly x: number
136
+ readonly y: number
137
+ readonly button?: NativeMouseButton
138
+ readonly count?: 1 | 2 | 3
139
+ }
140
+ | { readonly kind: 'move'; readonly x: number; readonly y: number }
141
+ | {
142
+ readonly kind: 'drag'
143
+ readonly x: number
144
+ readonly y: number
145
+ readonly toX: number
146
+ readonly toY: number
147
+ readonly button?: NativeMouseButton
148
+ }
149
+ | {
150
+ readonly kind: 'scroll'
151
+ readonly x: number
152
+ readonly y: number
153
+ readonly direction: NativeScrollDirection
154
+ readonly amount?: number
155
+ }
156
+ | { readonly kind: 'type'; readonly text: string }
157
+ | { readonly kind: 'key'; readonly keys: string }
158
+ )
159
+
160
+ export type NativeCaptureTarget =
161
+ | { readonly kind: 'window'; readonly windowId: string }
162
+ | { readonly kind: 'display'; readonly id?: string }
163
+ | {
164
+ readonly kind: 'region'
165
+ readonly x: number
166
+ readonly y: number
167
+ readonly width: number
168
+ readonly height: number
169
+ }
170
+
171
+ export interface NativeCaptureRequest {
172
+ readonly op: 'capture'
173
+ readonly target: NativeCaptureTarget
174
+ /** A directory the caller made; the picture is written into it. */
175
+ readonly into?: string
176
+ /** Return a small picture in the reply instead. */
177
+ readonly inline?: boolean
178
+ readonly cursor?: boolean
179
+ readonly timeoutMs?: number
180
+ }
181
+
182
+ export type NativeMonitorHook = 'foreground' | 'input'
183
+
184
+ /** What to watch; default both. */
185
+ export interface NativeMonitorStartRequest {
186
+ readonly op: 'monitor.start'
187
+ readonly hooks?: readonly NativeMonitorHook[]
188
+ }
189
+
190
+ export type NativePresenceKind = 'click' | 'type' | 'move'
191
+
192
+ export interface NativePresenceActRequest {
193
+ readonly op: 'presence.act'
194
+ readonly windowId: string
195
+ readonly kind: NativePresenceKind
196
+ /** Where the action lands, in virtual-desktop pixels; absent for typing. */
197
+ readonly at?: { readonly x: number; readonly y: number }
198
+ }
199
+
200
+ export interface NativeLeaseBeginRequest {
201
+ readonly op: 'lease.begin'
202
+ readonly windowId?: string
203
+ readonly raise?: boolean
204
+ readonly idleMs?: number
205
+ readonly ttlMs?: number
206
+ readonly leasePath?: string
207
+ readonly token?: string
208
+ }
209
+
210
+ /** One request as a line, without the trailing newline. */
211
+ export function encodeRequest(id: number, request: NativeRequest): string {
212
+ assertId(id)
213
+ return JSON.stringify({ id, ...request })
214
+ }
215
+
216
+ // --- replies ----------------------------------------------------------------
217
+
218
+ export interface NativeHello {
219
+ readonly version: string
220
+ readonly buildHash: string
221
+ readonly arch: string
222
+ readonly osBuild: string
223
+ readonly signer?: string
224
+ readonly caps: readonly string[]
225
+ readonly dpiAwareness: string
226
+ }
227
+
228
+ /** A control as the helper lists it: the accessibility node plus the ref `act` takes. */
229
+ export interface NativeNode extends A11yNode {
230
+ readonly ref: string
231
+ }
232
+
233
+ export interface NativeSnapshot {
234
+ readonly windowId: string
235
+ readonly revision: number
236
+ readonly nodes: readonly NativeNode[]
237
+ readonly total: number
238
+ readonly truncated: boolean
239
+ readonly skeleton: boolean
240
+ readonly readMs: number
241
+ }
242
+
243
+ export type NativeResolution =
244
+ | {
245
+ readonly found: true
246
+ readonly index: number
247
+ readonly via: 'runtimeId' | 'automationId' | 'name'
248
+ readonly revision: number
249
+ }
250
+ | {
251
+ readonly found: false
252
+ readonly code: 'not_found' | 'ambiguous'
253
+ readonly candidates?: number
254
+ }
255
+
256
+ export type NativeWaitResult =
257
+ | {
258
+ readonly changed: true
259
+ readonly settled: boolean
260
+ readonly firstEventMs: number
261
+ readonly settledMs: number
262
+ readonly events: number
263
+ readonly newWindows: readonly string[]
264
+ }
265
+ | { readonly changed: false; readonly timedOut: true; readonly settledMs: number }
266
+
267
+ export interface NativeActState {
268
+ readonly value?: string
269
+ readonly toggle?: 'on' | 'off' | 'mixed'
270
+ readonly expand?: 'expanded' | 'collapsed' | 'partial' | 'leaf'
271
+ readonly selected?: boolean
272
+ readonly focused?: boolean
273
+ }
274
+
275
+ export interface NativeActReply {
276
+ /** The pattern call went through. */
277
+ readonly done: boolean
278
+ readonly via: 'pattern'
279
+ /** Whether the read-back shows the effect; absent when there is nothing to read. */
280
+ readonly verified?: boolean
281
+ readonly after?: NativeActState
282
+ /** The control's place in the read that found it, and that read's revision. */
283
+ readonly index: number
284
+ readonly revision: number
285
+ }
286
+
287
+ export interface NativeInputReply {
288
+ readonly delivered: number
289
+ readonly via: 'sendinput'
290
+ readonly cursor?: { readonly x: number; readonly y: number }
291
+ }
292
+
293
+ export interface NativeCaptureReply {
294
+ readonly path?: string
295
+ readonly dataBase64?: string
296
+ readonly bytes: number
297
+ readonly width: number
298
+ readonly height: number
299
+ readonly scale: number
300
+ readonly via: 'wgc' | 'printwindow' | 'bitblt'
301
+ readonly sha256: string
302
+ readonly bounds: A11yRect
303
+ readonly display?: string
304
+ }
305
+
306
+ export interface NativeForegroundWindow {
307
+ readonly windowId: string
308
+ readonly processId: number
309
+ readonly exe: string
310
+ readonly elevated: boolean
311
+ /** The integrity level as a RID (0x2000 medium, 0x3000 high); -1 when unreadable. */
312
+ readonly integrity: number
313
+ }
314
+
315
+ export interface NativeForegroundState {
316
+ readonly foreground: NativeForegroundWindow | null
317
+ readonly cursor: { readonly x: number; readonly y: number }
318
+ readonly desktop: string
319
+ readonly selfElevated: boolean
320
+ readonly selfIntegrity: number
321
+ readonly inputTick: number
322
+ readonly userIdleMs: number
323
+ readonly target?: {
324
+ readonly exe: string
325
+ readonly elevated: boolean
326
+ readonly integrity: number
327
+ }
328
+ }
329
+
330
+ export type NativeRaiseHow = 'already' | 'plain' | 'unlock' | 'attach' | 'switch' | 'refused'
331
+
332
+ export interface NativeForegroundSetReply {
333
+ readonly raised: boolean
334
+ readonly changed: boolean
335
+ readonly how: NativeRaiseHow
336
+ readonly blockedBy?: 'windows' | 'elevated'
337
+ }
338
+
339
+ export interface NativeLeaseBeginReply extends NativeForegroundState {
340
+ readonly refused: boolean
341
+ readonly raised?: boolean
342
+ readonly raiseHow?: NativeRaiseHow
343
+ }
344
+
345
+ export interface NativeLeaseEndReply {
346
+ readonly restoredForeground: boolean
347
+ readonly restoredCursor: boolean
348
+ readonly restoreNote?: string
349
+ readonly inputMoved: boolean
350
+ readonly frontElevated: boolean
351
+ readonly released: boolean
352
+ /** A person's input events between begin and end; absent when the monitor was not running throughout. */
353
+ readonly inputsDuring?: number
354
+ }
355
+
356
+ export interface NativeMonitorStartReply {
357
+ /** Raw Input is registered: a person's use of keyboard and mouse is seen. */
358
+ readonly input: boolean
359
+ /** Foreground changes are hooked. */
360
+ readonly foreground: boolean
361
+ }
362
+
363
+ /**
364
+ * One thing that happened. Input carries the device class and a time only,
365
+ * never a key, a character or a position.
366
+ */
367
+ export interface NativeMonitorEvent {
368
+ readonly seq: number
369
+ readonly kind: 'input' | 'foreground'
370
+ /** ms since the monitor started. */
371
+ readonly tMs: number
372
+ readonly device?: 'keyboard' | 'mouse'
373
+ /** The system synthesised the input (SendInput, from this helper or another program). */
374
+ readonly injected?: boolean
375
+ /** For a foreground change: the window that came to the front. */
376
+ readonly windowId?: string
377
+ }
378
+
379
+ export interface NativeMonitorPollReply {
380
+ readonly events: readonly NativeMonitorEvent[]
381
+ readonly seq: number
382
+ /** Events a person's devices produced since the monitor started. */
383
+ readonly inputs: number
384
+ readonly injectedInputs: number
385
+ readonly foregroundChanges: number
386
+ /** ms since a person's last input, when there was one. */
387
+ readonly lastInputAgoMs?: number
388
+ /** `since` was older than the oldest event kept. */
389
+ readonly dropped: boolean
390
+ }
391
+
392
+ export interface NativePresenceActReply {
393
+ readonly cursorWindow: number
394
+ readonly frameWindow: number
395
+ }
396
+
397
+ export interface NativeReplyBodies {
398
+ readonly hello: NativeHello
399
+ readonly windows: { readonly windows: readonly A11yWindow[] }
400
+ readonly displays: { readonly displays: readonly A11yDisplay[] }
401
+ readonly snapshot: NativeSnapshot
402
+ readonly identity: { readonly fingerprint: A11yFingerprint }
403
+ readonly resolve: NativeResolution
404
+ readonly seq: { readonly seq: number }
405
+ readonly wait_change: NativeWaitResult
406
+ readonly act: NativeActReply
407
+ readonly input: NativeInputReply
408
+ readonly capture: NativeCaptureReply
409
+ readonly 'foreground.get': NativeForegroundState
410
+ readonly 'foreground.set': NativeForegroundSetReply
411
+ readonly 'lease.begin': NativeLeaseBeginReply
412
+ readonly 'lease.end': NativeLeaseEndReply
413
+ readonly 'monitor.start': NativeMonitorStartReply
414
+ readonly 'monitor.stop': Record<string, never>
415
+ readonly 'monitor.poll': NativeMonitorPollReply
416
+ readonly 'presence.act': NativePresenceActReply
417
+ readonly 'presence.hide': Record<string, never>
418
+ readonly cancel: Record<string, never>
419
+ readonly quit: Record<string, never>
420
+ }
421
+
422
+ export type NativeReply<K extends NativeOp> =
423
+ | { readonly id: number; readonly ok: true; readonly body: NativeReplyBodies[K] }
424
+ | { readonly id: number; readonly ok: false; readonly code: string; readonly message: string }
425
+
426
+ /** A line the helper should not have sent: not JSON, or not the shape the op promises. */
427
+ export class NativeProtocolError extends Error {
428
+ constructor(message: string) {
429
+ super(message)
430
+ this.name = 'NativeProtocolError'
431
+ }
432
+ }
433
+
434
+ type Obj = Record<string, unknown>
435
+
436
+ function bad(path: string, want: string): never {
437
+ throw new NativeProtocolError(`${path} must be ${want}`)
438
+ }
439
+
440
+ function assertId(id: number): void {
441
+ if (!Number.isSafeInteger(id) || id < 0) {
442
+ throw new NativeProtocolError(
443
+ 'id must be a non-negative integer a JavaScript number holds exactly',
444
+ )
445
+ }
446
+ }
447
+
448
+ function obj(v: unknown, path: string): Obj {
449
+ if (typeof v !== 'object' || v === null || Array.isArray(v)) bad(path, 'an object')
450
+ return v as Obj
451
+ }
452
+
453
+ function str(o: Obj, key: string, path: string): string {
454
+ const v = o[key]
455
+ if (typeof v !== 'string') bad(`${path}.${key}`, 'a string')
456
+ return v
457
+ }
458
+
459
+ function optStr(o: Obj, key: string, path: string): string | undefined {
460
+ return o[key] === undefined ? undefined : str(o, key, path)
461
+ }
462
+
463
+ function int(o: Obj, key: string, path: string, min = 0): number {
464
+ const v = o[key]
465
+ if (typeof v !== 'number' || !Number.isSafeInteger(v) || v < min) {
466
+ bad(`${path}.${key}`, `an integer of at least ${min}`)
467
+ }
468
+ return v
469
+ }
470
+
471
+ function optInt(o: Obj, key: string, path: string): number | undefined {
472
+ return o[key] === undefined ? undefined : int(o, key, path)
473
+ }
474
+
475
+ function num(o: Obj, key: string, path: string): number {
476
+ const v = o[key]
477
+ if (typeof v !== 'number' || !Number.isFinite(v)) bad(`${path}.${key}`, 'a number')
478
+ return v
479
+ }
480
+
481
+ function bool(o: Obj, key: string, path: string): boolean {
482
+ const v = o[key]
483
+ if (typeof v !== 'boolean') bad(`${path}.${key}`, 'a boolean')
484
+ return v
485
+ }
486
+
487
+ function optBool(o: Obj, key: string, path: string): boolean | undefined {
488
+ return o[key] === undefined ? undefined : bool(o, key, path)
489
+ }
490
+
491
+ function arr(o: Obj, key: string, path: string): readonly unknown[] {
492
+ const v = o[key]
493
+ if (!Array.isArray(v)) bad(`${path}.${key}`, 'a list')
494
+ return v
495
+ }
496
+
497
+ function oneOf<T extends string>(v: unknown, allowed: readonly T[], path: string): T {
498
+ if (typeof v !== 'string' || !(allowed as readonly string[]).includes(v)) {
499
+ bad(path, `one of ${allowed.join(', ')}`)
500
+ }
501
+ return v as T
502
+ }
503
+
504
+ function rect(o: Obj, key: string, path: string): A11yRect {
505
+ const r = obj(o[key], `${path}.${key}`)
506
+ const p = `${path}.${key}`
507
+ return {
508
+ x: int(r, 'x', p, Number.MIN_SAFE_INTEGER),
509
+ y: int(r, 'y', p, Number.MIN_SAFE_INTEGER),
510
+ width: int(r, 'width', p, Number.MIN_SAFE_INTEGER),
511
+ height: int(r, 'height', p, Number.MIN_SAFE_INTEGER),
512
+ }
513
+ }
514
+
515
+ const ACTIONS: readonly A11yAction[] = [
516
+ 'invoke',
517
+ 'value',
518
+ 'toggle',
519
+ 'expandCollapse',
520
+ 'selectionItem',
521
+ 'scroll',
522
+ ]
523
+
524
+ function node(v: unknown, path: string): NativeNode {
525
+ const o = obj(v, path)
526
+ const out: { -readonly [K in keyof NativeNode]: NativeNode[K] } = {
527
+ index: int(o, 'index', path),
528
+ ref: str(o, 'ref', path),
529
+ parent: int(o, 'parent', path, -1),
530
+ depth: int(o, 'depth', path),
531
+ role: str(o, 'role', path),
532
+ bounds: rect(o, 'bounds', path),
533
+ enabled: bool(o, 'enabled', path),
534
+ offscreen: bool(o, 'offscreen', path),
535
+ focused: bool(o, 'focused', path),
536
+ actions: arr(o, 'actions', path).map((a, i) => oneOf(a, ACTIONS, `${path}.actions[${i}]`)),
537
+ }
538
+ const name = optStr(o, 'name', path)
539
+ if (name !== undefined) out.name = name
540
+ const automationId = optStr(o, 'automationId', path)
541
+ if (automationId !== undefined) out.automationId = automationId
542
+ const className = optStr(o, 'className', path)
543
+ if (className !== undefined) out.className = className
544
+ const value = optStr(o, 'value', path)
545
+ if (value !== undefined) out.value = value
546
+ if (o.toggle !== undefined)
547
+ out.toggle = oneOf<'on' | 'off' | 'mixed'>(o.toggle, ['on', 'off', 'mixed'], `${path}.toggle`)
548
+ if (o.expand !== undefined) {
549
+ out.expand = oneOf<'expanded' | 'collapsed' | 'partial' | 'leaf'>(
550
+ o.expand,
551
+ ['expanded', 'collapsed', 'partial', 'leaf'],
552
+ `${path}.expand`,
553
+ )
554
+ }
555
+ const selected = optBool(o, 'selected', path)
556
+ if (selected !== undefined) out.selected = selected
557
+ const childCount = optInt(o, 'childCount', path)
558
+ if (childCount !== undefined) out.childCount = childCount
559
+ return out
560
+ }
561
+
562
+ function window(v: unknown, path: string): A11yWindow {
563
+ const o = obj(v, path)
564
+ return {
565
+ windowId: str(o, 'windowId', path),
566
+ processId: int(o, 'processId', path),
567
+ processName: str(o, 'processName', path),
568
+ title: str(o, 'title', path),
569
+ bounds: rect(o, 'bounds', path),
570
+ minimized: bool(o, 'minimized', path),
571
+ focused: bool(o, 'focused', path),
572
+ z: int(o, 'z', path),
573
+ }
574
+ }
575
+
576
+ function display(v: unknown, path: string): A11yDisplay {
577
+ const o = obj(v, path)
578
+ return {
579
+ id: str(o, 'id', path),
580
+ bounds: rect(o, 'bounds', path),
581
+ workArea: rect(o, 'workArea', path),
582
+ scale: num(o, 'scale', path),
583
+ primary: bool(o, 'primary', path),
584
+ }
585
+ }
586
+
587
+ function hello(o: Obj): NativeHello {
588
+ const out: { -readonly [K in keyof NativeHello]: NativeHello[K] } = {
589
+ version: str(o, 'version', 'hello'),
590
+ buildHash: str(o, 'buildHash', 'hello'),
591
+ arch: str(o, 'arch', 'hello'),
592
+ osBuild: str(o, 'osBuild', 'hello'),
593
+ caps: arr(o, 'caps', 'hello').map((c, i) => {
594
+ if (typeof c !== 'string') bad(`hello.caps[${i}]`, 'a string')
595
+ return c
596
+ }),
597
+ dpiAwareness: str(o, 'dpiAwareness', 'hello'),
598
+ }
599
+ const signer = optStr(o, 'signer', 'hello')
600
+ if (signer !== undefined) out.signer = signer
601
+ return out
602
+ }
603
+
604
+ function snapshot(o: Obj): NativeSnapshot {
605
+ return {
606
+ windowId: str(o, 'windowId', 'snapshot'),
607
+ revision: int(o, 'revision', 'snapshot'),
608
+ nodes: arr(o, 'nodes', 'snapshot').map((n, i) => node(n, `snapshot.nodes[${i}]`)),
609
+ total: int(o, 'total', 'snapshot'),
610
+ truncated: bool(o, 'truncated', 'snapshot'),
611
+ skeleton: bool(o, 'skeleton', 'snapshot'),
612
+ readMs: num(o, 'readMs', 'snapshot'),
613
+ }
614
+ }
615
+
616
+ function fingerprint(v: unknown, path: string): A11yFingerprint {
617
+ const o = obj(v, path)
618
+ return {
619
+ runtimeId: str(o, 'runtimeId', path),
620
+ automationId: str(o, 'automationId', path),
621
+ role: str(o, 'role', path),
622
+ nameHash: str(o, 'nameHash', path),
623
+ parentPath: str(o, 'parentPath', path),
624
+ ordinal: int(o, 'ordinal', path),
625
+ processStart: int(o, 'processStart', path),
626
+ }
627
+ }
628
+
629
+ function resolution(o: Obj): NativeResolution {
630
+ if (bool(o, 'found', 'resolve')) {
631
+ return {
632
+ found: true,
633
+ index: int(o, 'index', 'resolve'),
634
+ via: oneOf(o.via, ['runtimeId', 'automationId', 'name'], 'resolve.via'),
635
+ revision: int(o, 'revision', 'resolve'),
636
+ }
637
+ }
638
+ const code = oneOf(o.code, ['not_found', 'ambiguous'], 'resolve.code')
639
+ const candidates = optInt(o, 'candidates', 'resolve')
640
+ return candidates === undefined ? { found: false, code } : { found: false, code, candidates }
641
+ }
642
+
643
+ function waitResult(o: Obj): NativeWaitResult {
644
+ if (bool(o, 'changed', 'wait_change')) {
645
+ return {
646
+ changed: true,
647
+ settled: bool(o, 'settled', 'wait_change'),
648
+ firstEventMs: int(o, 'firstEventMs', 'wait_change', Number.MIN_SAFE_INTEGER),
649
+ settledMs: int(o, 'settledMs', 'wait_change'),
650
+ events: int(o, 'events', 'wait_change'),
651
+ newWindows: arr(o, 'newWindows', 'wait_change').map((w, i) => {
652
+ if (typeof w !== 'string') bad(`wait_change.newWindows[${i}]`, 'a string')
653
+ return w
654
+ }),
655
+ }
656
+ }
657
+ if (o.timedOut !== true) bad('wait_change.timedOut', 'true when nothing changed')
658
+ return { changed: false, timedOut: true, settledMs: int(o, 'settledMs', 'wait_change') }
659
+ }
660
+
661
+ function point(v: unknown, path: string): { x: number; y: number } {
662
+ const o = obj(v, path)
663
+ return {
664
+ x: int(o, 'x', path, Number.MIN_SAFE_INTEGER),
665
+ y: int(o, 'y', path, Number.MIN_SAFE_INTEGER),
666
+ }
667
+ }
668
+
669
+ const RAISE_HOW: readonly NativeRaiseHow[] = [
670
+ 'already',
671
+ 'plain',
672
+ 'unlock',
673
+ 'attach',
674
+ 'switch',
675
+ 'refused',
676
+ ]
677
+
678
+ function actState(v: unknown, path: string): NativeActState {
679
+ const o = obj(v, path)
680
+ const out: { -readonly [K in keyof NativeActState]: NativeActState[K] } = {}
681
+ const value = optStr(o, 'value', path)
682
+ if (value !== undefined) out.value = value
683
+ if (o.toggle !== undefined)
684
+ out.toggle = oneOf<'on' | 'off' | 'mixed'>(o.toggle, ['on', 'off', 'mixed'], `${path}.toggle`)
685
+ if (o.expand !== undefined) {
686
+ out.expand = oneOf<'expanded' | 'collapsed' | 'partial' | 'leaf'>(
687
+ o.expand,
688
+ ['expanded', 'collapsed', 'partial', 'leaf'],
689
+ `${path}.expand`,
690
+ )
691
+ }
692
+ const selected = optBool(o, 'selected', path)
693
+ if (selected !== undefined) out.selected = selected
694
+ const focused = optBool(o, 'focused', path)
695
+ if (focused !== undefined) out.focused = focused
696
+ return out
697
+ }
698
+
699
+ function actReply(o: Obj): NativeActReply {
700
+ const out: { -readonly [K in keyof NativeActReply]: NativeActReply[K] } = {
701
+ done: bool(o, 'done', 'act'),
702
+ via: oneOf<'pattern'>(o.via, ['pattern'], 'act.via'),
703
+ index: int(o, 'index', 'act'),
704
+ revision: int(o, 'revision', 'act'),
705
+ }
706
+ const verified = optBool(o, 'verified', 'act')
707
+ if (verified !== undefined) out.verified = verified
708
+ if (o.after !== undefined) out.after = actState(o.after, 'act.after')
709
+ return out
710
+ }
711
+
712
+ function inputReply(o: Obj): NativeInputReply {
713
+ const out: { -readonly [K in keyof NativeInputReply]: NativeInputReply[K] } = {
714
+ delivered: int(o, 'delivered', 'input'),
715
+ via: oneOf<'sendinput'>(o.via, ['sendinput'], 'input.via'),
716
+ }
717
+ if (o.cursor !== undefined) out.cursor = point(o.cursor, 'input.cursor')
718
+ return out
719
+ }
720
+
721
+ function captureReply(o: Obj): NativeCaptureReply {
722
+ const out: { -readonly [K in keyof NativeCaptureReply]: NativeCaptureReply[K] } = {
723
+ bytes: int(o, 'bytes', 'capture'),
724
+ width: int(o, 'width', 'capture'),
725
+ height: int(o, 'height', 'capture'),
726
+ scale: num(o, 'scale', 'capture'),
727
+ via: oneOf<'wgc' | 'printwindow' | 'bitblt'>(
728
+ o.via,
729
+ ['wgc', 'printwindow', 'bitblt'],
730
+ 'capture.via',
731
+ ),
732
+ sha256: str(o, 'sha256', 'capture'),
733
+ bounds: rect(o, 'bounds', 'capture'),
734
+ }
735
+ const path = optStr(o, 'path', 'capture')
736
+ if (path !== undefined) out.path = path
737
+ const data = optStr(o, 'dataBase64', 'capture')
738
+ if (data !== undefined) out.dataBase64 = data
739
+ const display = optStr(o, 'display', 'capture')
740
+ if (display !== undefined) out.display = display
741
+ return out
742
+ }
743
+
744
+ function foregroundState(o: Obj, path: string): NativeForegroundState {
745
+ let foreground: NativeForegroundWindow | null = null
746
+ if (o.foreground === undefined) bad(`${path}.foreground`, 'a window or null')
747
+ if (o.foreground !== null) {
748
+ const f = obj(o.foreground, `${path}.foreground`)
749
+ const p = `${path}.foreground`
750
+ foreground = {
751
+ windowId: str(f, 'windowId', p),
752
+ processId: int(f, 'processId', p),
753
+ exe: str(f, 'exe', p),
754
+ elevated: bool(f, 'elevated', p),
755
+ integrity: int(f, 'integrity', p, -1),
756
+ }
757
+ }
758
+ const out: { -readonly [K in keyof NativeForegroundState]: NativeForegroundState[K] } = {
759
+ foreground,
760
+ cursor: point(o.cursor, `${path}.cursor`),
761
+ desktop: str(o, 'desktop', path),
762
+ selfElevated: bool(o, 'selfElevated', path),
763
+ selfIntegrity: int(o, 'selfIntegrity', path, -1),
764
+ inputTick: int(o, 'inputTick', path),
765
+ userIdleMs: int(o, 'userIdleMs', path),
766
+ }
767
+ if (o.target !== undefined) {
768
+ const t = obj(o.target, `${path}.target`)
769
+ out.target = {
770
+ exe: str(t, 'exe', `${path}.target`),
771
+ elevated: bool(t, 'elevated', `${path}.target`),
772
+ integrity: int(t, 'integrity', `${path}.target`, -1),
773
+ }
774
+ }
775
+ return out
776
+ }
777
+
778
+ function foregroundSet(o: Obj): NativeForegroundSetReply {
779
+ const out: { -readonly [K in keyof NativeForegroundSetReply]: NativeForegroundSetReply[K] } = {
780
+ raised: bool(o, 'raised', 'foreground.set'),
781
+ changed: bool(o, 'changed', 'foreground.set'),
782
+ how: oneOf(o.how, RAISE_HOW, 'foreground.set.how'),
783
+ }
784
+ if (o.blockedBy !== undefined)
785
+ out.blockedBy = oneOf<'windows' | 'elevated'>(
786
+ o.blockedBy,
787
+ ['windows', 'elevated'],
788
+ 'foreground.set.blockedBy',
789
+ )
790
+ return out
791
+ }
792
+
793
+ function leaseBegin(o: Obj): NativeLeaseBeginReply {
794
+ const out: { -readonly [K in keyof NativeLeaseBeginReply]: NativeLeaseBeginReply[K] } = {
795
+ ...foregroundState(o, 'lease.begin'),
796
+ refused: bool(o, 'refused', 'lease.begin'),
797
+ }
798
+ const raised = optBool(o, 'raised', 'lease.begin')
799
+ if (raised !== undefined) out.raised = raised
800
+ if (o.raiseHow !== undefined) out.raiseHow = oneOf(o.raiseHow, RAISE_HOW, 'lease.begin.raiseHow')
801
+ return out
802
+ }
803
+
804
+ function leaseEnd(o: Obj): NativeLeaseEndReply {
805
+ const out: { -readonly [K in keyof NativeLeaseEndReply]: NativeLeaseEndReply[K] } = {
806
+ restoredForeground: bool(o, 'restoredForeground', 'lease.end'),
807
+ restoredCursor: bool(o, 'restoredCursor', 'lease.end'),
808
+ inputMoved: bool(o, 'inputMoved', 'lease.end'),
809
+ frontElevated: bool(o, 'frontElevated', 'lease.end'),
810
+ released: bool(o, 'released', 'lease.end'),
811
+ }
812
+ const note = optStr(o, 'restoreNote', 'lease.end')
813
+ if (note !== undefined) out.restoreNote = note
814
+ const during = optInt(o, 'inputsDuring', 'lease.end')
815
+ if (during !== undefined) out.inputsDuring = during
816
+ return out
817
+ }
818
+
819
+ function monitorEvent(v: unknown, path: string): NativeMonitorEvent {
820
+ const o = obj(v, path)
821
+ const out: { -readonly [K in keyof NativeMonitorEvent]: NativeMonitorEvent[K] } = {
822
+ seq: int(o, 'seq', path),
823
+ kind: oneOf<'input' | 'foreground'>(o.kind, ['input', 'foreground'], `${path}.kind`),
824
+ tMs: int(o, 'tMs', path),
825
+ }
826
+ if (o.device !== undefined)
827
+ out.device = oneOf<'keyboard' | 'mouse'>(o.device, ['keyboard', 'mouse'], `${path}.device`)
828
+ const injected = optBool(o, 'injected', path)
829
+ if (injected !== undefined) out.injected = injected
830
+ const windowId = optStr(o, 'windowId', path)
831
+ if (windowId !== undefined) out.windowId = windowId
832
+ return out
833
+ }
834
+
835
+ function monitorPoll(o: Obj): NativeMonitorPollReply {
836
+ const out: { -readonly [K in keyof NativeMonitorPollReply]: NativeMonitorPollReply[K] } = {
837
+ events: arr(o, 'events', 'monitor.poll').map((e, i) =>
838
+ monitorEvent(e, `monitor.poll.events[${i}]`),
839
+ ),
840
+ seq: int(o, 'seq', 'monitor.poll'),
841
+ inputs: int(o, 'inputs', 'monitor.poll'),
842
+ injectedInputs: int(o, 'injectedInputs', 'monitor.poll'),
843
+ foregroundChanges: int(o, 'foregroundChanges', 'monitor.poll'),
844
+ dropped: bool(o, 'dropped', 'monitor.poll'),
845
+ }
846
+ const ago = optInt(o, 'lastInputAgoMs', 'monitor.poll')
847
+ if (ago !== undefined) out.lastInputAgoMs = ago
848
+ return out
849
+ }
850
+
851
+ function body(op: NativeOp, o: Obj): NativeReplyBodies[NativeOp] {
852
+ switch (op) {
853
+ case 'hello':
854
+ return hello(o)
855
+ case 'windows':
856
+ return { windows: arr(o, 'windows', 'windows').map((w, i) => window(w, `windows[${i}]`)) }
857
+ case 'displays':
858
+ return {
859
+ displays: arr(o, 'displays', 'displays').map((d, i) => display(d, `displays[${i}]`)),
860
+ }
861
+ case 'snapshot':
862
+ return snapshot(o)
863
+ case 'identity':
864
+ return { fingerprint: fingerprint(o.fingerprint, 'identity.fingerprint') }
865
+ case 'resolve':
866
+ return resolution(o)
867
+ case 'seq':
868
+ return { seq: int(o, 'seq', 'seq') }
869
+ case 'wait_change':
870
+ return waitResult(o)
871
+ case 'act':
872
+ return actReply(o)
873
+ case 'input':
874
+ return inputReply(o)
875
+ case 'capture':
876
+ return captureReply(o)
877
+ case 'foreground.get':
878
+ return foregroundState(o, 'foreground.get')
879
+ case 'foreground.set':
880
+ return foregroundSet(o)
881
+ case 'lease.begin':
882
+ return leaseBegin(o)
883
+ case 'lease.end':
884
+ return leaseEnd(o)
885
+ case 'monitor.start':
886
+ return {
887
+ input: bool(o, 'input', 'monitor.start'),
888
+ foreground: bool(o, 'foreground', 'monitor.start'),
889
+ }
890
+ case 'monitor.poll':
891
+ return monitorPoll(o)
892
+ case 'presence.act':
893
+ return {
894
+ cursorWindow: int(o, 'cursorWindow', 'presence.act'),
895
+ frameWindow: int(o, 'frameWindow', 'presence.act'),
896
+ }
897
+ case 'monitor.stop':
898
+ case 'presence.hide':
899
+ case 'cancel':
900
+ case 'quit':
901
+ return {}
902
+ }
903
+ }
904
+
905
+ /**
906
+ * Reads the reply to a request of kind `op`. Throws {@link NativeProtocolError}
907
+ * for a line that is not a reply; a reply that says the request failed is a
908
+ * value (`ok: false`), not a throw.
909
+ */
910
+ export function decodeReply<K extends NativeOp>(op: K, line: string): NativeReply<K> {
911
+ let parsed: unknown
912
+ try {
913
+ parsed = JSON.parse(line)
914
+ } catch {
915
+ throw new NativeProtocolError('a reply is one JSON object per line')
916
+ }
917
+ const o = obj(parsed, 'reply')
918
+ const id = int(o, 'id', 'reply')
919
+ if (typeof o.ok !== 'boolean') bad('reply.ok', 'a boolean')
920
+ if (!o.ok) {
921
+ return { id, ok: false, code: str(o, 'code', 'reply'), message: str(o, 'message', 'reply') }
922
+ }
923
+ return { id, ok: true, body: body(op, o) as NativeReplyBodies[K] }
924
+ }
925
+
926
+ // --- refs -------------------------------------------------------------------
927
+
928
+ /** A ref names control `index` of read `revision`: `r<revision>.<index>`. */
929
+ export function formatRef(revision: number, index: number): string {
930
+ return `r${revision}.${index}`
931
+ }
932
+
933
+ const MAX_INDEX = 0xffff_ffff
934
+
935
+ function plainNumber(s: string, max: number): number | undefined {
936
+ if (!/^(0|[1-9][0-9]*)$/.test(s)) return undefined
937
+ const n = Number(s)
938
+ return Number.isSafeInteger(n) && n <= max ? n : undefined
939
+ }
940
+
941
+ /** The pair a ref names, or `undefined` for a string that is not exactly one. */
942
+ export function parseRef(ref: string): { revision: number; index: number } | undefined {
943
+ const m = /^r([0-9]+)\.([0-9]+)$/.exec(ref)
944
+ if (!m) return undefined
945
+ const revision = plainNumber(m[1] ?? '', MAX_SAFE_ID)
946
+ const index = plainNumber(m[2] ?? '', MAX_INDEX)
947
+ return revision === undefined || index === undefined ? undefined : { revision, index }
948
+ }
949
+
950
+ // --- fingerprints -----------------------------------------------------------
951
+
952
+ /**
953
+ * FNV-1a 32 over the UTF-16 code units of `s`, eight lowercase hex digits:
954
+ * the `nameHash` of a fingerprint, the same as the PowerShell helper wrote.
955
+ */
956
+ export function nameHash(s: string): string {
957
+ let h = 2166136261
958
+ for (let i = 0; i < s.length; i++) {
959
+ h ^= s.charCodeAt(i)
960
+ h = Math.imul(h, 16777619) >>> 0
961
+ }
962
+ return h.toString(16).padStart(8, '0')
963
+ }