antigravity-hands 0.0.0-stage → 0.6.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (58) hide show
  1. package/CHANGELOG.md +46 -0
  2. package/LICENSE +21 -0
  3. package/README.md +135 -2
  4. package/README_ZH.md +100 -0
  5. package/dist/cli.d.ts +2 -0
  6. package/dist/cli.js +121 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/driver/client.d.ts +19 -0
  9. package/dist/driver/client.js +169 -0
  10. package/dist/driver/client.js.map +1 -0
  11. package/dist/driver/downloader.d.ts +29 -0
  12. package/dist/driver/downloader.js +161 -0
  13. package/dist/driver/downloader.js.map +1 -0
  14. package/dist/driver/locator.d.ts +11 -0
  15. package/dist/driver/locator.js +108 -0
  16. package/dist/driver/locator.js.map +1 -0
  17. package/dist/engine/batch.d.ts +125 -0
  18. package/dist/engine/batch.js +910 -0
  19. package/dist/engine/batch.js.map +1 -0
  20. package/dist/engine/script.d.ts +47 -0
  21. package/dist/engine/script.js +403 -0
  22. package/dist/engine/script.js.map +1 -0
  23. package/dist/engine/snapshot.d.ts +23 -0
  24. package/dist/engine/snapshot.js +175 -0
  25. package/dist/engine/snapshot.js.map +1 -0
  26. package/dist/hooks/runner.d.ts +11 -0
  27. package/dist/hooks/runner.js +118 -0
  28. package/dist/hooks/runner.js.map +1 -0
  29. package/dist/installer/index.d.ts +21 -0
  30. package/dist/installer/index.js +170 -0
  31. package/dist/installer/index.js.map +1 -0
  32. package/dist/mcp/protocol.d.ts +38 -0
  33. package/dist/mcp/protocol.js +135 -0
  34. package/dist/mcp/protocol.js.map +1 -0
  35. package/dist/mcp/server.d.ts +19 -0
  36. package/dist/mcp/server.js +576 -0
  37. package/dist/mcp/server.js.map +1 -0
  38. package/dist/safety/policy.d.ts +26 -0
  39. package/dist/safety/policy.js +216 -0
  40. package/dist/safety/policy.js.map +1 -0
  41. package/dist/sidecar/server.d.ts +45 -0
  42. package/dist/sidecar/server.js +568 -0
  43. package/dist/sidecar/server.js.map +1 -0
  44. package/dist/sidecar/telemetry.d.ts +93 -0
  45. package/dist/sidecar/telemetry.js +257 -0
  46. package/dist/sidecar/telemetry.js.map +1 -0
  47. package/dist/sidecar/ui.html +1245 -0
  48. package/dist/types.d.ts +287 -0
  49. package/dist/types.js +21 -0
  50. package/dist/types.js.map +1 -0
  51. package/package.json +57 -4
  52. package/plugin/assets/logo.svg +15 -0
  53. package/plugin/hooks.json +11 -0
  54. package/plugin/mcp_config.json +8 -0
  55. package/plugin/plugin.json +18 -0
  56. package/plugin/rules/AGENTS.md +8 -0
  57. package/plugin/sidecars/hands_console/sidecar.json +21 -0
  58. package/plugin/skills/computer-use/SKILL.md +46 -0
