@aivin-labs/cli 1.0.47 → 1.0.51
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/README.md +1 -1
- package/bin/cli.mjs +1 -1
- package/bin/lib/auth.mjs +1 -1
- package/bin/lib/context.mjs +3 -3
- package/bin/lib/openFile.mjs +3 -2
- package/bin/lib/remote/client.mjs +1418 -1221
- package/bin/lib/remote/confirmBarrier.mjs +45 -0
- package/bin/lib/remote/constants.mjs +3 -1
- package/bin/lib/remote/desktop/aivinIco.mjs +696 -0
- package/bin/lib/remote/desktop/castAuth.mjs +23 -9
- package/bin/lib/remote/desktop/castConsent.mjs +37 -6
- package/bin/lib/remote/desktop/castFileDrop.mjs +24 -0
- package/bin/lib/remote/desktop/castInput.mjs +63 -19
- package/bin/lib/remote/desktop/castTouchViewers.mjs +26 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +25 -2
- package/bin/lib/remote/desktop/desktopCastSource.mjs +298 -101
- package/bin/lib/remote/desktop/index.mjs +5 -3
- package/bin/lib/remote/desktop/traySource.mjs +1385 -1343
- package/bin/lib/remote/desktop/webrtcWorker.mjs +3 -0
- package/bin/lib/remote/deviceProfile.mjs +2 -0
- package/bin/lib/remote/gui/index.mjs +485 -480
- package/bin/lib/remote/humanInput.mjs +117 -0
- package/bin/lib/remote/idempotency.mjs +19 -2
- package/bin/lib/remote/keepAwake.mjs +15 -9
- package/bin/lib/remote/localConfirm.mjs +26 -7
- package/bin/lib/remote/mascot/ask.mjs +23 -4
- package/bin/lib/remote/mascot/askHostSource.mjs +10 -4
- package/bin/lib/remote/processes.mjs +231 -230
- package/bin/lib/remote/scheduler.mjs +164 -124
- package/bin/lib/remote/toolHandlers.mjs +3 -2
- package/bin/lib/remote/winTree.mjs +29 -0
- package/bin/lib/servers.mjs +31 -1
- package/docs/CLI.md +2 -2
- package/package.json +1 -1
|
@@ -1,480 +1,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
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
* thay
|
|
18
|
-
*
|
|
19
|
-
*
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
'
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
*
|
|
32
|
-
*
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
'
|
|
37
|
-
'
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
const
|
|
46
|
-
const
|
|
47
|
-
const
|
|
48
|
-
const
|
|
49
|
-
const
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
if (
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
const
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
if (
|
|
122
|
-
if (
|
|
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
|
-
c
|
|
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
|
-
const
|
|
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
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
const
|
|
252
|
-
const
|
|
253
|
-
const
|
|
254
|
-
|
|
255
|
-
const
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
if (
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
if (!
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
}
|
|
321
|
-
if (
|
|
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
|
-
async function
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
const
|
|
355
|
-
if (
|
|
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
|
-
const
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
}
|
|
427
|
-
|
|
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
|
-
}
|
|
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 str = (description) => ({ type: 'string', description });
|
|
56
|
+
const num = (description) => ({ type: 'number', description });
|
|
57
|
+
const bool = (description) => ({ type: 'boolean', description });
|
|
58
|
+
const schema = (properties, required = []) => ({ type: 'object', properties, required });
|
|
59
|
+
|
|
60
|
+
export const GuiAction = Object.freeze({
|
|
61
|
+
CLICK: 'click', DOUBLE_CLICK: 'double_click', RIGHT_CLICK: 'right_click', SET_VALUE: 'set_value', TYPE: 'type', KEY: 'key',
|
|
62
|
+
SCROLL: 'scroll', SELECT: 'select', TOGGLE: 'toggle', EXPAND: 'expand', COLLAPSE: 'collapse', DRAG: 'drag',
|
|
63
|
+
});
|
|
64
|
+
|
|
65
|
+
/** 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. */
|
|
66
|
+
export function detectGui({ disabled = false, multiUser = false, platform = process.platform } = {}) {
|
|
67
|
+
if (disabled || multiUser || platform !== 'win32') return null;
|
|
68
|
+
// Phiên 0 (dịch vụ) không có màn hình tương tác.
|
|
69
|
+
if (process.env.SESSIONNAME === 'Services') return null;
|
|
70
|
+
return { backend: 'uia', actions: Object.values(GuiAction) };
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
const normalizeProcess = (name) => String(name || '').toLowerCase().replace(/\.exe$/, '');
|
|
74
|
+
|
|
75
|
+
/** Ứng dụng này có được điều khiển không — ném lỗi nếu bị chặn. */
|
|
76
|
+
export function assertWindowAllowed(windowInfo, { fullAccess }) {
|
|
77
|
+
// 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).
|
|
78
|
+
if (isProtectedPromptWindow(windowInfo?.title)) {
|
|
79
|
+
throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, 'This is an Aivin confirmation box — only the person at this computer can answer it');
|
|
80
|
+
}
|
|
81
|
+
const proc = normalizeProcess(windowInfo?.process);
|
|
82
|
+
if (!proc) return;
|
|
83
|
+
if (BLOCKED_PROCESSES.has(proc)) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Controlling "${windowInfo.process}" is not allowed on this device`);
|
|
84
|
+
if (!fullAccess && SHELL_PROCESSES.has(proc)) {
|
|
85
|
+
throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Controlling "${windowInfo.process}" needs full device access (aivin remote start --full-access)`);
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
/** Ứng dụng này (tên trong menu Start) có được mở không — ném lỗi trước khi mở. */
|
|
90
|
+
export function assertAppAllowed(name, { fullAccess }) {
|
|
91
|
+
if (BLOCKED_PROCESSES.has(normalizeProcess(String(name || '').replace(/\s+/g, '')))) throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Opening "${name}" is not allowed`);
|
|
92
|
+
if (!fullAccess && SHELL_APP_NAME.test(String(name || ''))) {
|
|
93
|
+
throw new DeviceToolError(DeviceErrorCode.GUI_BLOCKED_APP, `Opening "${name}" needs full device access (aivin remote start --full-access)`);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const normalizeName = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/gi, 'd').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
|
|
98
|
+
|
|
99
|
+
/**
|
|
100
|
+
* Rank UI nodes with richer evidence while keeping the model-facing schema small. Hard exclusions happen
|
|
101
|
+
* before scoring; exact accessible names and AutomationIds beat loose word matches. The margin between the
|
|
102
|
+
* first two candidates is used by gui.do to refuse ambiguous actions instead of guessing.
|
|
103
|
+
*/
|
|
104
|
+
export function rankGuiNodes(nodes, query, role = '', { matchValue = true } = {}) {
|
|
105
|
+
const q = normalizeName(query);
|
|
106
|
+
const words = q.split(' ').filter(Boolean);
|
|
107
|
+
const wantedRole = String(role || '').toLowerCase();
|
|
108
|
+
if (!words.length) return [];
|
|
109
|
+
return (nodes || [])
|
|
110
|
+
.filter((n) => (!wantedRole || String(n.role || '').toLowerCase() === wantedRole || n.source === 'ocr') && !n.disabled && !n.offscreen)
|
|
111
|
+
.map((node, order) => {
|
|
112
|
+
const name = normalizeName(node.name);
|
|
113
|
+
const aid = normalizeName(node.automation_id);
|
|
114
|
+
const value = matchValue ? normalizeName(node.value) : '';
|
|
115
|
+
const help = normalizeName(node.help);
|
|
116
|
+
const combined = [name, aid, value, help].filter(Boolean).join(' ');
|
|
117
|
+
const hits = words.filter((word) => combined.includes(word)).length;
|
|
118
|
+
if (!hits) return null;
|
|
119
|
+
let score = Math.round((hits / words.length) * 50);
|
|
120
|
+
const evidence = [];
|
|
121
|
+
if (name === q) { score += 50; evidence.push('exact_name'); }
|
|
122
|
+
else if (aid === q) { score += 45; evidence.push('exact_automation_id'); }
|
|
123
|
+
else if (name.startsWith(q)) { score += 35; evidence.push('name_prefix'); }
|
|
124
|
+
else if (words.every((word) => name.includes(word))) { score += 30; evidence.push('all_words_in_name'); }
|
|
125
|
+
else if (words.every((word) => combined.includes(word))) { score += 20; evidence.push('all_words'); }
|
|
126
|
+
if (node.source === 'ocr') { score -= 5; evidence.push('ocr'); }
|
|
127
|
+
if (node.patterns?.length) { score += 3; evidence.push('actionable_pattern'); }
|
|
128
|
+
return { node, score, hits, evidence, order };
|
|
129
|
+
})
|
|
130
|
+
.filter(Boolean)
|
|
131
|
+
.sort((a, b) => b.score - a.score || b.hits - a.hits || a.order - b.order);
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/**
|
|
135
|
+
* 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
|
|
136
|
+
* 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.
|
|
137
|
+
*/
|
|
138
|
+
const RISKY_LABEL_WORDS = new Set([
|
|
139
|
+
'send', 'submit', 'post', 'publish', 'delete', 'remove', 'erase', 'pay', 'purchase', 'buy', 'order', 'confirm', 'approve', 'transfer', 'logout', 'signout',
|
|
140
|
+
'gui', 'dang', 'xoa', 'go', 'huy', 'mua', 'chuyen', 'duyet',
|
|
141
|
+
]);
|
|
142
|
+
const RISKY_LABEL_PHRASES = ['sign out', 'log out', 'thanh toan', 'xac nhan', 'dang xuat', 'dat hang', 'chuyen tien', 'go bo'];
|
|
143
|
+
|
|
144
|
+
export function riskyLabelWords(label) {
|
|
145
|
+
const n = normalizeName(label);
|
|
146
|
+
const words = n.split(' ').filter((w) => RISKY_LABEL_WORDS.has(w));
|
|
147
|
+
return [...words, ...RISKY_LABEL_PHRASES.filter((p) => ` ${n} `.includes(` ${p} `))];
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/** 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. */
|
|
151
|
+
export function needsServerCheck(query, node) {
|
|
152
|
+
const asked = new Set(riskyLabelWords(query));
|
|
153
|
+
return riskyLabelWords(node?.name || node?.automation_id).some((w) => !asked.has(w));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
/** 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. */
|
|
157
|
+
export function matchApps(apps, query) {
|
|
158
|
+
const q = normalizeName(query);
|
|
159
|
+
if (!q) return [];
|
|
160
|
+
const scored = apps.map((app) => {
|
|
161
|
+
const n = normalizeName(app.name);
|
|
162
|
+
const score = n === q ? 3 : n.startsWith(q) ? 2 : n.includes(q) ? 1 : 0;
|
|
163
|
+
return { app, score };
|
|
164
|
+
}).filter((x) => x.score > 0).sort((a, b) => b.score - a.score || a.app.name.length - b.app.name.length);
|
|
165
|
+
if (!scored.length) return [];
|
|
166
|
+
const top = scored[0].score;
|
|
167
|
+
return scored.filter((x) => x.score === top).map((x) => x.app);
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function runPowerShellJson(script, signal) {
|
|
171
|
+
return new Promise((resolve, reject) => {
|
|
172
|
+
// Đầ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).
|
|
173
|
+
const c = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `${PS_UTF8_PREFIX}${script}`], { windowsHide: true });
|
|
174
|
+
const chunks = [];
|
|
175
|
+
c.stdout.on('data', (d) => { chunks.push(d); });
|
|
176
|
+
const onAbort = () => { try { c.kill(); } catch { /* đã thoát */ } };
|
|
177
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
178
|
+
c.on('error', (e) => reject(e));
|
|
179
|
+
c.on('close', () => {
|
|
180
|
+
signal?.removeEventListener('abort', onAbort);
|
|
181
|
+
const out = Buffer.concat(chunks).toString('utf8');
|
|
182
|
+
try { const v = JSON.parse(out || 'null'); resolve(Array.isArray(v) ? v : v ? [v] : []); } catch (e) { reject(e); }
|
|
183
|
+
});
|
|
184
|
+
});
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
/**
|
|
188
|
+
* 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ả).
|
|
189
|
+
*/
|
|
190
|
+
export function createGuiController({
|
|
191
|
+
fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true, defaultWindow = () => null, fetchApps = (signal) => runPowerShellJson('Get-StartApps | Select-Object Name, AppID | ConvertTo-Json -Compress', signal),
|
|
192
|
+
} = {}) {
|
|
193
|
+
let appsCache = null;
|
|
194
|
+
let appsInflight = null;
|
|
195
|
+
let lastNotifyAt = 0;
|
|
196
|
+
/** Cửa sổ của từng lần observe — để kiểm ứng dụng bị chặn ở thao tác theo node_id. */
|
|
197
|
+
const snapshotWindows = new Map();
|
|
198
|
+
|
|
199
|
+
const announce = (windowInfo) => {
|
|
200
|
+
const now = Date.now();
|
|
201
|
+
if (now - lastNotifyAt < NOTIFY_EVERY_MS) return;
|
|
202
|
+
lastNotifyAt = now;
|
|
203
|
+
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.`);
|
|
204
|
+
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.` });
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
async function windows(args, ctx) {
|
|
208
|
+
const list = await host.call('windows', { all: !!args.include_dialogs }, ctx);
|
|
209
|
+
return { windows: list.map((w) => ({ ...w, blocked: BLOCKED_PROCESSES.has(normalizeProcess(w.process)) || (!fullAccess && SHELL_PROCESSES.has(normalizeProcess(w.process))) || isProtectedPromptWindow(w.title) || undefined })) };
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* 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ọ
|
|
214
|
+
* đang dùng ngay trước đó (`defaultWindow()` = `{ avoid_pid, fallback }`).
|
|
215
|
+
*/
|
|
216
|
+
const target = (args) => (args.window ? { window: args.window } : { ...defaultWindow() });
|
|
217
|
+
const windowInfoOf = (args, ctx) => host.call('window_info', target(args), ctx);
|
|
218
|
+
/**
|
|
219
|
+
* 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ỉ
|
|
220
|
+
* 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).
|
|
221
|
+
*/
|
|
222
|
+
const assertWindowNamed = (windowArg) => {
|
|
223
|
+
if (windowArg || defaultWindow()?.fallback) return;
|
|
224
|
+
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');
|
|
225
|
+
};
|
|
226
|
+
|
|
227
|
+
async function observe(args, ctx) {
|
|
228
|
+
const res = await host.call('observe', {
|
|
229
|
+
...target(args),
|
|
230
|
+
max_nodes: Math.min(Number(args.max_nodes) || OBSERVE_MAX_NODES, 1500),
|
|
231
|
+
include_image: !!args.include_image,
|
|
232
|
+
image_when_poor: args.image_when_poor !== false,
|
|
233
|
+
ocr: typeof args.ocr === 'boolean' ? args.ocr : undefined,
|
|
234
|
+
image_max_width: Number(args.image_max_width) || 1366,
|
|
235
|
+
image_quality: Number(args.image_quality) || 70,
|
|
236
|
+
}, ctx);
|
|
237
|
+
assertWindowAllowed(res.window, { fullAccess });
|
|
238
|
+
snapshotWindows.set(String(res.snapshot), res.window);
|
|
239
|
+
if (snapshotWindows.size > 20) snapshotWindows.delete(snapshotWindows.keys().next().value);
|
|
240
|
+
return res;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* 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
|
|
245
|
+
* 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 đủ
|
|
246
|
+
* hết từ thì lấy phần tử khớp nhiều từ nhất.
|
|
247
|
+
*/
|
|
248
|
+
async function find(args, ctx) {
|
|
249
|
+
const words = normalizeName(args.query).split(' ').filter(Boolean);
|
|
250
|
+
if (!words.length) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give query (words of the element to find)');
|
|
251
|
+
const role = String(args.role || '').toLowerCase();
|
|
252
|
+
const max = Math.max(1, Math.min(Number(args.max) || FIND_DEFAULT, FIND_MAX));
|
|
253
|
+
const res = await observe({ ...args, max_nodes: 1500 }, ctx);
|
|
254
|
+
// 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).
|
|
255
|
+
const scored = rankGuiNodes(res.nodes, args.query, role, { matchValue: args.match_value !== false });
|
|
256
|
+
const all = scored.filter((x) => x.hits === words.length);
|
|
257
|
+
const pool = all.length ? all : scored.filter((x) => x.hits === scored[0]?.hits);
|
|
258
|
+
const picked = pool.slice(0, max);
|
|
259
|
+
const margin = picked.length > 1 ? picked[0].score - picked[1].score : picked.length ? picked[0].score : 0;
|
|
260
|
+
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 };
|
|
261
|
+
Object.defineProperty(out, '_raw_observation', { value: res, enumerable: false });
|
|
262
|
+
return out;
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
/**
|
|
266
|
+
* Compact semantic fast path. The caller states intent; candidate evidence, exclusions, ambiguity handling,
|
|
267
|
+
* execution and cheap post-action verification stay inside the device runtime.
|
|
268
|
+
*/
|
|
269
|
+
async function semanticDo(args, ctx, env) {
|
|
270
|
+
const command = String(args.do || '').toLowerCase();
|
|
271
|
+
if (command === 'open') return openApp({ name: args.target, file: args.file }, ctx, env);
|
|
272
|
+
const action = {
|
|
273
|
+
click: GuiAction.CLICK, fill: GuiAction.SET_VALUE, select: GuiAction.SELECT, toggle: GuiAction.TOGGLE,
|
|
274
|
+
key: GuiAction.KEY, scroll: GuiAction.SCROLL,
|
|
275
|
+
}[command];
|
|
276
|
+
if (!action) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Unknown semantic action: ${args.do || ''}`);
|
|
277
|
+
assertWindowNamed(args.within || args.window);
|
|
278
|
+
|
|
279
|
+
if ((command === 'key' || command === 'scroll') && !args.target) {
|
|
280
|
+
const result = await act({
|
|
281
|
+
action, window: args.within || args.window, keys: command === 'key' ? args.value : undefined,
|
|
282
|
+
direction: command === 'scroll' ? args.value : undefined,
|
|
283
|
+
}, ctx);
|
|
284
|
+
return { ok: true, action: command, effect: result.window_title_changed || result.focused_element || command };
|
|
285
|
+
}
|
|
286
|
+
|
|
287
|
+
const query = String(args.target || '').trim();
|
|
288
|
+
if (!query) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give target');
|
|
289
|
+
let found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, match_value: false }, ctx);
|
|
290
|
+
if (!found.nodes.length && !found.ocr && found.tree_quality !== 'poor') {
|
|
291
|
+
found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, match_value: false, ocr: true }, ctx);
|
|
292
|
+
}
|
|
293
|
+
if (!found.nodes.length) throw new DeviceToolError(DeviceErrorCode.GUI_TARGET_NOT_FOUND, `No enabled visible target matched "${query}"`);
|
|
294
|
+
if (found.ambiguous) {
|
|
295
|
+
return {
|
|
296
|
+
ok: false, code: DeviceErrorCode.GUI_AMBIGUOUS_TARGET,
|
|
297
|
+
choices: found.nodes.map((n) => ({ ref: n.id, label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — ') })),
|
|
298
|
+
observation: found._raw_observation,
|
|
299
|
+
};
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
const node = found.nodes[0];
|
|
303
|
+
if (command !== 'fill' && needsServerCheck(query, node)) {
|
|
304
|
+
return {
|
|
305
|
+
ok: false, code: DeviceErrorCode.GUI_AMBIGUOUS_TARGET,
|
|
306
|
+
choices: found.nodes.map((n) => ({ ref: n.id, label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — ') })),
|
|
307
|
+
observation: found._raw_observation,
|
|
308
|
+
};
|
|
309
|
+
}
|
|
310
|
+
if (command === 'fill' && node.password) {
|
|
311
|
+
throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'AI may not fill password or secret fields — ask the user to enter it');
|
|
312
|
+
}
|
|
313
|
+
const result = await act({
|
|
314
|
+
action, node_id: node.id,
|
|
315
|
+
text: command === 'fill' ? args.value : undefined,
|
|
316
|
+
option: command === 'select' ? args.value : undefined,
|
|
317
|
+
state: command === 'toggle' ? args.value : undefined,
|
|
318
|
+
}, ctx);
|
|
319
|
+
let verified;
|
|
320
|
+
if (command === 'fill' && Object.hasOwn(result.target || {}, 'value')) verified = String(result.target.value) === String(args.value ?? '');
|
|
321
|
+
if (command === 'select' && Object.hasOwn(result.target || {}, 'selected')) verified = result.target.selected === true;
|
|
322
|
+
if (command === 'toggle' && Object.hasOwn(result.target || {}, 'checked')) {
|
|
323
|
+
const expected = String(args.value || '').toLowerCase();
|
|
324
|
+
verified = expected === 'on' ? result.target.checked === 'on' : expected === 'off' ? result.target.checked === 'off' : undefined;
|
|
325
|
+
}
|
|
326
|
+
if (verified === false) {
|
|
327
|
+
throw new DeviceToolError(DeviceErrorCode.GUI_NO_EFFECT, `${command} ran but the target did not reach the requested state`);
|
|
328
|
+
}
|
|
329
|
+
return {
|
|
330
|
+
ok: true, action: command, target: node.name || node.automation_id || node.role,
|
|
331
|
+
...(verified === undefined ? {} : { verified }),
|
|
332
|
+
...(result.screen_point ? { screen_point: result.screen_point } : {}),
|
|
333
|
+
effect: result.window_title_changed || result.target || result.focused_element || command,
|
|
334
|
+
};
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
/** 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. */
|
|
338
|
+
async function waitFor(args, ctx) {
|
|
339
|
+
const elementWait = !!(args.name || args.automation_id);
|
|
340
|
+
if (elementWait || args.window) assertWindowAllowed(await windowInfoOf(args, ctx), { fullAccess });
|
|
341
|
+
return host.call('wait_for', {
|
|
342
|
+
...(elementWait || args.window ? target(args) : {}),
|
|
343
|
+
until: args.until, name: args.name, automation_id: args.automation_id, role: args.role, title_contains: args.title_contains,
|
|
344
|
+
timeout_ms: Math.min(Number(args.timeout_ms) || 10_000, WAIT_MAX_MS),
|
|
345
|
+
}, ctx);
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
async function focus(args, ctx) {
|
|
349
|
+
assertWindowAllowed(await windowInfoOf(args, ctx), { fullAccess });
|
|
350
|
+
return host.call('focus', target(args), ctx);
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
async function act(args, ctx) {
|
|
354
|
+
const action = String(args.action || GuiAction.CLICK);
|
|
355
|
+
if (!Object.values(GuiAction).includes(action)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Unknown action: ${action}`);
|
|
356
|
+
const snap = args.node_id ? String(args.node_id).split('.')[0] : null;
|
|
357
|
+
// 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ổ.
|
|
358
|
+
if (!snap) assertWindowNamed(args.window);
|
|
359
|
+
const windowInfo = snap ? snapshotWindows.get(snap) : await windowInfoOf(args, ctx);
|
|
360
|
+
if (snap && !windowInfo) throw new DeviceToolError(DeviceErrorCode.GUI_STALE_NODE, `Node ${args.node_id} is from an old observation — observe again`);
|
|
361
|
+
assertWindowAllowed(windowInfo, { fullAccess });
|
|
362
|
+
announce(windowInfo);
|
|
363
|
+
return host.call('act', {
|
|
364
|
+
action, node_id: args.node_id, ...(args.node_id ? {} : target(args)), method: args.method, text: args.text, keys: args.keys,
|
|
365
|
+
option: args.option, state: args.state, direction: args.direction, amount: args.amount, point: args.point, to: args.to,
|
|
366
|
+
image_scale: args.image_scale, settle_ms: args.settle_ms,
|
|
367
|
+
check_user_input: true, user_input_grace_ms: Number(args.user_input_grace_ms) || 1500,
|
|
368
|
+
}, ctx);
|
|
369
|
+
}
|
|
370
|
+
|
|
371
|
+
async function listApps(signal) {
|
|
372
|
+
if (appsCache && Date.now() - appsCache.at < APPS_CACHE_MS) return appsCache.apps;
|
|
373
|
+
if (appsInflight && !signal) return appsInflight;
|
|
374
|
+
const task = Promise.resolve().then(() => fetchApps(signal)).catch(() => []).then((rows) => {
|
|
375
|
+
const apps = (rows || []).filter((r) => r?.Name && r?.AppID).map((r) => ({ name: String(r.Name), app_id: String(r.AppID) }));
|
|
376
|
+
if (apps.length) appsCache = { at: Date.now(), apps };
|
|
377
|
+
return apps.length ? apps : (appsCache?.apps || []);
|
|
378
|
+
}).finally(() => { if (appsInflight === task) appsInflight = null; });
|
|
379
|
+
if (!signal) appsInflight = task;
|
|
380
|
+
return task;
|
|
381
|
+
}
|
|
382
|
+
|
|
383
|
+
async function waitNewWindow(before, ctx, hint) {
|
|
384
|
+
const known = new Set(before.map((w) => w.window));
|
|
385
|
+
const deadline = Date.now() + OPEN_WAIT_MS;
|
|
386
|
+
while (Date.now() < deadline) {
|
|
387
|
+
await new Promise((r) => setTimeout(r, 400));
|
|
388
|
+
if (ctx.signal?.aborted) throw ctx.signal.reason;
|
|
389
|
+
const now = await host.call('windows', {}, ctx);
|
|
390
|
+
const fresh = now.filter((w) => !known.has(w.window));
|
|
391
|
+
const pick = fresh.find((w) => hint && normalizeName(`${w.title} ${w.process}`).includes(normalizeName(hint).split(' ')[0])) || fresh[0];
|
|
392
|
+
if (pick) return pick;
|
|
393
|
+
}
|
|
394
|
+
return null;
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
/** 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). */
|
|
398
|
+
async function sendToBack(win, before, ctx) {
|
|
399
|
+
if (!win || background === false) return;
|
|
400
|
+
const userWindow = before.find((w) => w.focused)?.window;
|
|
401
|
+
await host.call('to_back', { window: win.window, restore_to: userWindow }, ctx).catch(() => undefined);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/** 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ỳ ý. */
|
|
405
|
+
async function openApp(args, ctx, env) {
|
|
406
|
+
const before = await host.call('windows', {}, ctx);
|
|
407
|
+
if (args.file) {
|
|
408
|
+
const abs = resolveInRoots(env.roots, String(args.file));
|
|
409
|
+
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');
|
|
410
|
+
if (!fs.existsSync(abs)) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `File not found: ${args.file}`);
|
|
411
|
+
spawn('explorer.exe', [abs], { windowsHide: true, detached: true, stdio: 'ignore' }).unref();
|
|
412
|
+
const win = await waitNewWindow(before, ctx, path.basename(abs, path.extname(abs)));
|
|
413
|
+
await sendToBack(win, before, ctx);
|
|
414
|
+
return { opened: path.basename(abs), window: win, hint: win ? undefined : 'No new window appeared yet — the file may have opened in an existing window; check gui.windows' };
|
|
415
|
+
}
|
|
416
|
+
const name = String(args.name || '').trim();
|
|
417
|
+
if (!name) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give name (an installed app) or file');
|
|
418
|
+
const matches = matchApps(await listApps(ctx.signal), name);
|
|
419
|
+
if (!matches.length) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No installed app named "${name}"`);
|
|
420
|
+
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' };
|
|
421
|
+
const app = matches[0];
|
|
422
|
+
assertAppAllowed(app.name, { fullAccess });
|
|
423
|
+
spawn('explorer.exe', [`shell:AppsFolder\\${app.app_id}`], { windowsHide: true, detached: true, stdio: 'ignore' }).unref();
|
|
424
|
+
const win = await waitNewWindow(before, ctx, app.name);
|
|
425
|
+
await sendToBack(win, before, ctx);
|
|
426
|
+
if (win) assertWindowAllowed(win, { fullAccess });
|
|
427
|
+
return { opened: app.name, window: win, hint: win ? undefined : 'App started but no new window yet — call gui.windows in a moment' };
|
|
428
|
+
}
|
|
429
|
+
|
|
430
|
+
return { windows, observe, find, waitFor, focus, act, semanticDo, openApp, prewarm: () => listApps(), close: () => host.close() };
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
/** Công cụ GUI cho danh mục của Planner. */
|
|
434
|
+
export function buildGuiTools(gui) {
|
|
435
|
+
const target = {
|
|
436
|
+
node_id: str('target element id from the latest gui.observe (preferred)'),
|
|
437
|
+
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)'),
|
|
438
|
+
};
|
|
439
|
+
return [
|
|
440
|
+
{ name: 'gui.do', group: ToolGroup.GUI, handler: (a, c, e) => gui.semanticDo(a, c, e),
|
|
441
|
+
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.',
|
|
442
|
+
input_schema: schema({
|
|
443
|
+
do: str('click | fill | select | toggle | key | scroll | open'), target: str('short visible label or app name'),
|
|
444
|
+
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)'),
|
|
445
|
+
role: str('optional role such as button or edit'), file: str('document path for open'),
|
|
446
|
+
}, ['do']) },
|
|
447
|
+
{ name: 'gui.windows', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.windows(a, c),
|
|
448
|
+
description: 'List open desktop windows: title, app process, handle, position, which is focused/minimized. blocked = the AI may not control it.',
|
|
449
|
+
input_schema: schema({ include_dialogs: bool('also list owned dialogs') }) },
|
|
450
|
+
{ name: 'gui.observe', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.observe(a, c),
|
|
451
|
+
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. 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).',
|
|
452
|
+
input_schema: schema({
|
|
453
|
+
window: target.window, include_image: bool('attach a screenshot even when the tree is good'), max_nodes: num('default 300'),
|
|
454
|
+
ocr: bool('read the text on the window even when the tree is good (default: only when poor)'),
|
|
455
|
+
}) },
|
|
456
|
+
{ name: 'gui.find', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.find(a, c),
|
|
457
|
+
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.',
|
|
458
|
+
input_schema: schema({
|
|
459
|
+
query: str('words of the element, e.g. "Save", "Số tiền", "Customer name"'), window: target.window,
|
|
460
|
+
role: str('only this role, e.g. button, edit, menuitem, dataitem'), max: num('default 20, max 60'),
|
|
461
|
+
}, ['query']) },
|
|
462
|
+
{ name: 'gui.wait_for', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.waitFor(a, c),
|
|
463
|
+
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.',
|
|
464
|
+
input_schema: schema({
|
|
465
|
+
until: str('appears (default) | gone'), window: target.window, name: str('element name contains this text (case-insensitive)'),
|
|
466
|
+
automation_id: str('element AutomationId (exact)'), role: str('element role, e.g. button, menuitem, edit, window'),
|
|
467
|
+
title_contains: str('wait on a window title instead of an element'), timeout_ms: num('default 10000, max 60000'),
|
|
468
|
+
}) },
|
|
469
|
+
{ name: 'gui.focus', group: ToolGroup.GUI, handler: (a, c) => gui.focus(a, c),
|
|
470
|
+
description: 'Bring a window to the front (restores it if minimized).',
|
|
471
|
+
input_schema: schema({ window: target.window }, ['window']) },
|
|
472
|
+
{ name: 'gui.act', group: ToolGroup.GUI, handler: (a, c) => gui.act(a, c),
|
|
473
|
+
description: '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. 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.',
|
|
474
|
+
input_schema: schema({
|
|
475
|
+
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'),
|
|
476
|
+
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'),
|
|
477
|
+
point: { type: 'object', description: '{x,y} on the last screenshot when no node_id', properties: { x: num('x'), y: num('y') } },
|
|
478
|
+
to: { type: 'object', description: 'drag destination {x,y} on the last screenshot', properties: { x: num('x'), y: num('y') } },
|
|
479
|
+
image_scale: num('scale of the screenshot the point was taken from'), method: str('auto | pattern | mouse (default auto)'),
|
|
480
|
+
}, ['action']) },
|
|
481
|
+
{ name: 'gui.open_app', group: ToolGroup.GUI, handler: (a, c, e) => gui.openApp(a, c, e),
|
|
482
|
+
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.',
|
|
483
|
+
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') }) },
|
|
484
|
+
];
|
|
485
|
+
}
|