@aivin-labs/cli 1.0.51 → 1.0.57
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.
- package/bin/cli.mjs +2214 -2211
- package/bin/lib/remote/agentContract.mjs +370 -0
- package/bin/lib/remote/agentEvidence.mjs +409 -0
- package/bin/lib/remote/autoStart.mjs +640 -623
- package/bin/lib/remote/client.mjs +1454 -1418
- package/bin/lib/remote/codingAgents.mjs +594 -293
- package/bin/lib/remote/constants.mjs +1 -1
- package/bin/lib/remote/desktop/castAuth.mjs +259 -249
- package/bin/lib/remote/desktop/castConsent.mjs +154 -90
- package/bin/lib/remote/desktop/castInput.mjs +3 -0
- package/bin/lib/remote/desktop/castTrust.mjs +184 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +483 -443
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +1 -1
- package/bin/lib/remote/desktop/desktopCastSource.mjs +250 -12
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +59 -4
- package/bin/lib/remote/desktop/strings.mjs +138 -132
- package/bin/lib/remote/desktop/traySource.mjs +1438 -1385
- package/bin/lib/remote/gui/index.mjs +567 -485
- package/bin/lib/remote/gui/windowsHostSource.mjs +630 -33
- package/bin/lib/remote/humanInput.mjs +7 -0
- package/bin/lib/remote/localConfirm.mjs +2 -2
- package/bin/lib/remote/toolHandlers.mjs +861 -859
- package/docs/CLI.md +1606 -1602
- package/package.json +1 -1
|
@@ -1,485 +1,567 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import { spawn } from 'child_process';
|
|
4
|
-
import { DeviceErrorCode, ToolGroup } from '../constants.mjs';
|
|
5
|
-
import { DeviceToolError, resolveInRoots } from '../sandbox.mjs';
|
|
6
|
-
import { showOSNotification } from '../notify.mjs';
|
|
7
|
-
import { PS_UTF8_PREFIX } from '../processes.mjs';
|
|
8
|
-
import { createWindowsHost } from './windowsHost.mjs';
|
|
9
|
-
import { isProtectedPromptWindow } from '../humanInput.mjs';
|
|
10
|
-
|
|
11
|
-
/**
|
|
12
|
-
* Tầng điều khiển giao diện (28/10/2026, đợt 1: Windows). Nhìn cửa sổ bằng cây trợ năng của hệ điều hành (UI Automation) + ảnh khi cây
|
|
13
|
-
* nghèo; thao tác theo "pattern" (Invoke / Value / Toggle…) trước, chuột / phím giả lập sau. Mọi thao tác ghi trả bằng chứng đọc lại
|
|
14
|
-
* sau khi làm (giá trị mới, tiêu đề cửa sổ, phần tử còn / mất).
|
|
15
|
-
*
|
|
16
|
-
* Đợt 2 (30/10/2026): cây nghèo → host đọc chữ trên ảnh bằng OCR có sẵn của Windows (chạy trên máy), mỗi cụm chữ thành node `<snap>.t<k>`
|
|
17
|
-
* click / gõ được — BE tìm "nút Ghi sổ" theo chữ thay vì nhờ VLM đoán toạ độ; `gui.wait_for` chờ phần tử / cửa sổ hiện ra hoặc mất đi
|
|
18
|
-
* thay cho observe lặp.
|
|
19
|
-
*
|
|
20
|
-
* Sàn cứng trên máy (BE không đổi được): không gõ vào ô mật khẩu (host chặn), không điều khiển ứng dụng nhạy cảm (`BLOCKED_PROCESSES`),
|
|
21
|
-
* máy chỉ mở thư mục (không toàn quyền) thì không điều khiển cửa sổ dòng lệnh / registry — không lách vùng thư mục bằng cách gõ lệnh
|
|
22
|
-
* vào terminal; người dùng đang dùng chuột / phím → dừng (`GUI_USER_ACTIVE`).
|
|
23
|
-
*/
|
|
24
|
-
|
|
25
|
-
/** Tiến trình không bao giờ điều khiển: quản lý mật khẩu, hộp nâng quyền, bảo mật hệ thống, màn hình khoá. */
|
|
26
|
-
const BLOCKED_PROCESSES = new Set([
|
|
27
|
-
'consent', 'credentialuihost', 'lockapp', 'logonui', 'securityhealthsystray', 'securityhealthhost', 'windowsdefender', 'msmpeng',
|
|
28
|
-
'keepass', 'keepassxc', '1password', 'bitwarden', 'lastpass', 'dashlane', 'enpass', 'nordpass', 'roboform',
|
|
29
|
-
]);
|
|
30
|
-
/**
|
|
31
|
-
* Chỉ cho khi máy toàn quyền — điều khiển được những thứ này là chạy lệnh tuỳ ý ngoài vùng thư mục: terminal / registry, và (30/10/2026)
|
|
32
|
-
* trình soạn code có terminal tích hợp + ứng dụng agent tự chạy lệnh (VS Code, Cursor, Claude…) — gõ vào terminal của VS Code hay nhờ panel
|
|
33
|
-
* Claude chạy lệnh cũng là lách vùng thư mục như gõ vào cmd.
|
|
34
|
-
*/
|
|
35
|
-
const SHELL_PROCESSES = new Set([
|
|
36
|
-
'cmd', 'powershell', 'pwsh', 'windowsterminal', 'wt', 'openconsole', 'conhost', 'regedit', 'mmc', 'taskmgr', 'wsl', 'bash', 'mintty',
|
|
37
|
-
'code', 'code - insiders', 'codium', 'cursor', 'windsurf', 'zed', 'devenv', 'idea64', 'pycharm64', 'webstorm64', 'rider64', 'goland64',
|
|
38
|
-
'claude', 'chatgpt', 'warp', 'alacritty', 'wezterm-gui', 'hyper', 'tabby',
|
|
39
|
-
]);
|
|
40
|
-
/** Cùng nhóm đó theo tên trong menu Start (`gui.open_app` tìm theo tên, khác tên tiến trình) — chặn trước khi mở. */
|
|
41
|
-
const SHELL_APP_NAME = /\b(command prompt|powershell|terminal|registry editor|task manager|visual studio|vs ?code|cursor|windsurf|zed|intellij|pycharm|webstorm|rider|goland|claude|chatgpt|warp|alacritty|wezterm|hyper|tabby|wsl|ubuntu|git bash)\b/i;
|
|
42
|
-
/** Không mở tệp có đuôi chạy được bằng `gui.open_app` (mở = chạy chương trình). */
|
|
43
|
-
const EXECUTABLE_EXT = /\.(exe|com|bat|cmd|ps1|psm1|vbs|vbe|js|jse|wsf|wsh|msi|msp|lnk|scr|pif|hta|cpl|jar|reg|url|appref-ms|application)$/i;
|
|
44
|
-
|
|
45
|
-
const OBSERVE_MAX_NODES = 300;
|
|
46
|
-
const APPS_CACHE_MS = 10 * 60_000;
|
|
47
|
-
const OPEN_WAIT_MS = 10_000;
|
|
48
|
-
const WAIT_MAX_MS = 60_000;
|
|
49
|
-
const FIND_DEFAULT = 20;
|
|
50
|
-
const FIND_MAX = 60;
|
|
51
|
-
const SEMANTIC_CHOICES = 5;
|
|
52
|
-
/** Báo người dùng "AI đang điều khiển" một lần mỗi quãng này (lần thao tác ghi đầu tiên). */
|
|
53
|
-
const NOTIFY_EVERY_MS = 5 * 60_000;
|
|
54
|
-
|
|
55
|
-
const
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
const
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
});
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
export
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
if (
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
if (
|
|
93
|
-
throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP,
|
|
94
|
-
}
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
*/
|
|
104
|
-
export function
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
.
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
async function
|
|
249
|
-
const
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
const
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
if (command === '
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
const
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
return {
|
|
428
|
-
}
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
})
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
}
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { spawn } from 'child_process';
|
|
4
|
+
import { DeviceErrorCode, ToolGroup } from '../constants.mjs';
|
|
5
|
+
import { DeviceToolError, resolveInRoots } from '../sandbox.mjs';
|
|
6
|
+
import { showOSNotification } from '../notify.mjs';
|
|
7
|
+
import { PS_UTF8_PREFIX } from '../processes.mjs';
|
|
8
|
+
import { createWindowsHost } from './windowsHost.mjs';
|
|
9
|
+
import { isProtectedPromptWindow } from '../humanInput.mjs';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Tầng điều khiển giao diện (28/10/2026, đợt 1: Windows). Nhìn cửa sổ bằng cây trợ năng của hệ điều hành (UI Automation) + ảnh khi cây
|
|
13
|
+
* nghèo; thao tác theo "pattern" (Invoke / Value / Toggle…) trước, chuột / phím giả lập sau. Mọi thao tác ghi trả bằng chứng đọc lại
|
|
14
|
+
* sau khi làm (giá trị mới, tiêu đề cửa sổ, phần tử còn / mất).
|
|
15
|
+
*
|
|
16
|
+
* Đợt 2 (30/10/2026): cây nghèo → host đọc chữ trên ảnh bằng OCR có sẵn của Windows (chạy trên máy), mỗi cụm chữ thành node `<snap>.t<k>`
|
|
17
|
+
* click / gõ được — BE tìm "nút Ghi sổ" theo chữ thay vì nhờ VLM đoán toạ độ; `gui.wait_for` chờ phần tử / cửa sổ hiện ra hoặc mất đi
|
|
18
|
+
* thay cho observe lặp.
|
|
19
|
+
*
|
|
20
|
+
* Sàn cứng trên máy (BE không đổi được): không gõ vào ô mật khẩu (host chặn), không điều khiển ứng dụng nhạy cảm (`BLOCKED_PROCESSES`),
|
|
21
|
+
* máy chỉ mở thư mục (không toàn quyền) thì không điều khiển cửa sổ dòng lệnh / registry — không lách vùng thư mục bằng cách gõ lệnh
|
|
22
|
+
* vào terminal; người dùng đang dùng chuột / phím → dừng (`GUI_USER_ACTIVE`).
|
|
23
|
+
*/
|
|
24
|
+
|
|
25
|
+
/** Tiến trình không bao giờ điều khiển: quản lý mật khẩu, hộp nâng quyền, bảo mật hệ thống, màn hình khoá. */
|
|
26
|
+
const BLOCKED_PROCESSES = new Set([
|
|
27
|
+
'consent', 'credentialuihost', 'credentialuibroker', 'lockapp', 'logonui', 'securityhealthsystray', 'securityhealthhost', 'windowsdefender', 'msmpeng',
|
|
28
|
+
'keepass', 'keepassxc', '1password', 'bitwarden', 'lastpass', 'dashlane', 'enpass', 'nordpass', 'roboform',
|
|
29
|
+
]);
|
|
30
|
+
/**
|
|
31
|
+
* Chỉ cho khi máy toàn quyền — điều khiển được những thứ này là chạy lệnh tuỳ ý ngoài vùng thư mục: terminal / registry, và (30/10/2026)
|
|
32
|
+
* trình soạn code có terminal tích hợp + ứng dụng agent tự chạy lệnh (VS Code, Cursor, Claude…) — gõ vào terminal của VS Code hay nhờ panel
|
|
33
|
+
* Claude chạy lệnh cũng là lách vùng thư mục như gõ vào cmd.
|
|
34
|
+
*/
|
|
35
|
+
const SHELL_PROCESSES = new Set([
|
|
36
|
+
'cmd', 'powershell', 'pwsh', 'windowsterminal', 'wt', 'openconsole', 'conhost', 'regedit', 'mmc', 'taskmgr', 'wsl', 'bash', 'mintty',
|
|
37
|
+
'code', 'code - insiders', 'codium', 'cursor', 'windsurf', 'zed', 'devenv', 'idea64', 'pycharm64', 'webstorm64', 'rider64', 'goland64',
|
|
38
|
+
'claude', 'chatgpt', 'warp', 'alacritty', 'wezterm-gui', 'hyper', 'tabby',
|
|
39
|
+
]);
|
|
40
|
+
/** Cùng nhóm đó theo tên trong menu Start (`gui.open_app` tìm theo tên, khác tên tiến trình) — chặn trước khi mở. */
|
|
41
|
+
const SHELL_APP_NAME = /\b(command prompt|powershell|terminal|registry editor|task manager|visual studio|vs ?code|cursor|windsurf|zed|intellij|pycharm|webstorm|rider|goland|claude|chatgpt|warp|alacritty|wezterm|hyper|tabby|wsl|ubuntu|git bash)\b/i;
|
|
42
|
+
/** Không mở tệp có đuôi chạy được bằng `gui.open_app` (mở = chạy chương trình). */
|
|
43
|
+
const EXECUTABLE_EXT = /\.(exe|com|bat|cmd|ps1|psm1|vbs|vbe|js|jse|wsf|wsh|msi|msp|lnk|scr|pif|hta|cpl|jar|reg|url|appref-ms|application)$/i;
|
|
44
|
+
|
|
45
|
+
const OBSERVE_MAX_NODES = 300;
|
|
46
|
+
const APPS_CACHE_MS = 10 * 60_000;
|
|
47
|
+
const OPEN_WAIT_MS = 10_000;
|
|
48
|
+
const WAIT_MAX_MS = 60_000;
|
|
49
|
+
const FIND_DEFAULT = 20;
|
|
50
|
+
const FIND_MAX = 60;
|
|
51
|
+
const SEMANTIC_CHOICES = 5;
|
|
52
|
+
/** Báo người dùng "AI đang điều khiển" một lần mỗi quãng này (lần thao tác ghi đầu tiên). */
|
|
53
|
+
const NOTIFY_EVERY_MS = 5 * 60_000;
|
|
54
|
+
/** Không hỏi người dùng (10/11/2026, user: "xin quyền gì lắt nhắt thế"): cần chuột / phím thật thì chờ họ ngừng tay chừng này rồi mượn thật nhanh. */
|
|
55
|
+
export const REAL_INPUT_IDLE_MS = 2500;
|
|
56
|
+
/** Họ bận liên tục quá chừng này thì thôi, báo Planner để nói trong khung chat. */
|
|
57
|
+
export const REAL_INPUT_WAIT_MS = 30_000;
|
|
58
|
+
const REAL_INPUT_POLL_MS = 400;
|
|
59
|
+
const GUI_PERSON_PRESENT = 'GUI_PERSON_PRESENT';
|
|
60
|
+
|
|
61
|
+
const str = (description) => ({ type: 'string', description });
|
|
62
|
+
const num = (description) => ({ type: 'number', description });
|
|
63
|
+
const bool = (description) => ({ type: 'boolean', description });
|
|
64
|
+
const schema = (properties, required = []) => ({ type: 'object', properties, required });
|
|
65
|
+
|
|
66
|
+
export const GuiAction = Object.freeze({
|
|
67
|
+
CLICK: 'click', DOUBLE_CLICK: 'double_click', RIGHT_CLICK: 'right_click', SET_VALUE: 'set_value', TYPE: 'type', KEY: 'key',
|
|
68
|
+
SCROLL: 'scroll', SELECT: 'select', TOGGLE: 'toggle', EXPAND: 'expand', COLLAPSE: 'collapse', DRAG: 'drag',
|
|
69
|
+
});
|
|
70
|
+
|
|
71
|
+
/** Năng lực GUI khai trong hồ sơ máy. Chỉ Windows ở đợt này; máy tính tổ chức (nhiều người chung) không có màn hình. */
|
|
72
|
+
export function detectGui({ disabled = false, multiUser = false, platform = process.platform } = {}) {
|
|
73
|
+
if (disabled || multiUser || platform !== 'win32') return null;
|
|
74
|
+
// Phiên 0 (dịch vụ) không có màn hình tương tác.
|
|
75
|
+
if (process.env.SESSIONNAME === 'Services') return null;
|
|
76
|
+
return { backend: 'uia', actions: Object.values(GuiAction) };
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
const normalizeProcess = (name) => String(name || '').toLowerCase().replace(/\.exe$/, '');
|
|
80
|
+
|
|
81
|
+
/** PickerHost còn mở các hộp chọn tệp bình thường, nên chỉ chặn đúng hộp xác thực "Windows Security" của nó. */
|
|
82
|
+
function isWindowsSecurityPrompt(windowInfo) {
|
|
83
|
+
if (normalizeProcess(windowInfo?.process) !== 'pickerhost') return false;
|
|
84
|
+
const title = normalizeName(windowInfo?.title);
|
|
85
|
+
return title === 'windows security' || title === 'bao mat windows';
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/** Ứng dụng này có được điều khiển không — ném lỗi nếu bị chặn. */
|
|
89
|
+
export function assertWindowAllowed(windowInfo, { fullAccess }) {
|
|
90
|
+
if (isWindowsSecurityPrompt(windowInfo)) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, 'This is a Windows Security prompt — only the person at this computer can answer it');
|
|
91
|
+
// Hộp xác nhận / đồng ý của chính Aivin: chỉ người ở máy trả lời — AI bấm "Cho phép" là tự duyệt việc của mình (humanInput.mjs).
|
|
92
|
+
if (isProtectedPromptWindow(windowInfo?.title)) {
|
|
93
|
+
throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, 'This is an Aivin confirmation box — only the person at this computer can answer it');
|
|
94
|
+
}
|
|
95
|
+
const proc = normalizeProcess(windowInfo?.process);
|
|
96
|
+
if (!proc) return;
|
|
97
|
+
if (BLOCKED_PROCESSES.has(proc)) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Controlling "${windowInfo.process}" is not allowed on this device`);
|
|
98
|
+
if (!fullAccess && SHELL_PROCESSES.has(proc)) {
|
|
99
|
+
throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Controlling "${windowInfo.process}" needs full device access (aivin remote start --full-access)`);
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** Ứng dụng này (tên trong menu Start) có được mở không — ném lỗi trước khi mở. */
|
|
104
|
+
export function assertAppAllowed(name, { fullAccess }) {
|
|
105
|
+
if (BLOCKED_PROCESSES.has(normalizeProcess(String(name || '').replace(/\s+/g, '')))) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Opening "${name}" is not allowed`);
|
|
106
|
+
if (!fullAccess && SHELL_APP_NAME.test(String(name || ''))) {
|
|
107
|
+
throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Opening "${name}" needs full device access (aivin remote start --full-access)`);
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
const normalizeName = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/gi, 'd').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Rank UI nodes with richer evidence while keeping the model-facing schema small. Hard exclusions happen
|
|
115
|
+
* before scoring; exact accessible names and AutomationIds beat loose word matches. The margin between the
|
|
116
|
+
* first two candidates is used by gui.do to refuse ambiguous actions instead of guessing.
|
|
117
|
+
*/
|
|
118
|
+
export function rankGuiNodes(nodes, query, role = '', { matchValue = true } = {}) {
|
|
119
|
+
const q = normalizeName(query);
|
|
120
|
+
const words = q.split(' ').filter(Boolean);
|
|
121
|
+
const wantedRole = String(role || '').toLowerCase();
|
|
122
|
+
if (!words.length) return [];
|
|
123
|
+
// Chữ OCR nằm trên một phần tử đã tắt cũng là đã tắt: bấm vào đó không có tác dụng mà vẫn báo thành công.
|
|
124
|
+
const disabledRects = (nodes || []).filter((n) => n.disabled && n.rect).map((n) => n.rect);
|
|
125
|
+
const onDisabled = (n) => n.source === 'ocr' && n.rect && disabledRects.some((r) => {
|
|
126
|
+
const cx = n.rect.x + n.rect.w / 2;
|
|
127
|
+
const cy = n.rect.y + n.rect.h / 2;
|
|
128
|
+
return cx >= r.x && cx <= r.x + r.w && cy >= r.y && cy <= r.y + r.h;
|
|
129
|
+
});
|
|
130
|
+
return (nodes || [])
|
|
131
|
+
.filter((n) => (!wantedRole || String(n.role || '').toLowerCase() === wantedRole || n.source === 'ocr') && !n.disabled && !n.offscreen && !onDisabled(n))
|
|
132
|
+
.map((node, order) => {
|
|
133
|
+
const name = normalizeName(node.name);
|
|
134
|
+
const aid = normalizeName(node.automation_id);
|
|
135
|
+
const value = matchValue ? normalizeName(node.value) : '';
|
|
136
|
+
const help = normalizeName(node.help);
|
|
137
|
+
const combined = [name, aid, value, help].filter(Boolean).join(' ');
|
|
138
|
+
// Khớp theo đầu từ; chỉ từ đủ dài mới được khớp giữa chuỗi (AutomationId dính liền) — "ton" (tồn) không được khớp "TogglePaneButton".
|
|
139
|
+
const tokens = combined.split(' ');
|
|
140
|
+
const hits = words.filter((word) => tokens.some((token) => token.startsWith(word)) || (word.length >= 4 && combined.includes(word))).length;
|
|
141
|
+
if (!hits) return null;
|
|
142
|
+
let score = Math.round((hits / words.length) * 50);
|
|
143
|
+
const evidence = [];
|
|
144
|
+
if (name === q) { score += 50; evidence.push('exact_name'); }
|
|
145
|
+
else if (aid === q) { score += 45; evidence.push('exact_automation_id'); }
|
|
146
|
+
else if (name.startsWith(q)) { score += 35; evidence.push('name_prefix'); }
|
|
147
|
+
else if (words.every((word) => name.includes(word))) { score += 30; evidence.push('all_words_in_name'); }
|
|
148
|
+
else if (words.every((word) => combined.includes(word))) { score += 20; evidence.push('all_words'); }
|
|
149
|
+
if (node.source === 'ocr') { score -= 5; evidence.push('ocr'); }
|
|
150
|
+
if (node.patterns?.length) { score += 3; evidence.push('actionable_pattern'); }
|
|
151
|
+
return { node, score, hits, evidence, order };
|
|
152
|
+
})
|
|
153
|
+
.filter(Boolean)
|
|
154
|
+
.sort((a, b) => b.score - a.score || b.hits - a.hits || a.order - b.order);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Nhãn nút chốt / phá huỷ (đã bỏ dấu, viết thường). Cổng duyệt trên BE xét câu mô tả, nên khi máy tự chọn phần tử có nhãn kiểu này mà câu
|
|
159
|
+
* mô tả không nói tới (vd "Lưu" khớp tiền tố "Lưu và gửi") thì không bấm thẳng — trả mơ hồ để BE phân giải + xét sàn an toàn trên đúng nút.
|
|
160
|
+
*/
|
|
161
|
+
const RISKY_LABEL_WORDS = new Set([
|
|
162
|
+
'send', 'submit', 'post', 'publish', 'delete', 'remove', 'erase', 'pay', 'purchase', 'buy', 'order', 'confirm', 'approve', 'transfer', 'logout', 'signout',
|
|
163
|
+
'gui', 'dang', 'xoa', 'go', 'huy', 'mua', 'chuyen', 'duyet',
|
|
164
|
+
]);
|
|
165
|
+
const RISKY_LABEL_PHRASES = ['sign out', 'log out', 'thanh toan', 'xac nhan', 'dang xuat', 'dat hang', 'chuyen tien', 'go bo'];
|
|
166
|
+
|
|
167
|
+
export function riskyLabelWords(label) {
|
|
168
|
+
const n = normalizeName(label);
|
|
169
|
+
const words = n.split(' ').filter((w) => RISKY_LABEL_WORDS.has(w));
|
|
170
|
+
return [...words, ...RISKY_LABEL_PHRASES.filter((p) => ` ${n} `.includes(` ${p} `))];
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
/** Phần tử đã chọn mang nhãn chốt / phá huỷ mà câu mô tả không có → không bấm thẳng. */
|
|
174
|
+
export function needsServerCheck(query, node) {
|
|
175
|
+
const asked = new Set(riskyLabelWords(query));
|
|
176
|
+
return riskyLabelWords(node?.name || node?.automation_id).some((w) => !asked.has(w));
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** Chọn ứng dụng theo tên: trùng hẳn > bắt đầu bằng > chứa. Nhiều ứng viên ngang nhau → trả danh sách để Planner chọn lại. */
|
|
180
|
+
export function matchApps(apps, query) {
|
|
181
|
+
const q = normalizeName(query);
|
|
182
|
+
if (!q) return [];
|
|
183
|
+
const scored = apps.map((app) => {
|
|
184
|
+
const n = normalizeName(app.name);
|
|
185
|
+
const score = n === q ? 3 : n.startsWith(q) ? 2 : n.includes(q) ? 1 : 0;
|
|
186
|
+
return { app, score };
|
|
187
|
+
}).filter((x) => x.score > 0).sort((a, b) => b.score - a.score || a.app.name.length - b.app.name.length);
|
|
188
|
+
if (!scored.length) return [];
|
|
189
|
+
const top = scored[0].score;
|
|
190
|
+
return scored.filter((x) => x.score === top).map((x) => x.app);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
function runPowerShellJson(script, signal) {
|
|
194
|
+
return new Promise((resolve, reject) => {
|
|
195
|
+
// Đầu ra UTF-8: tên cửa sổ / ứng dụng tiếng Việt không thành `?` (PowerShell không console ghi theo bảng mã OEM).
|
|
196
|
+
const c = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `${PS_UTF8_PREFIX}${script}`], { windowsHide: true });
|
|
197
|
+
const chunks = [];
|
|
198
|
+
c.stdout.on('data', (d) => { chunks.push(d); });
|
|
199
|
+
const onAbort = () => { try { c.kill(); } catch { /* đã thoát */ } };
|
|
200
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
201
|
+
c.on('error', (e) => reject(e));
|
|
202
|
+
c.on('close', () => {
|
|
203
|
+
signal?.removeEventListener('abort', onAbort);
|
|
204
|
+
const out = Buffer.concat(chunks).toString('utf8');
|
|
205
|
+
try { const v = JSON.parse(out || 'null'); resolve(Array.isArray(v) ? v : v ? [v] : []); } catch (e) { reject(e); }
|
|
206
|
+
});
|
|
207
|
+
});
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/**
|
|
211
|
+
* Bộ điều khiển GUI của máy. `env.fullAccess` quyết định có cho điều khiển terminal không. `host` truyền vào được (test dùng host giả).
|
|
212
|
+
*/
|
|
213
|
+
export function createGuiController({
|
|
214
|
+
fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true, defaultWindow = () => null, realInputIdleMs = REAL_INPUT_IDLE_MS, realInputWaitMs = REAL_INPUT_WAIT_MS, fetchApps = (signal) => runPowerShellJson('Get-StartApps | Select-Object Name, AppID | ConvertTo-Json -Compress', signal),
|
|
215
|
+
} = {}) {
|
|
216
|
+
let appsCache = null;
|
|
217
|
+
let appsInflight = null;
|
|
218
|
+
let lastNotifyAt = 0;
|
|
219
|
+
/** Cửa sổ của từng lần observe — để kiểm ứng dụng bị chặn ở thao tác theo node_id. */
|
|
220
|
+
const snapshotWindows = new Map();
|
|
221
|
+
|
|
222
|
+
/**
|
|
223
|
+
* Thao tác chạy dưới nền thì đi thẳng. Host chỉ báo GUI_PERSON_PRESENT ngay trước lần đầu đụng chuột / phím thật, lúc chưa làm gì, nên thử lại
|
|
224
|
+
* là an toàn: chờ người dùng ngừng tay. Họ bận suốt → GUI_USER_ACTIVE, không có hộp hỏi nào.
|
|
225
|
+
*/
|
|
226
|
+
async function whenPersonPauses(ctx, run) {
|
|
227
|
+
const deadline = Date.now() + Math.min(realInputWaitMs, (ctx?.timeoutMs || Infinity) / 2);
|
|
228
|
+
for (;;) {
|
|
229
|
+
try {
|
|
230
|
+
return await run(realInputIdleMs);
|
|
231
|
+
} catch (e) {
|
|
232
|
+
if (e?.code !== GUI_PERSON_PRESENT) throw e;
|
|
233
|
+
if (ctx?.signal?.aborted) throw ctx.signal.reason;
|
|
234
|
+
if (Date.now() + REAL_INPUT_POLL_MS >= deadline) throw new DeviceToolError(DeviceErrorCode.GUI_USER_ACTIVE, 'The person at this computer kept using it and this step needs the real mouse/keyboard — nothing was done. Tell them in the chat so they can do this step themselves or pause for a few seconds');
|
|
235
|
+
await new Promise((r) => setTimeout(r, REAL_INPUT_POLL_MS));
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
const announce = (windowInfo) => {
|
|
241
|
+
const now = Date.now();
|
|
242
|
+
if (now - lastNotifyAt < NOTIFY_EVERY_MS) return;
|
|
243
|
+
lastNotifyAt = now;
|
|
244
|
+
say(`🖱 AI đang điều khiển ${windowInfo?.process || 'màn hình'} — di chuột hoặc gõ phím để AI dừng lại.`);
|
|
245
|
+
notify({ title: 'Aivin đang điều khiển máy này', body: `AI đang thao tác trên ${windowInfo?.title || windowInfo?.process || 'màn hình'}. Di chuột hoặc gõ phím để AI dừng và hỏi bạn.` });
|
|
246
|
+
};
|
|
247
|
+
|
|
248
|
+
async function windows(args, ctx) {
|
|
249
|
+
const list = await host.call('windows', { all: !!args.include_dialogs }, ctx);
|
|
250
|
+
return { windows: list.map((w) => ({ ...w, blocked: BLOCKED_PROCESSES.has(normalizeProcess(w.process)) || (!fullAccess && SHELL_PROCESSES.has(normalizeProcess(w.process))) || isProtectedPromptWindow(w.title) || isWindowsSecurityPrompt(w) || undefined })) };
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
/**
|
|
254
|
+
* Không nói cửa sổ = cửa sổ đang focus; nhưng chủ máy vừa gõ vào ô hỏi của linh vật thì focus là chính linh vật → host đổi sang cửa sổ họ
|
|
255
|
+
* đang dùng ngay trước đó (`defaultWindow()` = `{ avoid_pid, fallback }`).
|
|
256
|
+
*/
|
|
257
|
+
const target = (args) => (args.window ? { window: args.window } : { ...defaultWindow() });
|
|
258
|
+
const windowInfoOf = (args, ctx) => host.call('window_info', target(args), ctx);
|
|
259
|
+
/**
|
|
260
|
+
* Thao tác có thay đổi mà không nêu cửa sổ (02/11/2026): không lấy cửa sổ đang focus — người dùng có thể vừa chuyển sang cửa sổ khác. Chỉ
|
|
261
|
+
* cho khi hỏi từ linh vật (có cửa sổ chủ máy dùng ngay trước đó); host kiểm lại đúng lúc thao tác (linh vật có đang được focus không).
|
|
262
|
+
*/
|
|
263
|
+
const assertWindowNamed = (windowArg) => {
|
|
264
|
+
if (windowArg || defaultWindow()?.fallback) return;
|
|
265
|
+
throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Name the window for this action (window / within: a handle 0x… or a title/process from gui.windows) — input is never sent to whatever window happens to be focused');
|
|
266
|
+
};
|
|
267
|
+
|
|
268
|
+
async function observe(args, ctx) {
|
|
269
|
+
const res = await host.call('observe', {
|
|
270
|
+
...target(args),
|
|
271
|
+
max_nodes: Math.min(Number(args.max_nodes) || OBSERVE_MAX_NODES, 1500),
|
|
272
|
+
include_image: !!args.include_image,
|
|
273
|
+
image_when_poor: args.image_when_poor !== false,
|
|
274
|
+
ocr: typeof args.ocr === 'boolean' ? args.ocr : undefined,
|
|
275
|
+
image_max_width: Number(args.image_max_width) || 1366,
|
|
276
|
+
image_quality: Number(args.image_quality) || 70,
|
|
277
|
+
budget_ms: Number(args.budget_ms) || undefined,
|
|
278
|
+
}, ctx);
|
|
279
|
+
assertWindowAllowed(res.window, { fullAccess });
|
|
280
|
+
snapshotWindows.set(String(res.snapshot), res.window);
|
|
281
|
+
if (snapshotWindows.size > 20) snapshotWindows.delete(snapshotWindows.keys().next().value);
|
|
282
|
+
return res;
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Chỉ những phần tử khớp chữ cần tìm (cửa sổ lớn: Excel, ERP có hàng trăm phần tử) — đi cả cây (tới 1500) rồi lọc ở đây; id vẫn của lần
|
|
287
|
+
* observe đó nên `gui.act` dùng được ngay. Mọi từ đều có trong tên / AutomationId / giá trị / chú thích (bỏ dấu); không phần tử nào đủ
|
|
288
|
+
* hết từ thì lấy phần tử khớp nhiều từ nhất.
|
|
289
|
+
*/
|
|
290
|
+
async function find(args, ctx) {
|
|
291
|
+
const words = normalizeName(args.query).split(' ').filter(Boolean);
|
|
292
|
+
if (!words.length) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give query (words of the element to find)');
|
|
293
|
+
const role = String(args.role || '').toLowerCase();
|
|
294
|
+
const max = Math.max(1, Math.min(Number(args.max) || FIND_DEFAULT, FIND_MAX));
|
|
295
|
+
const res = await observe({ ...args, max_nodes: 1500, budget_ms: 10_000 }, ctx);
|
|
296
|
+
// gui.do chọn phần tử để BẤM: không tính nội dung ô — chữ trên màn hình (thư, trang web) không được lái việc chọn nút (02/11/2026).
|
|
297
|
+
const scored = rankGuiNodes(res.nodes, args.query, role, { matchValue: args.match_value !== false });
|
|
298
|
+
const all = scored.filter((x) => x.hits === words.length);
|
|
299
|
+
const pool = all.length ? all : scored.filter((x) => x.hits === scored[0]?.hits);
|
|
300
|
+
const picked = pool.slice(0, max);
|
|
301
|
+
const margin = picked.length > 1 ? picked[0].score - picked[1].score : picked.length ? picked[0].score : 0;
|
|
302
|
+
const out = { ...res, nodes: picked.map((x) => x.node), query: String(args.query), matched: all.length || scored.length, exact: all.length > 0, confidence: !picked.length ? 'none' : margin >= 15 || picked.length === 1 ? 'high' : margin >= 5 ? 'medium' : 'low', ambiguous: picked.length > 1 && margin < 5 || undefined };
|
|
303
|
+
Object.defineProperty(out, '_raw_observation', { value: res, enumerable: false });
|
|
304
|
+
return out;
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
/**
|
|
308
|
+
* Compact semantic fast path. The caller states intent; candidate evidence, exclusions, ambiguity handling,
|
|
309
|
+
* execution and cheap post-action verification stay inside the device runtime.
|
|
310
|
+
*/
|
|
311
|
+
async function semanticDo(args, ctx, env) {
|
|
312
|
+
const command = String(args.do || '').toLowerCase();
|
|
313
|
+
if (command === 'open') return openApp({ name: args.target, file: args.file }, ctx, env);
|
|
314
|
+
const action = {
|
|
315
|
+
click: GuiAction.CLICK, fill: GuiAction.SET_VALUE, select: GuiAction.SELECT, toggle: GuiAction.TOGGLE,
|
|
316
|
+
key: GuiAction.KEY, scroll: GuiAction.SCROLL,
|
|
317
|
+
}[command];
|
|
318
|
+
if (!action) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Unknown semantic action: ${args.do || ''}`);
|
|
319
|
+
assertWindowNamed(args.within || args.window);
|
|
320
|
+
|
|
321
|
+
if ((command === 'key' || command === 'scroll') && !args.target) {
|
|
322
|
+
const result = await act({
|
|
323
|
+
action, window: args.within || args.window, keys: command === 'key' ? args.value : undefined,
|
|
324
|
+
direction: command === 'scroll' ? args.value : undefined,
|
|
325
|
+
}, ctx);
|
|
326
|
+
return { ok: true, action: command, effect: result.window_title_changed || result.focused_element || command };
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
const query = String(args.target || '').trim();
|
|
330
|
+
if (!query) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give target');
|
|
331
|
+
let found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, match_value: false }, ctx);
|
|
332
|
+
if ((!found.nodes.length || !found.exact) && !found.ocr && found.tree_quality !== 'poor') {
|
|
333
|
+
const viaOcr = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, match_value: false, ocr: true }, ctx);
|
|
334
|
+
if (viaOcr.nodes.length && (viaOcr.exact || !found.nodes.length)) found = viaOcr;
|
|
335
|
+
}
|
|
336
|
+
if (!found.nodes.length) throw new DeviceToolError(DeviceErrorCode.GUI_TARGET_NOT_FOUND, `No enabled visible target matched "${query}"`);
|
|
337
|
+
// Khớp một phần (không phần tử nào có đủ mọi từ) cũng là không chắc: chỉ trả ứng viên để BE phân giải, không bấm thẳng.
|
|
338
|
+
if (found.ambiguous || !found.exact) {
|
|
339
|
+
return {
|
|
340
|
+
ok: false, code: DeviceErrorCode.GUI_AMBIGUOUS_TARGET,
|
|
341
|
+
choices: found.nodes.map((n) => ({ ref: n.id, label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — ') })),
|
|
342
|
+
observation: found._raw_observation,
|
|
343
|
+
};
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
const node = found.nodes[0];
|
|
347
|
+
if (command !== 'fill' && needsServerCheck(query, node)) {
|
|
348
|
+
return {
|
|
349
|
+
ok: false, code: DeviceErrorCode.GUI_AMBIGUOUS_TARGET,
|
|
350
|
+
choices: found.nodes.map((n) => ({ ref: n.id, label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — ') })),
|
|
351
|
+
observation: found._raw_observation,
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
if (command === 'fill' && node.password) {
|
|
355
|
+
throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'AI may not fill password or secret fields — ask the user to enter it');
|
|
356
|
+
}
|
|
357
|
+
const result = await act({
|
|
358
|
+
action, node_id: node.id,
|
|
359
|
+
text: command === 'fill' ? args.value : undefined,
|
|
360
|
+
option: command === 'select' ? args.value : undefined,
|
|
361
|
+
state: command === 'toggle' ? args.value : undefined,
|
|
362
|
+
}, ctx);
|
|
363
|
+
let verified;
|
|
364
|
+
if (command === 'fill' && Object.hasOwn(result.target || {}, 'value')) verified = String(result.target.value) === String(args.value ?? '');
|
|
365
|
+
if (command === 'select' && Object.hasOwn(result.target || {}, 'selected')) verified = result.target.selected === true;
|
|
366
|
+
if (command === 'toggle' && Object.hasOwn(result.target || {}, 'checked')) {
|
|
367
|
+
const expected = String(args.value || '').toLowerCase();
|
|
368
|
+
verified = expected === 'on' ? result.target.checked === 'on' : expected === 'off' ? result.target.checked === 'off' : undefined;
|
|
369
|
+
}
|
|
370
|
+
if (verified === false) {
|
|
371
|
+
throw new DeviceToolError(DeviceErrorCode.GUI_NO_EFFECT, `${command} ran but the target did not reach the requested state`);
|
|
372
|
+
}
|
|
373
|
+
return {
|
|
374
|
+
ok: true, action: command, target: node.name || node.automation_id || node.role,
|
|
375
|
+
...(verified === undefined ? {} : { verified }),
|
|
376
|
+
...(result.screen_point ? { screen_point: result.screen_point } : {}),
|
|
377
|
+
...(result.app_busy ? { app_busy: true } : {}),
|
|
378
|
+
method: result.method,
|
|
379
|
+
window_class: result.window_class,
|
|
380
|
+
effect: result.window_title_changed || result.target || result.focused_element || command,
|
|
381
|
+
};
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** Chờ phần tử / cửa sổ hiện ra hoặc mất đi — chỉ đọc. Chờ trong một cửa sổ thì cửa sổ đó phải được phép điều khiển. */
|
|
385
|
+
async function waitFor(args, ctx) {
|
|
386
|
+
const elementWait = !!(args.name || args.automation_id);
|
|
387
|
+
if (elementWait || args.window) assertWindowAllowed(await windowInfoOf(args, ctx), { fullAccess });
|
|
388
|
+
return host.call('wait_for', {
|
|
389
|
+
...(elementWait || args.window ? target(args) : {}),
|
|
390
|
+
until: args.until, name: args.name, automation_id: args.automation_id, role: args.role, title_contains: args.title_contains,
|
|
391
|
+
timeout_ms: Math.min(Number(args.timeout_ms) || 10_000, WAIT_MAX_MS),
|
|
392
|
+
}, ctx);
|
|
393
|
+
}
|
|
394
|
+
|
|
395
|
+
async function focus(args, ctx) {
|
|
396
|
+
const windowInfo = await windowInfoOf(args, ctx);
|
|
397
|
+
assertWindowAllowed(windowInfo, { fullAccess });
|
|
398
|
+
return whenPersonPauses(ctx, (grace) => host.call('focus', { ...target(args), check_user_input: true, user_input_grace_ms: grace }, ctx));
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
async function act(args, ctx) {
|
|
402
|
+
const action = String(args.action || GuiAction.CLICK);
|
|
403
|
+
if (!Object.values(GuiAction).includes(action)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Unknown action: ${action}`);
|
|
404
|
+
const snap = args.node_id ? String(args.node_id).split('.')[0] : null;
|
|
405
|
+
// node_id đã chỉ đúng phần tử của một lần observe (kèm cửa sổ của nó) — chỉ thao tác không node_id mới phải nêu cửa sổ.
|
|
406
|
+
if (!snap) assertWindowNamed(args.window);
|
|
407
|
+
const windowInfo = snap ? snapshotWindows.get(snap) : await windowInfoOf(args, ctx);
|
|
408
|
+
if (snap && !windowInfo) throw new DeviceToolError(DeviceErrorCode.GUI_STALE_NODE, `Node ${args.node_id} is from an old observation — observe again`);
|
|
409
|
+
assertWindowAllowed(windowInfo, { fullAccess });
|
|
410
|
+
announce(windowInfo);
|
|
411
|
+
return whenPersonPauses(ctx, (grace) => host.call('act', {
|
|
412
|
+
action, node_id: args.node_id, ...(args.node_id ? {} : target(args)), method: args.method, text: args.text, keys: args.keys,
|
|
413
|
+
option: args.option, state: args.state, direction: args.direction, amount: args.amount, point: args.point, to: args.to,
|
|
414
|
+
image_scale: args.image_scale, settle_ms: args.settle_ms,
|
|
415
|
+
// Planner chỉ được xin chờ lâu hơn, không được rút ngắn: rút ngắn là tự cho phép lấy chuột của người đang dùng máy.
|
|
416
|
+
check_user_input: true, user_input_grace_ms: Math.max(grace, Number(args.user_input_grace_ms) || 0),
|
|
417
|
+
}, ctx));
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** Đọc cả bảng dưới nền: host tự cuộn, gộp các dòng rồi cuộn về chỗ cũ. */
|
|
421
|
+
async function readTable(args, ctx) {
|
|
422
|
+
const snap = args.node_id ? String(args.node_id).split('.')[0] : null;
|
|
423
|
+
if (!snap || String(args.node_id).includes('.t')) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give node_id of the table (from gui.observe or gui.find)');
|
|
424
|
+
const windowInfo = snapshotWindows.get(snap);
|
|
425
|
+
if (!windowInfo) throw new DeviceToolError(DeviceErrorCode.GUI_STALE_NODE, `Node ${args.node_id} is from an old observation — observe again`);
|
|
426
|
+
assertWindowAllowed(windowInfo, { fullAccess });
|
|
427
|
+
return host.call('read_table', { node_id: args.node_id, max_rows: Math.max(1, Math.min(Number(args.max_rows) || 300, 2000)) }, ctx);
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
async function listApps(signal) {
|
|
431
|
+
if (appsCache && Date.now() - appsCache.at < APPS_CACHE_MS) return appsCache.apps;
|
|
432
|
+
if (appsInflight && !signal) return appsInflight;
|
|
433
|
+
const task = Promise.resolve().then(() => fetchApps(signal)).catch(() => []).then((rows) => {
|
|
434
|
+
const apps = (rows || []).filter((r) => r?.Name && r?.AppID).map((r) => ({ name: String(r.Name), app_id: String(r.AppID) }));
|
|
435
|
+
if (apps.length) appsCache = { at: Date.now(), apps };
|
|
436
|
+
return apps.length ? apps : (appsCache?.apps || []);
|
|
437
|
+
}).finally(() => { if (appsInflight === task) appsInflight = null; });
|
|
438
|
+
if (!signal) appsInflight = task;
|
|
439
|
+
return task;
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
async function waitNewWindow(before, ctx, hint) {
|
|
443
|
+
const known = new Set(before.map((w) => w.window));
|
|
444
|
+
const deadline = Date.now() + OPEN_WAIT_MS;
|
|
445
|
+
while (Date.now() < deadline) {
|
|
446
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
447
|
+
if (ctx.signal?.aborted) throw ctx.signal.reason;
|
|
448
|
+
const now = await host.call('windows', {}, ctx);
|
|
449
|
+
const fresh = now.filter((w) => !known.has(w.window));
|
|
450
|
+
const pick = fresh.find((w) => hint && normalizeName(`${w.title} ${w.process}`).includes(normalizeName(hint).split(' ')[0])) || fresh[0];
|
|
451
|
+
if (pick) return pick;
|
|
452
|
+
}
|
|
453
|
+
return null;
|
|
454
|
+
}
|
|
455
|
+
|
|
456
|
+
/** Cửa sổ đang ở trên cùng trước khi mở ứng dụng, kể cả loại không có trong gui.windows (hộp hệ thống, cửa sổ công cụ). */
|
|
457
|
+
const currentForeground = (ctx) => host.call('window_info', {}, ctx).then((w) => w?.window).catch(() => undefined);
|
|
458
|
+
|
|
459
|
+
/**
|
|
460
|
+
* Cửa sổ AI vừa mở được Windows đưa lên trước → đẩy xuống dưới, trả focus cho cửa sổ người dùng đang dùng (chạy nền). Ứng dụng thường tự
|
|
461
|
+
* kích hoạt lại ngay sau khi cửa sổ hiện ra, nên làm thêm vài lượt ngắn; host chỉ trả focus khi nó vẫn đang ở ứng dụng vừa mở.
|
|
462
|
+
*/
|
|
463
|
+
async function sendToBack(win, userWindow, ctx) {
|
|
464
|
+
if (!win || background === false) return;
|
|
465
|
+
for (const [i, wait] of [0, 350, 600].entries()) {
|
|
466
|
+
if (wait) await new Promise((r) => setTimeout(r, wait));
|
|
467
|
+
if (ctx.signal?.aborted) return;
|
|
468
|
+
await host.call('to_back', { window: win.window, restore_to: userWindow, wait_content: i === 0 }, ctx).catch(() => undefined);
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
/** Đưa cửa sổ mới xuống nền; cửa sổ đầu tiên đôi khi chỉ là màn hình chờ đã đóng (Sticky Notes) → trả cửa sổ thật thay vì handle đã chết. */
|
|
473
|
+
async function settleNewWindow(win, before, userWindow, hint, ctx) {
|
|
474
|
+
if (!win) return win;
|
|
475
|
+
await sendToBack(win, userWindow, ctx);
|
|
476
|
+
const alive = await host.call('window_info', { window: win.window }, ctx).then(() => true).catch(() => false);
|
|
477
|
+
if (alive) return win;
|
|
478
|
+
const next = await waitNewWindow(before, ctx, hint);
|
|
479
|
+
await sendToBack(next, userWindow, ctx);
|
|
480
|
+
return next;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
/** Mở ứng dụng theo tên trong danh sách Start, hoặc mở một tệp trong vùng được phép bằng ứng dụng mặc định. Không chạy lệnh tuỳ ý. */
|
|
484
|
+
async function openApp(args, ctx, env) {
|
|
485
|
+
const before = await host.call('windows', {}, ctx);
|
|
486
|
+
const userWindow = await currentForeground(ctx);
|
|
487
|
+
if (args.file) {
|
|
488
|
+
const abs = resolveInRoots(env.roots, String(args.file));
|
|
489
|
+
if (EXECUTABLE_EXT.test(abs)) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, 'Opening programs or scripts is not allowed — use an app name, or shell.exec');
|
|
490
|
+
if (!fs.existsSync(abs)) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `File not found: ${args.file}`);
|
|
491
|
+
spawn('explorer.exe', [abs], { windowsHide: true, detached: true, stdio: 'ignore' }).unref();
|
|
492
|
+
const win = await settleNewWindow(await waitNewWindow(before, ctx, path.basename(abs, path.extname(abs))), before, userWindow, path.basename(abs, path.extname(abs)), ctx);
|
|
493
|
+
return { opened: path.basename(abs), window: win, hint: win ? undefined : 'No new window appeared — the file may have opened in an existing window, or Windows has no working default app for this file type; check gui.windows, or open the app by name' };
|
|
494
|
+
}
|
|
495
|
+
const name = String(args.name || '').trim();
|
|
496
|
+
if (!name) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give name (an installed app) or file');
|
|
497
|
+
const matches = matchApps(await listApps(ctx.signal), name);
|
|
498
|
+
if (!matches.length) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No installed app named "${name}"`);
|
|
499
|
+
if (matches.length > 1 && !args.first) return { ambiguous: true, candidates: matches.slice(0, 10).map((m) => m.name), hint: 'Call again with the exact name' };
|
|
500
|
+
const app = matches[0];
|
|
501
|
+
assertAppAllowed(app.name, { fullAccess });
|
|
502
|
+
spawn('explorer.exe', [`shell:AppsFolder\\${app.app_id}`], { windowsHide: true, detached: true, stdio: 'ignore' }).unref();
|
|
503
|
+
const win = await settleNewWindow(await waitNewWindow(before, ctx, app.name), before, userWindow, app.name, ctx);
|
|
504
|
+
if (win) assertWindowAllowed(win, { fullAccess });
|
|
505
|
+
return { opened: app.name, window: win, hint: win ? undefined : 'App started but no new window yet — call gui.windows in a moment' };
|
|
506
|
+
}
|
|
507
|
+
|
|
508
|
+
return { windows, observe, find, waitFor, focus, act, readTable, semanticDo, openApp, prewarm: () => listApps(), close: () => host.close() };
|
|
509
|
+
}
|
|
510
|
+
|
|
511
|
+
/** Công cụ GUI cho danh mục của Planner. */
|
|
512
|
+
export function buildGuiTools(gui) {
|
|
513
|
+
const target = {
|
|
514
|
+
node_id: str('target element id from the latest gui.observe (preferred)'),
|
|
515
|
+
window: str('window handle (0x…) or a title/process to match; reading defaults to the focused window, but an action without node_id must name it (asked from the mascot: the window the person was using)'),
|
|
516
|
+
};
|
|
517
|
+
return [
|
|
518
|
+
{ name: 'gui.do', group: ToolGroup.GUI, handler: (a, c, e) => gui.semanticDo(a, c, e),
|
|
519
|
+
description: 'Fast semantic desktop action. State the intent briefly; the device finds one enabled visible target, refuses ambiguity, acts, and verifies simple value/state changes. Use precise gui.find/gui.act only after an ambiguous result.',
|
|
520
|
+
input_schema: schema({
|
|
521
|
+
do: str('click | fill | select | toggle | key | scroll | open'), target: str('short visible label or app name'),
|
|
522
|
+
value: str('text, option, on/off, key chord, or scroll direction'), within: str('window title/process to act in (required, except when asked from the mascot)'),
|
|
523
|
+
role: str('optional role such as button or edit'), file: str('document path for open'),
|
|
524
|
+
}, ['do']) },
|
|
525
|
+
{ name: 'gui.windows', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.windows(a, c),
|
|
526
|
+
description: 'List open desktop windows: title, app process, handle, position, which is focused/minimized. blocked = the AI may not control it.',
|
|
527
|
+
input_schema: schema({ include_dialogs: bool('also list owned dialogs') }) },
|
|
528
|
+
{ name: 'gui.observe', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.observe(a, c),
|
|
529
|
+
description: 'Read a window as an accessibility tree: each element has an id (node_id), role, name, value, state and supported actions. tree_quality "poor" = the app draws its own UI; a screenshot is then attached and the text on it is read on the device (OCR): each text run becomes a node with role "text", source "ocr" and an id like "4.t2" that gui.act can click / type at. Ids are only valid until the next observe of that window. truncated_by = why the list is partial: time / long_list (a very long table or list; scroll it, or use gui.find) / node_limit. In a long table scrolled far down, the rows on screen come back with role "row", source "accessible" and an id like "4.t2" that gui.act can click. content_unavailable = a Store app shows only its frame because it is still starting or suspended — gui.focus it, then observe again. image_error = no screenshot this time (the app can only be captured from the screen and the window is behind/covered — gui.focus it first if a screenshot is needed).',
|
|
530
|
+
input_schema: schema({
|
|
531
|
+
window: target.window, include_image: bool('attach a screenshot even when the tree is good'), max_nodes: num('default 300'),
|
|
532
|
+
ocr: bool('read the text on the window even when the tree is good (default: only when poor)'),
|
|
533
|
+
}) },
|
|
534
|
+
{ name: 'gui.find', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.find(a, c),
|
|
535
|
+
description: 'Like gui.observe but returns only the elements whose name / AutomationId / value contains the query words (accents ignored), optionally of one role — for big windows (spreadsheets, ERP forms) where the full tree is too long. Ids work with gui.act right away. exact=false means no element had every word; the closest ones are returned.',
|
|
536
|
+
input_schema: schema({
|
|
537
|
+
query: str('words of the element, e.g. "Save", "Số tiền", "Customer name"'), window: target.window,
|
|
538
|
+
role: str('only this role, e.g. button, edit, menuitem, dataitem'), max: num('default 20, max 60'),
|
|
539
|
+
}, ['query']) },
|
|
540
|
+
{ name: 'gui.wait_for', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.waitFor(a, c),
|
|
541
|
+
description: 'Wait until the UI reaches a state instead of observing again and again: an element (name contains / automation_id, optional role) appears or is gone in a window, or a window whose title contains some text appears or is gone (no window = any window). Returns met + waited_ms + the match; GUI_WAIT_TIMEOUT if it did not happen in time.',
|
|
542
|
+
input_schema: schema({
|
|
543
|
+
until: str('appears (default) | gone'), window: target.window, name: str('element name contains this text (case-insensitive)'),
|
|
544
|
+
automation_id: str('element AutomationId (exact)'), role: str('element role, e.g. button, menuitem, edit, window'),
|
|
545
|
+
title_contains: str('wait on a window title instead of an element'), timeout_ms: num('default 10000, max 60000'),
|
|
546
|
+
}) },
|
|
547
|
+
{ name: 'gui.read_table', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.readTable(a, c),
|
|
548
|
+
description: 'Read a whole long table as data, in the background: scrolls it, joins the rows, scrolls back. Prefer this to observing and scrolling screen by screen. node_id = the table, from gui.observe or gui.find. Returns columns, rows (each one line of cells), complete, reason when incomplete, gaps = rows may be missing between pages.',
|
|
549
|
+
input_schema: schema({ node_id: target.node_id, max_rows: num('default 300, at most 2000') }, ['node_id']) },
|
|
550
|
+
{ name: 'gui.focus', group: ToolGroup.GUI, handler: (a, c) => gui.focus(a, c),
|
|
551
|
+
description: 'Bring a window to the front (restores it if minimized). This takes the screen from the person using the computer: most actions work on windows behind others, so only use it when an action really needs the window in front.',
|
|
552
|
+
input_schema: schema({ window: target.window }, ['window']) },
|
|
553
|
+
{ name: 'gui.act', group: ToolGroup.GUI, handler: (a, c) => gui.act(a, c),
|
|
554
|
+
description: 'Runs behind the person\'s windows whenever the app allows it. Result method: invoke/value/select/toggle/scroll/background/posted = done without the real mouse; accessible = the control selected the item but no click event fired, so check the app reacted (observe) before relying on it. The real mouse/keyboard is only borrowed when the person pauses for a moment, then given back; GUI_USER_ACTIVE = they kept using the computer, nothing was done, so tell them in the chat. Do one action on an element (node_id) or at a point of the last screenshot: click, double_click, right_click, set_value (replace a field\'s text), type (keystrokes into the focused element), key (shortcut like "ctrl+s", "alt+f4", "enter"), scroll, select (option of a list/combo), toggle, expand, collapse, drag. Uses accessibility actions first (works even when the window is behind), real mouse/keyboard otherwise. Returns evidence: the element\'s new value/state, window title change, focused element; app_busy = the action ran but the app is still working, so no evidence yet — gui.wait_for or observe later. OCR text nodes ("4.t2") take click / double_click / right_click, or set_value / type (clicks there, then types). Without node_id give window. Stops with GUI_USER_ACTIVE if the person is using the mouse/keyboard, and with GUI_FOCUS_LOST (nothing clicked / the rest not typed) if real mouse/keyboard input could not reach the window — it could not come to the front, or another window covers the point.',
|
|
555
|
+
// method trong kết quả: posted = gửi thẳng vào cửa sổ; accessible = control tự chọn mục, không phát sự kiện bấm.
|
|
556
|
+
input_schema: schema({
|
|
557
|
+
action: str(Object.values(GuiAction).join(' | ')), ...target, text: str('text for set_value / type'), keys: str('for key: e.g. "ctrl+s", several separated by spaces'),
|
|
558
|
+
option: str('for select: the option name'), state: str('for toggle: on | off'), direction: str('for scroll: up | down | left | right'), amount: num('scroll steps, default 3'),
|
|
559
|
+
point: { type: 'object', description: '{x,y} on the last screenshot when no node_id', properties: { x: num('x'), y: num('y') } },
|
|
560
|
+
to: { type: 'object', description: 'drag destination {x,y} on the last screenshot', properties: { x: num('x'), y: num('y') } },
|
|
561
|
+
image_scale: num('scale of the screenshot the point was taken from'), method: str('auto | pattern | mouse | background (default auto; background = never touch the real mouse/keyboard, fail with GUI_NEEDS_REAL_INPUT instead)'),
|
|
562
|
+
}, ['action']) },
|
|
563
|
+
{ name: 'gui.open_app', group: ToolGroup.GUI, handler: (a, c, e) => gui.openApp(a, c, e),
|
|
564
|
+
description: 'Open an installed app by name (from the Start menu list), or open a document file with its default app. Returns the new window. Does not run programs or scripts by path.',
|
|
565
|
+
input_schema: schema({ name: str('app name, e.g. "Excel", "Calculator"'), file: str('a document path inside the allowed folders'), first: bool('take the first match when several apps share the name') }) },
|
|
566
|
+
];
|
|
567
|
+
}
|