@@ -0,0 +1,910 @@
1
+ import { HandsError, } from "../types.js";
2
+ import { TelemetryStore } from "../sidecar/telemetry.js";
3
+ import { SnapshotStore } from "./snapshot.js";
4
+ function sleep(ms) {
5
+ return new Promise((resolve) => setTimeout(resolve, ms));
6
+ }
7
+ function centerOf(rect) {
8
+ return {
9
+ x: Math.round(rect.x + rect.width / 2),
10
+ y: Math.round(rect.y + rect.height / 2),
11
+ };
12
+ }
13
+ export function formatWindowsCompact(res) {
14
+ const visible = res.windows.filter((w) => !w.is_minimized);
15
+ const offscreen = res.windows.filter((w) => w.is_minimized);
16
+ const lines = [
17
+ `frontmost: ${res.frontmost_app ?? "unknown"} | visible: ${visible.length} | minimized/other-space: ${offscreen.length}`,
18
+ ];
19
+ const fmt = (w) => {
20
+ const b = w.bounds;
21
+ const titlePart = w.title ? ` "${w.title.slice(0, 72)}"` : "";
22
+ const frontTag = w.is_frontmost ? " *frontmost*" : "";
23
+ return `#${w.window_id} | ${w.app} (pid ${w.pid})${titlePart} | [${Math.round(b.x)},${Math.round(b.y)},${Math.round(b.width)}x${Math.round(b.height)}]${frontTag}`;
24
+ };
25
+ if (visible.length > 0) {
26
+ lines.push("[VISIBLE]");
27
+ for (const w of visible)
28
+ lines.push(fmt(w));
29
+ }
30
+ if (offscreen.length > 0) {
31
+ lines.push("[MINIMIZED / OTHER SPACE]");
32
+ for (const w of offscreen)
33
+ lines.push(fmt(w));
34
+ }
35
+ if (visible.length === 0 && offscreen.length === 0) {
36
+ lines.push("(no matching windows)");
37
+ }
38
+ return lines.join("\n");
39
+ }
40
+ export function formatBatchCompact(res) {
41
+ const header = `batch: ${res.ok ? "OK" : "FAILED"} (${res.completed_steps}/${res.total_steps} steps, ${res.total_duration_ms}ms)${res.final_snapshot_id ? ` | snapshot_id: ${res.final_snapshot_id}` : ""}`;
42
+ const lines = [header];
43
+ if (res.aborted_reason) {
44
+ lines.push(`aborted: ${res.aborted_reason}`);
45
+ }
46
+ for (const s of res.steps) {
47
+ if (s.ok) {
48
+ let brief = "";
49
+ if (s.data && typeof s.data === "object") {
50
+ const d = s.data;
51
+ if (typeof d.compact === "string") {
52
+ brief = `snapshot=${String(d.snapshot_id ?? "")} nodes=${String(d.node_count ?? "")}`;
53
+ }
54
+ else {
55
+ brief = JSON.stringify(d);
56
+ }
57
+ }
58
+ lines.push(`#${s.index} ${s.action} (${s.duration_ms}ms): ok${brief ? ` ${brief}` : ""}`);
59
+ }
60
+ else {
61
+ lines.push(`#${s.index} ${s.action} (${s.duration_ms}ms): ERR ${s.error?.code ?? "error"}: ${s.error?.message ?? ""}`);
62
+ }
63
+ }
64
+ if (res.final_observe) {
65
+ lines.push(`[FINAL OBSERVE] strategy: ${res.final_observe.strategy} (ax=${res.final_observe.ax_count}, ocr=${res.final_observe.ocr_count})\n${res.final_observe.compact}`);
66
+ }
67
+ return lines.join("\n");
68
+ }
69
+ export function formatScreenshotMetaCompact(shot, snapshotId) {
70
+ const b = shot.logical_bounds;
71
+ const header = [
72
+ `screenshot: ${shot.width}x${shot.height} ${shot.mime_type}`,
73
+ `bounds: [${Math.round(b.x)},${Math.round(b.y)},${Math.round(b.width)}x${Math.round(b.height)}]`,
74
+ snapshotId ? `snapshot_id: ${snapshotId}` : null,
75
+ shot.marks ? `marks: ${shot.marks.length}` : null,
76
+ ]
77
+ .filter(Boolean)
78
+ .join(" | ");
79
+ if (!shot.marks || shot.marks.length === 0)
80
+ return header;
81
+ const lines = [header];
82
+ for (const m of shot.marks) {
83
+ lines.push(`${m.ref} [${m.source}] ${JSON.stringify(m.label)} @(${Math.round(m.center.x)},${Math.round(m.center.y)})`);
84
+ }
85
+ return lines.join("\n");
86
+ }
87
+ export class HandsEngine {
88
+ driver;
89
+ snapshots;
90
+ safety;
91
+ telemetry;
92
+ constructor(driver, snapshots, safety, telemetry = new TelemetryStore()) {
93
+ this.driver = driver;
94
+ this.snapshots = snapshots;
95
+ this.safety = safety;
96
+ this.telemetry = telemetry;
97
+ }
98
+ assertNotStopped() {
99
+ if (this.telemetry.isEmergencyStopRequested()) {
100
+ throw new HandsError({
101
+ code: "emergency_stop",
102
+ message: "Emergency stop engaged from Hands Live Console. Resume before continuing.",
103
+ retryable: false,
104
+ });
105
+ }
106
+ }
107
+ async takeSnapshot(params) {
108
+ this.safety.assertAppAllowed(params.app);
109
+ const raw = await this.driver.call("ax_snapshot", params);
110
+ this.safety.assertAppAllowed(raw.app);
111
+ const sanitized = this.safety.sanitizeSnapshot(raw);
112
+ return this.snapshots.save(sanitized);
113
+ }
114
+ /**
115
+ * Smart hybrid observer:
116
+ * - mode="auto" (default): reads AX tree first; if AX is unavailable or sparse (< min_ax_nodes),
117
+ * automatically merges native offline Chinese/English OCR marks (@m1..@mN).
118
+ * - mode="ax": AX tree only (fastest).
119
+ * - mode="ocr": native OCR only (best for known canvas/Qt apps).
120
+ * - mode="both" (or include_ocr=true): always merges AX + OCR.
121
+ */
122
+ async observe(params) {
123
+ const start = Date.now();
124
+ this.safety.assertAppAllowed(params.app);
125
+ const mode = params.mode ?? (params.include_ocr ? "both" : "auto");
126
+ const minAx = params.min_ax_nodes ?? 5;
127
+ let axRaw = null;
128
+ if (mode !== "ocr") {
129
+ try {
130
+ const raw = await this.driver.call("ax_snapshot", {
131
+ app: params.app,
132
+ window_id: params.window_id,
133
+ max_depth: params.max_depth ?? 20,
134
+ max_nodes: params.max_nodes ?? 200,
135
+ });
136
+ this.safety.assertAppAllowed(raw.app);
137
+ axRaw = this.safety.sanitizeSnapshot(raw);
138
+ }
139
+ catch (err) {
140
+ if (mode === "ax" ||
141
+ (err instanceof HandsError &&
142
+ (err.code === "policy_blocked" ||
143
+ err.code === "permission_denied" ||
144
+ err.code === "emergency_stop"))) {
145
+ throw err;
146
+ }
147
+ }
148
+ }
149
+ const axCount = axRaw?.nodes.length ?? 0;
150
+ const needsOcr = mode === "ocr" ||
151
+ mode === "both" ||
152
+ (mode === "auto" && (!axRaw || axCount < minAx));
153
+ if (!needsOcr && axRaw) {
154
+ const saved = this.snapshots.save(axRaw);
155
+ this.telemetry.recordEvent({
156
+ tool: "hands_observe",
157
+ mode: "observe",
158
+ app: saved.app,
159
+ window_title: saved.window_title,
160
+ window_id: saved.window_id,
161
+ summary: `ax (${axCount} nodes)`,
162
+ duration_ms: Date.now() - start,
163
+ ok: true,
164
+ });
165
+ return {
166
+ snapshot_id: saved.snapshot_id,
167
+ strategy: "ax",
168
+ app: saved.app,
169
+ window_id: saved.window_id,
170
+ window_title: saved.window_title,
171
+ window_bounds: saved.window_bounds,
172
+ ax_count: axCount,
173
+ ocr_count: 0,
174
+ nodes: saved.nodes,
175
+ compact: SnapshotStore.formatCompact(saved),
176
+ };
177
+ }
178
+ let ocrRes = null;
179
+ try {
180
+ ocrRes = await this.driver.call("ocr", {
181
+ app: axRaw?.app ?? params.app,
182
+ window_id: axRaw?.window_id ?? params.window_id,
183
+ languages: params.languages ?? ["zh-Hans", "zh-Hant", "en-US"],
184
+ });
185
+ }
186
+ catch (err) {
187
+ if (!axRaw ||
188
+ mode === "ocr" ||
189
+ (err instanceof HandsError && err.code === "window_not_visible")) {
190
+ throw err;
191
+ }
192
+ }
193
+ const base = axRaw ?? {
194
+ app: ocrRes?.app ?? params.app ?? "Desktop",
195
+ pid: 0,
196
+ window_id: ocrRes?.window_id ?? params.window_id,
197
+ window_title: ocrRes?.app ?? params.app ?? "Desktop",
198
+ nodes: [],
199
+ truncated: false,
200
+ };
201
+ const merged = ocrRes
202
+ ? this.snapshots.mergeOcrLines(base, ocrRes.lines)
203
+ : this.snapshots.save(base);
204
+ const ocrCount = Math.max(0, merged.nodes.length - axCount);
205
+ const strategy = axRaw && ocrCount > 0 ? "ax+ocr" : axRaw ? "ax" : "ocr";
206
+ this.telemetry.recordEvent({
207
+ tool: "hands_observe",
208
+ mode: "observe",
209
+ app: merged.app,
210
+ window_title: merged.window_title,
211
+ window_id: merged.window_id,
212
+ summary: `${strategy} (ax=${axCount}, ocr=${ocrCount})`,
213
+ duration_ms: Date.now() - start,
214
+ ok: true,
215
+ });
216
+ return {
217
+ snapshot_id: merged.snapshot_id,
218
+ strategy,
219
+ app: merged.app,
220
+ window_id: merged.window_id,
221
+ window_title: merged.window_title,
222
+ window_bounds: merged.window_bounds,
223
+ ax_count: axCount,
224
+ ocr_count: ocrCount,
225
+ nodes: merged.nodes,
226
+ compact: SnapshotStore.formatCompact(merged),
227
+ };
228
+ }
229
+ async takeScreenshot(params) {
230
+ const start = Date.now();
231
+ this.safety.assertAppAllowed(params.app);
232
+ const shot = await this.driver.call("screenshot", {
233
+ app: params.app,
234
+ window_id: params.window_id,
235
+ max_width: params.max_width ?? 1024,
236
+ format: params.format ?? "jpeg",
237
+ annotate: params.annotate ?? false,
238
+ languages: params.languages ?? ["zh-Hans", "zh-Hant", "en-US"],
239
+ });
240
+ let snapshotId;
241
+ if (params.annotate && shot.marks && shot.marks.length > 0) {
242
+ const saved = this.snapshots.saveMarks({
243
+ app: shot.app ?? params.app ?? "Desktop",
244
+ window_id: shot.window_id ?? params.window_id,
245
+ window_bounds: shot.logical_bounds,
246
+ marks: shot.marks,
247
+ });
248
+ snapshotId = saved.snapshot_id;
249
+ }
250
+ const appName = shot.app ?? params.app ?? "Desktop";
251
+ this.telemetry.recordFrame({
252
+ app: appName,
253
+ window_title: appName,
254
+ mime_type: shot.mime_type,
255
+ width: shot.width,
256
+ height: shot.height,
257
+ logical_bounds: shot.logical_bounds,
258
+ annotated: Boolean(params.annotate),
259
+ marks_count: shot.marks?.length ?? 0,
260
+ }, shot.data_base64);
261
+ this.telemetry.recordEvent({
262
+ tool: "hands_screenshot",
263
+ mode: "observe",
264
+ app: appName,
265
+ window_id: shot.window_id ?? params.window_id,
266
+ summary: `${shot.width}x${shot.height}${params.annotate ? ` · SoM ${shot.marks?.length ?? 0} marks` : ""}`,
267
+ duration_ms: Date.now() - start,
268
+ ok: true,
269
+ });
270
+ return { shot, snapshot_id: snapshotId };
271
+ }
272
+ async clickTarget(params) {
273
+ this.assertNotStopped();
274
+ const start = Date.now();
275
+ const button = params.button ?? "left";
276
+ const clickCount = params.click_count ?? 1;
277
+ const preferBg = params.prefer_background ?? true;
278
+ if (params.ocr_text) {
279
+ this.safety.assertAppAllowed(params.app);
280
+ const ocr = await this.driver.call("ocr", {
281
+ app: params.app,
282
+ window_id: params.window_id,
283
+ languages: ["zh-Hans", "zh-Hant", "en-US"],
284
+ });
285
+ const needle = params.ocr_text.trim().toLowerCase();
286
+ const hit = ocr.lines.find((l) => l.text.trim().toLowerCase() === needle) ??
287
+ ocr.lines.find((l) => l.text.toLowerCase().includes(needle));
288
+ if (!hit) {
289
+ throw new HandsError({
290
+ code: "element_not_found",
291
+ message: `OCR could not find text "${params.ocr_text}" in ${params.app ?? "target window"}.`,
292
+ retryable: true,
293
+ });
294
+ }
295
+ this.safety.assertTextTargetAllowed(hit.text, {
296
+ allowDestructive: params.allow_destructive,
297
+ });
298
+ if (params.app || params.window_id) {
299
+ await this.driver.call("focus_app", {
300
+ app: params.app,
301
+ window_id: params.window_id,
302
+ launch: false,
303
+ });
304
+ await sleep(80);
305
+ }
306
+ await this.driver.call("click", {
307
+ x: hit.center.x,
308
+ y: hit.center.y,
309
+ button,
310
+ click_count: clickCount,
311
+ restore_cursor: params.restore_cursor ?? false,
312
+ });
313
+ this.telemetry.recordEvent({
314
+ tool: clickCount === 2 ? "hands_double_click" : "hands_click",
315
+ mode: "foreground",
316
+ app: params.app,
317
+ window_id: params.window_id,
318
+ summary: `ocr "${hit.text.slice(0, 48)}" @(${Math.round(hit.center.x)},${Math.round(hit.center.y)})`,
319
+ duration_ms: Date.now() - start,
320
+ ok: true,
321
+ click_point: { x: hit.center.x, y: hit.center.y },
322
+ });
323
+ return {
324
+ method: "ocr_click",
325
+ x: hit.center.x,
326
+ y: hit.center.y,
327
+ matched_text: hit.text,
328
+ };
329
+ }
330
+ let resolvedNode = null;
331
+ let resolvedSnap = null;
332
+ if (params.ref) {
333
+ const res = this.snapshots.resolveRef(params.ref, params.snapshot_id);
334
+ resolvedSnap = res.snapshot;
335
+ resolvedNode = res.node;
336
+ }
337
+ else if (params.label || params.role) {
338
+ resolvedSnap = await this.takeSnapshot({
339
+ app: params.app,
340
+ window_id: params.window_id,
341
+ });
342
+ resolvedNode = this.snapshots.findSemantic(resolvedSnap, {
343
+ app: params.app,
344
+ window_id: params.window_id,
345
+ label: params.label,
346
+ role: params.role,
347
+ });
348
+ if (!resolvedNode) {
349
+ throw new HandsError({
350
+ code: "element_not_found",
351
+ message: `Could not find element matching label="${params.label ?? ""}" role="${params.role ?? ""}" in ${resolvedSnap.app}.`,
352
+ retryable: true,
353
+ });
354
+ }
355
+ }
356
+ if (resolvedNode && resolvedSnap) {
357
+ this.safety.assertAppAllowed(resolvedSnap.app);
358
+ this.safety.assertElementAllowed(resolvedNode, {
359
+ allowDestructive: params.allow_destructive,
360
+ });
361
+ const canBackgroundPress = preferBg &&
362
+ button === "left" &&
363
+ clickCount === 1 &&
364
+ resolvedNode.path.length > 0 &&
365
+ resolvedNode.actions.some((a) => a === "AXPress" || a === "invoke" || a === "press");
366
+ if (canBackgroundPress) {
367
+ try {
368
+ await this.driver.call("ax_action", {
369
+ pid: resolvedSnap.pid,
370
+ window_id: resolvedSnap.window_id,
371
+ path: resolvedNode.path,
372
+ action: "press",
373
+ });
374
+ this.telemetry.recordEvent({
375
+ tool: "hands_click",
376
+ mode: "background",
377
+ app: resolvedSnap.app,
378
+ window_title: resolvedSnap.window_title,
379
+ window_id: resolvedSnap.window_id,
380
+ summary: `BG AXPress ${resolvedNode.ref} (${resolvedNode.label || resolvedNode.role})`,
381
+ duration_ms: Date.now() - start,
382
+ ok: true,
383
+ });
384
+ return { method: "background_ax_press", ref: resolvedNode.ref };
385
+ }
386
+ catch (err) {
387
+ if (err instanceof HandsError && err.code === "emergency_stop") {
388
+ throw err;
389
+ }
390
+ }
391
+ }
392
+ const pt = centerOf(resolvedNode.bounds);
393
+ if (resolvedSnap.pid || resolvedSnap.window_id || resolvedSnap.app) {
394
+ await this.driver
395
+ .call("focus_app", {
396
+ pid: resolvedSnap.pid || undefined,
397
+ app: resolvedSnap.pid ? undefined : resolvedSnap.app,
398
+ window_id: resolvedSnap.window_id,
399
+ launch: false,
400
+ })
401
+ .catch(() => undefined);
402
+ await sleep(80);
403
+ }
404
+ await this.driver.call("click", {
405
+ x: pt.x,
406
+ y: pt.y,
407
+ button,
408
+ click_count: clickCount,
409
+ restore_cursor: params.restore_cursor ?? false,
410
+ });
411
+ const method = resolvedNode.role === "OCRText" ? "som_ocr_click" : "synthetic_click";
412
+ this.telemetry.recordEvent({
413
+ tool: clickCount === 2 ? "hands_double_click" : "hands_click",
414
+ mode: "foreground",
415
+ app: resolvedSnap.app,
416
+ window_title: resolvedSnap.window_title,
417
+ window_id: resolvedSnap.window_id,
418
+ summary: `${method} ${resolvedNode.ref} (${resolvedNode.label || resolvedNode.role}) @(${pt.x},${pt.y})`,
419
+ duration_ms: Date.now() - start,
420
+ ok: true,
421
+ click_point: pt,
422
+ });
423
+ return {
424
+ method,
425
+ x: pt.x,
426
+ y: pt.y,
427
+ ref: resolvedNode.ref,
428
+ };
429
+ }
430
+ if (params.x === undefined || params.y === undefined) {
431
+ throw new HandsError({
432
+ code: "element_not_found",
433
+ message: "Provide ref, semantic (label/role), ocr_text, or (x, y) coordinates to click.",
434
+ retryable: false,
435
+ });
436
+ }
437
+ this.safety.assertAppAllowed(params.app);
438
+ await this.driver.call("click", {
439
+ x: params.x,
440
+ y: params.y,
441
+ button,
442
+ click_count: clickCount,
443
+ restore_cursor: params.restore_cursor ?? false,
444
+ });
445
+ this.telemetry.recordEvent({
446
+ tool: clickCount === 2 ? "hands_double_click" : "hands_click",
447
+ mode: "foreground",
448
+ app: params.app,
449
+ summary: `click @(${params.x},${params.y})`,
450
+ duration_ms: Date.now() - start,
451
+ ok: true,
452
+ click_point: { x: params.x, y: params.y },
453
+ });
454
+ return { method: "synthetic_click", x: params.x, y: params.y };
455
+ }
456
+ async typeText(params) {
457
+ this.assertNotStopped();
458
+ const start = Date.now();
459
+ const preferBg = params.prefer_background ?? true;
460
+ let resolvedNode = null;
461
+ let resolvedSnap = null;
462
+ if (params.ref) {
463
+ const res = this.snapshots.resolveRef(params.ref, params.snapshot_id);
464
+ resolvedSnap = res.snapshot;
465
+ resolvedNode = res.node;
466
+ }
467
+ else if (params.label || params.role) {
468
+ resolvedSnap = await this.takeSnapshot({
469
+ app: params.app,
470
+ window_id: params.window_id,
471
+ });
472
+ resolvedNode = this.snapshots.findSemantic(resolvedSnap, {
473
+ app: params.app,
474
+ window_id: params.window_id,
475
+ label: params.label,
476
+ role: params.role,
477
+ });
478
+ if (!resolvedNode) {
479
+ throw new HandsError({
480
+ code: "element_not_found",
481
+ message: `Could not find text element matching label="${params.label ?? ""}" role="${params.role ?? ""}".`,
482
+ retryable: true,
483
+ });
484
+ }
485
+ }
486
+ if (resolvedNode && resolvedSnap) {
487
+ this.safety.assertAppAllowed(resolvedSnap.app);
488
+ this.safety.assertElementAllowed(resolvedNode, { isWrite: true });
489
+ const supportsSetValue = preferBg &&
490
+ resolvedNode.path.length > 0 &&
491
+ resolvedNode.actions.some((a) => a === "AXSetValue" || a === "set_value");
492
+ if (supportsSetValue) {
493
+ try {
494
+ await this.driver.call("ax_action", {
495
+ pid: resolvedSnap.pid,
496
+ window_id: resolvedSnap.window_id,
497
+ path: resolvedNode.path,
498
+ action: "set_value",
499
+ value: params.text,
500
+ });
501
+ this.telemetry.recordEvent({
502
+ tool: "hands_type_text",
503
+ mode: "background",
504
+ app: resolvedSnap.app,
505
+ window_title: resolvedSnap.window_title,
506
+ window_id: resolvedSnap.window_id,
507
+ summary: `BG AXSetValue ${resolvedNode.ref} (${params.text.length} chars)`,
508
+ duration_ms: Date.now() - start,
509
+ ok: true,
510
+ });
511
+ return {
512
+ method: "background_ax_set_value",
513
+ length: params.text.length,
514
+ ref: resolvedNode.ref,
515
+ };
516
+ }
517
+ catch (err) {
518
+ if (err instanceof HandsError && err.code === "emergency_stop") {
519
+ throw err;
520
+ }
521
+ }
522
+ }
523
+ const pt = centerOf(resolvedNode.bounds);
524
+ if (resolvedSnap.pid || resolvedSnap.window_id || resolvedSnap.app) {
525
+ await this.driver
526
+ .call("focus_app", {
527
+ pid: resolvedSnap.pid || undefined,
528
+ app: resolvedSnap.pid ? undefined : resolvedSnap.app,
529
+ window_id: resolvedSnap.window_id,
530
+ launch: false,
531
+ })
532
+ .catch(() => undefined);
533
+ await sleep(80);
534
+ }
535
+ await this.driver.call("click", { x: pt.x, y: pt.y, button: "left", click_count: 1 });
536
+ await sleep(60);
537
+ }
538
+ else {
539
+ this.safety.assertAppAllowed(params.app);
540
+ }
541
+ await this.driver.call("type_text", {
542
+ text: params.text,
543
+ method: params.method ?? "auto",
544
+ clear_first: params.clear_first ?? false,
545
+ });
546
+ this.telemetry.recordEvent({
547
+ tool: "hands_type_text",
548
+ mode: "foreground",
549
+ app: resolvedSnap?.app ?? params.app,
550
+ summary: `Typed ${params.text.length} chars (${params.method ?? "auto"})`,
551
+ duration_ms: Date.now() - start,
552
+ ok: true,
553
+ });
554
+ return {
555
+ method: params.method ?? "auto",
556
+ length: params.text.length,
557
+ ref: resolvedNode?.ref,
558
+ };
559
+ }
560
+ async pressKeyOrChord(params) {
561
+ this.assertNotStopped();
562
+ const start = Date.now();
563
+ const repeat = params.repeat ?? 1;
564
+ const delay_ms = params.delay_ms ?? 35;
565
+ if (params.keys && params.keys.length > 0) {
566
+ const res = params.keys.length === 1
567
+ ? await this.driver.call("press_key", {
568
+ key: params.keys[0],
569
+ modifiers: params.modifiers ?? [],
570
+ repeat,
571
+ delay_ms,
572
+ })
573
+ : await this.driver.call("hotkey", { keys: params.keys, repeat, delay_ms });
574
+ this.telemetry.recordEvent({
575
+ tool: "hands_key",
576
+ mode: "foreground",
577
+ summary: `${params.keys.join("+")}${repeat > 1 ? ` ×${repeat}` : ""}`,
578
+ duration_ms: Date.now() - start,
579
+ ok: true,
580
+ });
581
+ return res;
582
+ }
583
+ if (!params.key) {
584
+ throw new HandsError({
585
+ code: "internal_error",
586
+ message: "Provide either `key` (single key) or `keys` (shortcut chord).",
587
+ });
588
+ }
589
+ const res = await this.driver.call("press_key", {
590
+ key: params.key,
591
+ modifiers: params.modifiers ?? [],
592
+ repeat,
593
+ delay_ms,
594
+ });
595
+ this.telemetry.recordEvent({
596
+ tool: "hands_key",
597
+ mode: "foreground",
598
+ summary: `${params.key}${repeat > 1 ? ` ×${repeat}` : ""}`,
599
+ duration_ms: Date.now() - start,
600
+ ok: true,
601
+ });
602
+ return res;
603
+ }
604
+ async waitFor(params) {
605
+ const timeoutMs = params.timeout_ms ?? 8000;
606
+ const pollMs = Math.max(150, params.poll_ms ?? 350);
607
+ const start = Date.now();
608
+ while (Date.now() - start <= timeoutMs) {
609
+ if (params.ocr_text) {
610
+ this.safety.assertAppAllowed(params.app);
611
+ const ocr = await this.driver.call("ocr", {
612
+ app: params.app,
613
+ window_id: params.window_id,
614
+ languages: ["zh-Hans", "zh-Hant", "en-US"],
615
+ });
616
+ const needle = params.ocr_text.toLowerCase();
617
+ const hit = ocr.lines.find((l) => l.text.toLowerCase().includes(needle));
618
+ if (hit) {
619
+ return {
620
+ matched: true,
621
+ elapsed_ms: Date.now() - start,
622
+ ocr_match: hit,
623
+ };
624
+ }
625
+ }
626
+ else {
627
+ const snap = await this.takeSnapshot({
628
+ app: params.app,
629
+ window_id: params.window_id,
630
+ });
631
+ const hit = this.snapshots.findSemantic(snap, {
632
+ app: params.app,
633
+ window_id: params.window_id,
634
+ label: params.label,
635
+ role: params.role,
636
+ });
637
+ if (hit) {
638
+ return {
639
+ matched: true,
640
+ elapsed_ms: Date.now() - start,
641
+ snapshot_id: snap.snapshot_id,
642
+ ref: hit.ref,
643
+ };
644
+ }
645
+ }
646
+ await sleep(pollMs);
647
+ }
648
+ throw new HandsError({
649
+ code: "timeout",
650
+ message: `wait_for timed out after ${timeoutMs}ms waiting for ${params.ocr_text ? `ocr="${params.ocr_text}"` : `label="${params.label ?? ""}" role="${params.role ?? ""}"`}.`,
651
+ retryable: true,
652
+ });
653
+ }
654
+ async runBatch(params) {
655
+ const batchStart = Date.now();
656
+ const reports = [];
657
+ const showHud = params.show_hud ?? true;
658
+ let savedFocus = null;
659
+ let latestSnapshotId;
660
+ let activeApp = this.snapshots.get()?.app;
661
+ let activeWindowId = this.snapshots.get()?.window_id;
662
+ let activeHudBounds = params.hud_bounds ?? (await this.inferInitialHudBounds(params.steps));
663
+ if (params.reset_emergency_stop) {
664
+ await this.driver.call("reset_stop").catch(() => undefined);
665
+ this.telemetry.setEmergencyStop(false, "Reset by hands_batch");
666
+ }
667
+ if (params.restore_focus || params.restore_cursor) {
668
+ savedFocus = await this.driver
669
+ .call("capture_focus_state")
670
+ .catch(() => null);
671
+ }
672
+ try {
673
+ for (let i = 0; i < params.steps.length; i++) {
674
+ this.assertNotStopped();
675
+ const step = params.steps[i];
676
+ const stepStart = Date.now();
677
+ if ("app" in step && step.app)
678
+ activeApp = step.app;
679
+ if ("window_id" in step && step.window_id !== undefined) {
680
+ activeWindowId = step.window_id;
681
+ }
682
+ this.telemetry.setActive(true, `Batch ${i + 1}/${params.steps.length}: ${this.describeStep(step)}`, activeApp);
683
+ if (showHud) {
684
+ await this.driver
685
+ .call("hud_show", {
686
+ bounds: activeHudBounds,
687
+ status: `Step ${i + 1}/${params.steps.length}: ${this.describeStep(step)} · Esc to stop`,
688
+ state: step.action === "wait" || step.action === "wait_for" ? "waiting" : "working",
689
+ })
690
+ .catch(() => undefined);
691
+ }
692
+ try {
693
+ const data = await this.executeStep(step, latestSnapshotId);
694
+ if (data && typeof data === "object") {
695
+ const obj = data;
696
+ if (typeof obj.snapshot_id === "string") {
697
+ latestSnapshotId = obj.snapshot_id;
698
+ }
699
+ if (typeof obj.app === "string" && obj.app)
700
+ activeApp = obj.app;
701
+ if (typeof obj.window_id === "number" && obj.window_id > 0) {
702
+ activeWindowId = obj.window_id;
703
+ }
704
+ const freshBounds = obj.window_bounds ?? obj.bounds;
705
+ if (freshBounds && !params.hud_bounds) {
706
+ activeHudBounds = freshBounds;
707
+ }
708
+ }
709
+ reports.push({
710
+ index: i,
711
+ action: step.action,
712
+ ok: true,
713
+ duration_ms: Date.now() - stepStart,
714
+ data,
715
+ });
716
+ }
717
+ catch (err) {
718
+ const handsErr = err instanceof HandsError
719
+ ? err
720
+ : new HandsError({
721
+ code: "internal_error",
722
+ message: err instanceof Error ? err.message : String(err),
723
+ });
724
+ reports.push({
725
+ index: i,
726
+ action: step.action,
727
+ ok: false,
728
+ duration_ms: Date.now() - stepStart,
729
+ error: handsErr.toJSON(),
730
+ });
731
+ return {
732
+ ok: false,
733
+ completed_steps: i,
734
+ total_steps: params.steps.length,
735
+ total_duration_ms: Date.now() - batchStart,
736
+ aborted_reason: `${handsErr.code}: ${handsErr.message}`,
737
+ steps: reports,
738
+ final_snapshot_id: latestSnapshotId,
739
+ };
740
+ }
741
+ }
742
+ let finalObserve;
743
+ if (params.final_observe) {
744
+ const delayMs = params.final_observe_delay_ms ?? 300;
745
+ if (delayMs > 0)
746
+ await sleep(delayMs);
747
+ finalObserve = await this.observe({
748
+ app: activeApp,
749
+ window_id: activeWindowId,
750
+ mode: params.final_observe_mode ?? "auto",
751
+ });
752
+ latestSnapshotId = finalObserve.snapshot_id;
753
+ }
754
+ return {
755
+ ok: true,
756
+ completed_steps: params.steps.length,
757
+ total_steps: params.steps.length,
758
+ total_duration_ms: Date.now() - batchStart,
759
+ steps: reports,
760
+ final_snapshot_id: latestSnapshotId,
761
+ final_observe: finalObserve,
762
+ };
763
+ }
764
+ finally {
765
+ this.telemetry.setActive(false);
766
+ if (showHud) {
767
+ await this.driver.call("hud_hide").catch(() => undefined);
768
+ }
769
+ if (savedFocus && (params.restore_focus || params.restore_cursor)) {
770
+ await this.driver
771
+ .call("restore_focus_state", {
772
+ pid: params.restore_focus ? savedFocus.pid : undefined,
773
+ app: params.restore_focus ? savedFocus.app : undefined,
774
+ cursor: params.restore_cursor ? savedFocus.cursor : undefined,
775
+ })
776
+ .catch(() => undefined);
777
+ }
778
+ }
779
+ }
780
+ async inferInitialHudBounds(steps) {
781
+ const latest = this.snapshots.get();
782
+ if (latest?.window_bounds)
783
+ return latest.window_bounds;
784
+ const firstApp = steps.find((s) => "app" in s && typeof s.app === "string" && s.app.length > 0)?.app;
785
+ if (!firstApp)
786
+ return undefined;
787
+ try {
788
+ const list = await this.driver.call("list_windows", { app: firstApp });
789
+ return list.windows[0]?.bounds;
790
+ }
791
+ catch {
792
+ return undefined;
793
+ }
794
+ }
795
+ describeStep(step) {
796
+ switch (step.action) {
797
+ case "focus_app":
798
+ return `focus ${step.app ?? "window"}`;
799
+ case "click":
800
+ case "double_click":
801
+ case "right_click":
802
+ return `${step.action} ${step.ref ?? step.ocr_text ?? step.label ?? `(${step.x},${step.y})`}`;
803
+ case "type_text":
804
+ return `type ${step.text.length} chars`;
805
+ case "hotkey":
806
+ return `hotkey ${step.keys.join("+")}`;
807
+ case "press_key":
808
+ case "key":
809
+ return `key ${step.keys ? step.keys.join("+") : (step.key ?? "")}`;
810
+ case "wait_for":
811
+ return `wait for ${step.ocr_text ?? step.label ?? step.role ?? "UI"}`;
812
+ default:
813
+ return step.action;
814
+ }
815
+ }
816
+ async executeStep(step, fallbackSnapshotId) {
817
+ switch (step.action) {
818
+ case "focus_app":
819
+ this.safety.assertAppAllowed(step.app);
820
+ return this.driver.call("focus_app", {
821
+ app: step.app,
822
+ pid: step.pid,
823
+ window_id: step.window_id,
824
+ launch: step.launch ?? true,
825
+ });
826
+ case "click":
827
+ return this.clickTarget({
828
+ ...step,
829
+ snapshot_id: step.snapshot_id ?? fallbackSnapshotId,
830
+ button: step.button ?? "left",
831
+ click_count: step.click_count ?? 1,
832
+ });
833
+ case "double_click":
834
+ return this.clickTarget({
835
+ ...step,
836
+ snapshot_id: step.snapshot_id ?? fallbackSnapshotId,
837
+ button: "left",
838
+ click_count: 2,
839
+ });
840
+ case "right_click":
841
+ return this.clickTarget({
842
+ ...step,
843
+ snapshot_id: step.snapshot_id ?? fallbackSnapshotId,
844
+ button: "right",
845
+ click_count: 1,
846
+ });
847
+ case "type_text":
848
+ return this.typeText({
849
+ ...step,
850
+ snapshot_id: step.snapshot_id ?? fallbackSnapshotId,
851
+ });
852
+ case "press_key":
853
+ case "key":
854
+ return this.pressKeyOrChord({
855
+ key: step.key,
856
+ keys: step.keys,
857
+ modifiers: step.modifiers,
858
+ repeat: step.repeat,
859
+ delay_ms: step.delay_ms,
860
+ });
861
+ case "hotkey":
862
+ return this.driver.call("hotkey", {
863
+ keys: step.keys,
864
+ repeat: step.repeat ?? 1,
865
+ delay_ms: step.delay_ms ?? 40,
866
+ });
867
+ case "scroll":
868
+ return this.driver.call("scroll", {
869
+ x: step.x,
870
+ y: step.y,
871
+ delta_x: step.delta_x ?? 0,
872
+ delta_y: step.delta_y ?? -120,
873
+ repeat: step.repeat ?? 1,
874
+ delay_ms: step.delay_ms ?? 35,
875
+ });
876
+ case "drag":
877
+ return this.driver.call("drag", {
878
+ x1: step.x1,
879
+ y1: step.y1,
880
+ x2: step.x2,
881
+ y2: step.y2,
882
+ duration_ms: step.duration_ms ?? 250,
883
+ });
884
+ case "wait":
885
+ await sleep(Math.min(30_000, Math.max(0, step.ms)));
886
+ return { waited_ms: step.ms };
887
+ case "wait_for":
888
+ return this.waitFor(step);
889
+ case "observe":
890
+ return this.observe(step);
891
+ case "ax_snapshot": {
892
+ const snap = await this.takeSnapshot(step);
893
+ return {
894
+ snapshot_id: snap.snapshot_id,
895
+ window_bounds: snap.window_bounds,
896
+ node_count: snap.nodes.length,
897
+ compact: SnapshotStore.formatCompact(snap),
898
+ };
899
+ }
900
+ case "ocr":
901
+ this.safety.assertAppAllowed(step.app);
902
+ return this.driver.call("ocr", {
903
+ app: step.app,
904
+ window_id: step.window_id,
905
+ languages: step.languages,
906
+ });
907
+ }
908
+ }
909
+ }
910
+ //# sourceMappingURL=batch.js.map