@aivin-labs/cli 1.0.11 → 1.0.21
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 +325 -288
- package/bin/cli.mjs +163 -17
- package/bin/lib/localPreview.mjs +437 -0
- package/bin/lib/openFile.mjs +235 -0
- package/bin/lib/previewCache.mjs +71 -0
- package/bin/lib/remote/atomicFile.mjs +32 -0
- package/bin/lib/remote/autoStart.mjs +2 -1
- package/bin/lib/remote/autoUpdate.mjs +12 -0
- package/bin/lib/remote/browserTunnel.mjs +47 -8
- package/bin/lib/remote/callLedger.mjs +94 -14
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1024 -808
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +261 -234
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/dailyBrowser.mjs +8 -2
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +58 -7
- package/bin/lib/remote/desktop/linux.mjs +1 -1
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
- package/bin/lib/remote/desktop/mac.mjs +2 -2
- package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +905 -527
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +85 -0
- package/bin/lib/remote/fileIndexer.mjs +773 -399
- package/bin/lib/remote/folderRules.mjs +143 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +170 -19
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +12 -3
- package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/idempotency.mjs +49 -20
- package/bin/lib/remote/localPolicy.mjs +81 -9
- package/bin/lib/remote/mascot/ask.mjs +207 -42
- package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +658 -512
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +54 -5
- package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
- package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
- package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
- package/bin/lib/remote/mascot/fileChips.mjs +62 -0
- package/bin/lib/remote/mascot/hostSource.mjs +331 -52
- package/bin/lib/remote/mascot/hotkey.mjs +31 -7
- package/bin/lib/remote/mascot/images.mjs +111 -0
- package/bin/lib/remote/mascot/index.mjs +663 -493
- package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
- package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
- package/bin/lib/remote/mascot/mood.mjs +57 -0
- package/bin/lib/remote/mascot/rigSource.mjs +648 -609
- package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
- package/bin/lib/remote/mascot/strings.mjs +456 -375
- package/bin/lib/remote/mascot/ui.mjs +27 -7
- package/bin/lib/remote/multiUser.mjs +7 -2
- package/bin/lib/remote/notify.mjs +4 -1
- package/bin/lib/remote/office/index.mjs +12 -6
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/processes.mjs +5 -2
- package/bin/lib/remote/sandbox.mjs +26 -0
- package/bin/lib/remote/secretPaths.mjs +21 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +852 -741
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- package/bin/lib/remoteControl.mjs +26 -26
- package/bin/lib/selfUpdate.mjs +12 -2
- package/bin/lib/update/binarySwap.mjs +15 -1
- package/bin/lib/update/state.mjs +10 -0
- package/docs/AIVIN_MASCOT.md +14 -0
- package/docs/CLI.md +1545 -1484
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +75 -71
- package/docs/media/aivin-mascot-states.mp4 +0 -0
|
@@ -1,808 +1,1024 @@
|
|
|
1
|
-
import os from 'os';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import axios from 'axios';
|
|
4
|
-
import chalk from 'chalk';
|
|
5
|
-
import
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
import {
|
|
21
|
-
import {
|
|
22
|
-
import {
|
|
23
|
-
import {
|
|
24
|
-
import {
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
import {
|
|
29
|
-
import {
|
|
30
|
-
import {
|
|
31
|
-
import {
|
|
32
|
-
import {
|
|
33
|
-
import {
|
|
34
|
-
import {
|
|
35
|
-
import {
|
|
36
|
-
import {
|
|
37
|
-
import {
|
|
38
|
-
import {
|
|
39
|
-
import {
|
|
40
|
-
import {
|
|
41
|
-
import {
|
|
42
|
-
import {
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
} from '
|
|
46
|
-
import {
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
const
|
|
58
|
-
|
|
59
|
-
const
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
const
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
};
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
if (call
|
|
101
|
-
if (
|
|
102
|
-
if (call.
|
|
103
|
-
return
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
if (
|
|
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
|
-
const
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
const
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
const
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
const
|
|
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
|
-
//
|
|
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
|
-
roots
|
|
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
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
const
|
|
311
|
-
|
|
312
|
-
const
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
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
|
-
say(chalk.gray(
|
|
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
|
-
|
|
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
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
}
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
}
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
}
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
}
|
|
671
|
-
} catch (e) {
|
|
672
|
-
|
|
673
|
-
}
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
};
|
|
679
|
-
|
|
680
|
-
/**
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
}
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
}
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
scheduler.
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
}
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
}
|
|
807
|
-
|
|
808
|
-
|
|
1
|
+
import os from 'os';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import axios from 'axios';
|
|
4
|
+
import chalk from 'chalk';
|
|
5
|
+
import readline from 'readline/promises';
|
|
6
|
+
import { io } from 'socket.io-client';
|
|
7
|
+
import { DEFAULT_AIVIN_BASE_URL } from '../context.mjs';
|
|
8
|
+
import { logActivity } from './activityLog.mjs';
|
|
9
|
+
import { DEFAULT_SCOPE_LIMITS, DEVICE_NAMESPACE, CastState, DeviceAccess, DeviceErrorCode, DeviceEvent, HoldPhase, MAX_RESULT_BYTES, PROTOCOL_VERSION, REMOTE_IDEM_FILE, REMOTE_OUTBOX_FILE, ServerFeature, ToolGroup } from './constants.mjs';
|
|
10
|
+
import { CallState, createCallLedger } from './callLedger.mjs';
|
|
11
|
+
import { fallBackToPreviousToken, settleRotation } from './tokenRotation.mjs';
|
|
12
|
+
import { configureProxy, proxyAgentFor } from './netProxy.mjs';
|
|
13
|
+
import { createKeepAwake } from './keepAwake.mjs';
|
|
14
|
+
import { createPolicyGuard, describeCall, evaluateLocalPolicy } from './localPolicy.mjs';
|
|
15
|
+
import { ConfirmResult, createLocalConfirmer } from './localConfirm.mjs';
|
|
16
|
+
import { clearDeviceCredentials, credentialsFromEnv, listDevices, loadDeviceCredentials, pairDevice, pairDeviceWithCode, readStoredTokenFresh, saveDeviceCredentials } from './credentials.mjs';
|
|
17
|
+
import { ensureMemoryLoaded, memoryStats, stopWatchingMemory, watchMemoryDir } from './deviceMemory.mjs';
|
|
18
|
+
import { buildCatalog, buildDeviceProfile } from './deviceProfile.mjs';
|
|
19
|
+
import { createFileIndex, indexRootsFor } from './fileIndexer.mjs';
|
|
20
|
+
import { createScheduler } from './scheduler.mjs';
|
|
21
|
+
import { acquireDaemonLock, lockHolder } from './daemonLock.mjs';
|
|
22
|
+
import { randomUUID } from 'crypto';
|
|
23
|
+
import { DeviceToolError, fullAccessRoots, isRemotePaused, setRemotePaused } from './sandbox.mjs';
|
|
24
|
+
import { createMascot, HostEvent as MascotHostEvent, loadMascotSettings } from './mascot/index.mjs';
|
|
25
|
+
import { createMascotChat } from './mascot/ask.mjs';
|
|
26
|
+
import { mascotLang } from './mascot/strings.mjs';
|
|
27
|
+
import { showOSNotification } from './notify.mjs';
|
|
28
|
+
import { createMeetingManager, watchMeetingRequests } from './meeting/index.mjs';
|
|
29
|
+
import { createMediaHost, mediaSupported } from './meeting/recorder.mjs';
|
|
30
|
+
import { createClipboard } from './clipboard.mjs';
|
|
31
|
+
import { buildTools, toolMap } from './toolHandlers.mjs';
|
|
32
|
+
import { createBrowserTunnels, detectLocalBrowser } from './browserTunnel.mjs';
|
|
33
|
+
import { createGuiController, detectGui } from './gui/index.mjs';
|
|
34
|
+
import { createWindowsHost } from './gui/windowsHost.mjs';
|
|
35
|
+
import { detectOfficeApps } from './office/index.mjs';
|
|
36
|
+
import { createUndoStore } from './undoStore.mjs';
|
|
37
|
+
import { createProcessManager } from './processes.mjs';
|
|
38
|
+
import { createIdempotentRunner } from './idempotency.mjs';
|
|
39
|
+
import { createWatchManager } from './deviceWatches.mjs';
|
|
40
|
+
import { createScheduleManager } from './schedule.mjs';
|
|
41
|
+
import { remoteDebuggingPage } from './dailyBrowser.mjs';
|
|
42
|
+
import { HOME_BASE, SHARED_DIR, createMultiUserHost, isMultiUserMode } from './multiUser.mjs';
|
|
43
|
+
import { createAutoUpdater } from './autoUpdate.mjs';
|
|
44
|
+
import { createDesktopCastManager } from './desktop/desktopCast.mjs';
|
|
45
|
+
import { createDesktopWebRtcWorker } from './desktop/webrtcWorker.mjs';
|
|
46
|
+
import { CastInputRejection, createCastInputGate } from './desktop/castInput.mjs';
|
|
47
|
+
import {
|
|
48
|
+
BootAction, MAX_BOOTS_BEFORE_ROLLBACK, RESTART_EXIT_CODE, UPDATE_CONFIRM_AFTER_MS, UPDATE_ROLLED_BACK, checkBootAfterUpdate, cleanupRetired, clearStaleInstalledMarker,
|
|
49
|
+
confirmUpdate, ingestSupervisorRollback, isStandaloneBinary, noteCleanExit, updateProfile,
|
|
50
|
+
} from '../selfUpdate.mjs';
|
|
51
|
+
import { cliLaunchCommand, detectSupervisor } from './autoStart.mjs';
|
|
52
|
+
|
|
53
|
+
const HEARTBEAT_MS = 20_000;
|
|
54
|
+
// Nhịp nối lại tối đa. Máy cá nhân giãn tới 30 s (nhiều máy cùng dội BE lúc deploy). Cloud Computer (`--multi-user`): một socket / org qua
|
|
55
|
+
// mạng nội bộ, BE có thể đang chờ máy nối về để giao việc — giãn 30 s (+50 % ngẫu nhiên) nghĩa là BE lên lại rồi vẫn chờ tới ~45 s (28/10/2026).
|
|
56
|
+
const RECONNECT_DELAY_MAX_MS = 30_000;
|
|
57
|
+
const MULTI_USER_RECONNECT_DELAY_MAX_MS = 2_000;
|
|
58
|
+
const STREAM_FLUSH_MS = 150;
|
|
59
|
+
const STREAM_FLUSH_BYTES = 16 * 1024;
|
|
60
|
+
const ACK_TIMEOUT_MS = 10_000;
|
|
61
|
+
/** Một lô tính vector (32 đoạn) trên BE — bge-m3 bận thì chờ lâu hơn ack thường. */
|
|
62
|
+
const EMBED_TIMEOUT_MS = 60_000;
|
|
63
|
+
/** Kiểm công tắc tạm dừng (`aivin remote pause` ở cửa sổ khác) bấy nhiêu lâu một lần. */
|
|
64
|
+
const PAUSE_POLL_MS = 2000;
|
|
65
|
+
/** Chờ BE xác nhận đã nhận một kết quả (BE có `resume`) — quá hạn thì giữ kết quả trên đĩa, gửi lại khi nối lại. */
|
|
66
|
+
const RESULT_ACK_TIMEOUT_MS = 15_000;
|
|
67
|
+
/** Tự cập nhật: báo BE "sắp khởi động lại để chuyển bản" (chờ ack tối đa bấy nhiêu), và máy dự kiến quay lại trong bấy nhiêu. */
|
|
68
|
+
const RESTARTING_ACK_TIMEOUT_MS = 2_000;
|
|
69
|
+
const RESTART_EXPECT_BACK_MS = 30_000;
|
|
70
|
+
|
|
71
|
+
/** Gom đoạn stdout/stderr của một lời gọi, đẩy lên theo nhịp (không bắn mỗi dòng một gói). */
|
|
72
|
+
function createStreamer(socket, callId) {
|
|
73
|
+
const buffers = { stdout: '', stderr: '' };
|
|
74
|
+
let timer = null;
|
|
75
|
+
const flush = () => {
|
|
76
|
+
clearTimeout(timer);
|
|
77
|
+
timer = null;
|
|
78
|
+
for (const stream of Object.keys(buffers)) {
|
|
79
|
+
if (!buffers[stream]) continue;
|
|
80
|
+
if (socket.connected) socket.emit(DeviceEvent.STREAM, { call_id: callId, stream, chunk: buffers[stream] });
|
|
81
|
+
buffers[stream] = '';
|
|
82
|
+
}
|
|
83
|
+
};
|
|
84
|
+
const push = (stream, chunk) => {
|
|
85
|
+
buffers[stream] = (buffers[stream] || '') + chunk;
|
|
86
|
+
if (buffers[stream].length >= STREAM_FLUSH_BYTES) flush();
|
|
87
|
+
else if (!timer) timer = setTimeout(flush, STREAM_FLUSH_MS);
|
|
88
|
+
};
|
|
89
|
+
return { push, flush };
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
let unhandledRejectionHooked = false;
|
|
93
|
+
const MAX_CALL_ID = 64;
|
|
94
|
+
const MAX_TOOL_NAME = 128;
|
|
95
|
+
|
|
96
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
97
|
+
|
|
98
|
+
/** Lời gọi BE gửi xuống có đúng dạng không (object, call_id chuỗi ≤ 64, tool chuỗi, args object hoặc bỏ trống, timeout là số). */
|
|
99
|
+
export function isValidDeviceCall(call) {
|
|
100
|
+
if (!isPlainObject(call)) return false;
|
|
101
|
+
if (typeof call.call_id !== 'string' || !call.call_id || call.call_id.length > MAX_CALL_ID) return false;
|
|
102
|
+
if (typeof call.tool !== 'string' || !call.tool || call.tool.length > MAX_TOOL_NAME) return false;
|
|
103
|
+
if (call.args !== undefined && call.args !== null && !isPlainObject(call.args)) return false;
|
|
104
|
+
if (call.timeout_ms !== undefined && call.timeout_ms !== null && !Number.isFinite(call.timeout_ms)) return false;
|
|
105
|
+
if (call.user_scope !== undefined && call.user_scope !== null && typeof call.user_scope !== 'string') return false;
|
|
106
|
+
if (call.idem_key !== undefined && call.idem_key !== null && (typeof call.idem_key !== 'string' || call.idem_key.length > 80)) return false;
|
|
107
|
+
if (call.purpose !== undefined && call.purpose !== null && typeof call.purpose !== 'string') return false;
|
|
108
|
+
return true;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function boundedResult(outcome) {
|
|
112
|
+
if (!outcome.ok) return outcome;
|
|
113
|
+
let size;
|
|
114
|
+
try { size = Buffer.byteLength(JSON.stringify(outcome.result ?? null)); } catch { size = MAX_RESULT_BYTES + 1; }
|
|
115
|
+
if (size <= MAX_RESULT_BYTES) return outcome;
|
|
116
|
+
return { ok: false, error: `Result too large (${size} bytes) — read smaller ranges`, error_code: DeviceErrorCode.OUTPUT_TOO_LARGE, duration_ms: outcome.duration_ms };
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* Máy chủ của daemon: `--server` nêu rõ → có mã kết nối thì mặc định (mã chỉ đúng với máy chủ tạo ra nó, không theo cấu hình đăng nhập
|
|
121
|
+
* cũ) → máy chủ ĐÃ GHÉP → cấu hình đăng nhập → mặc định. Máy đã ghép đứng trước đăng nhập: ngược lại thì máy ghép bằng mã với máy chủ A,
|
|
122
|
+
* khởi động lại trên máy đang đăng nhập CLI với máy chủ B sẽ lặng lẽ ghép lại sang B bằng API key (chạy thật 26/10/2026). Đổi máy chủ
|
|
123
|
+
* thì dùng `--server` (hoặc `--repair`).
|
|
124
|
+
*/
|
|
125
|
+
export function resolveServerUrl(options, saved, env = process.env) {
|
|
126
|
+
const url = options.server || options.serverUrl
|
|
127
|
+
|| (options.code ? undefined : (options.repair ? undefined : saved?.server_url) || env.AIVIN_BASE_URL)
|
|
128
|
+
|| DEFAULT_AIVIN_BASE_URL;
|
|
129
|
+
return String(url).replace(/\/+$/, '');
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
/**
|
|
133
|
+
* Máy đang ghép với máy chủ khác: chuyển sang máy chủ mới là giao máy cho bên quản trị máy chủ đó → phải có người trả lời trong terminal (rà
|
|
134
|
+
* 02/11/2026). Không có terminal (lệnh do agent / script chạy) thì từ chối.
|
|
135
|
+
*/
|
|
136
|
+
async function confirmServerChange(saved, serverUrl) {
|
|
137
|
+
if (!saved?.server_url || saved.server_url === serverUrl) return;
|
|
138
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
139
|
+
throw new Error(`Máy này đang kết nối với ${saved.server_url}. Chuyển sang ${serverUrl} chỉ làm được khi gõ lệnh trong cửa sổ terminal.`);
|
|
140
|
+
}
|
|
141
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
142
|
+
try {
|
|
143
|
+
const answer = await rl.question(chalk.yellow(`⚠️ Máy này đang kết nối với ${saved.server_url}. Chuyển sang ${serverUrl}? Máy chủ mới sẽ điều khiển được máy này. Gõ "co" để đồng ý: `));
|
|
144
|
+
if (!/^\s*(co|có|yes|y)\s*$/i.test(answer)) throw new Error('Đã huỷ — máy giữ kết nối cũ.');
|
|
145
|
+
} finally {
|
|
146
|
+
rl.close();
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* Thông tin ghép máy: có mã kết nối thì luôn ghép bằng mã (người dùng vừa bấm "Thêm máy tính này"); có sẵn và đúng máy chủ thì dùng;
|
|
152
|
+
* không thì ghép mới bằng API key đang đăng nhập.
|
|
153
|
+
*/
|
|
154
|
+
async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name, repair, profile }) {
|
|
155
|
+
let creds = loadDeviceCredentials();
|
|
156
|
+
await confirmServerChange(creds, serverUrl);
|
|
157
|
+
if (code) {
|
|
158
|
+
creds = await pairDeviceWithCode({ serverUrl, code, roots, name, profile });
|
|
159
|
+
} else if (!creds || creds.server_url !== serverUrl || repair) {
|
|
160
|
+
creds = await pairDevice({ serverUrl, apiKey, roots, name, profile });
|
|
161
|
+
} else if (rootsGiven && JSON.stringify(roots) !== JSON.stringify(creds.roots)) {
|
|
162
|
+
creds.roots = roots;
|
|
163
|
+
saveDeviceCredentials(creds);
|
|
164
|
+
}
|
|
165
|
+
return creds;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
/**
|
|
169
|
+
* `aivin remote pair --code`: chỉ ghép máy, không nhận việc — bộ cài dùng khi đã có khay (khay thấy máy đã ghép là mở listener ngay,
|
|
170
|
+
* người dùng đóng được cửa sổ cài). Listener đang chạy bằng token cũ thì dừng nó để khay mở lại bằng token mới. Trả pid đã dừng (hoặc null).
|
|
171
|
+
*/
|
|
172
|
+
export async function pairWithCodeOnly(options) {
|
|
173
|
+
const saved = loadDeviceCredentials();
|
|
174
|
+
const serverUrl = resolveServerUrl(options, saved);
|
|
175
|
+
await confirmServerChange(saved, serverUrl);
|
|
176
|
+
configureProxy({ explicit: options.proxy });
|
|
177
|
+
const fullAccess = !options.dir && !!options.fullAccess;
|
|
178
|
+
const roots = (fullAccess ? fullAccessRoots() : [options.dir || process.cwd()]).map((r) => path.resolve(r));
|
|
179
|
+
const access = fullAccess ? DeviceAccess.FULL : DeviceAccess.FOLDERS;
|
|
180
|
+
const profile = { ...buildDeviceProfile(fullAccess ? [os.homedir()] : roots), roots, access };
|
|
181
|
+
const creds = await pairDeviceWithCode({ serverUrl, code: options.code, roots, name: options.name, profile });
|
|
182
|
+
saveDeviceCredentials({ ...creds, access });
|
|
183
|
+
const stale = lockHolder();
|
|
184
|
+
if (stale) try { process.kill(stale); } catch { /* vừa tự thoát */ }
|
|
185
|
+
return { creds, stopped: stale };
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Daemon nhận việc từ BE (`aivin remote start`): ghép máy (token thiết bị riêng), nối namespace `/device`, công bố hồ sơ + danh mục công
|
|
190
|
+
* cụ theo năng lực máy, nhận lô lời gọi, chạy song song theo nhóm, trả kết quả + luồng stdout. Thư mục gốc, công tắc ngắt, lọc biến môi
|
|
191
|
+
* trường là sàn cứng trên máy — BE không đổi được.
|
|
192
|
+
*/
|
|
193
|
+
export async function startRemoteClient(options = {}) {
|
|
194
|
+
// Máy tính tổ chức (`--multi-user`, container do Aivin cấp): token từ env, mọi thành viên org dùng chung, mỗi người một vùng riêng.
|
|
195
|
+
const multiUser = isMultiUserMode(options);
|
|
196
|
+
const envCreds = multiUser ? credentialsFromEnv() : null;
|
|
197
|
+
if (multiUser && !envCreds) throw new Error('--multi-user cần AIVIN_DEVICE_TOKEN, AIVIN_DEVICE_ID và AIVIN_SERVER (máy tính tổ chức do Aivin cấp).');
|
|
198
|
+
if (multiUser && process.platform === 'win32') throw new Error('--multi-user chỉ chạy trên Linux (container máy tính tổ chức).');
|
|
199
|
+
const saved = envCreds || loadDeviceCredentials();
|
|
200
|
+
const serverUrl = resolveServerUrl(options, saved);
|
|
201
|
+
// Trước mọi lời gọi mạng (ghép máy cũng đi qua proxy).
|
|
202
|
+
const proxy = configureProxy({ explicit: options.proxy });
|
|
203
|
+
const apiKey = options.apiKey ?? process.env.API_KEY;
|
|
204
|
+
const rootsGiven = Boolean(options.dir) && !multiUser;
|
|
205
|
+
// Toàn quyền: chủ máy chọn lúc kết nối (`--full-access`), giữ qua các lần khởi động lại; `--dir` tường minh thì về chế độ một thư mục.
|
|
206
|
+
// Nhiều người dùng: mỗi thành viên toàn quyền trong vùng của mình (thư mục nhà + thư mục chung) — gốc thật đặt theo từng lời gọi.
|
|
207
|
+
const fullAccess = multiUser || (!rootsGiven && (!!options.fullAccess || (!options.code && saved?.access === DeviceAccess.FULL)));
|
|
208
|
+
const roots = multiUser ? [HOME_BASE, SHARED_DIR] : fullAccess ? fullAccessRoots()
|
|
209
|
+
: rootsGiven ? [path.resolve(options.dir)] : (saved?.access !== DeviceAccess.FULL && saved?.roots?.length ? saved.roots : [process.cwd()]);
|
|
210
|
+
// Dò dự án + chỉ mục tệp chỉ trong thư mục nhà khi toàn quyền — quét cả ổ C: là hàng trăm nghìn tệp hệ thống vô ích.
|
|
211
|
+
const scanRoots = multiUser ? [] : fullAccess ? [os.homedir()] : roots;
|
|
212
|
+
const quiet = !!options.quiet;
|
|
213
|
+
const say = (...args) => { if (!quiet) console.log(...args); };
|
|
214
|
+
|
|
215
|
+
// Cửa sổ thứ hai cùng thư mục cấu hình → dừng ngay với hướng dẫn (trừ khi ghép lại bằng mã: cửa sổ cũ sẽ tự dừng).
|
|
216
|
+
const releaseLock = acquireDaemonLock({ takeOver: !!options.code });
|
|
217
|
+
// Tự cập nhật — ngay sau khi giữ khoá (cửa sổ thứ hai bị từ chối không được tính là một lần khởi động): bản vừa cài sập nhiều lần trước
|
|
218
|
+
// khi chạy ổn thì trả bản cũ trước khi đụng tới gì khác. Máy tính tổ chức: phiên bản do ảnh container quyết, không tự đổi.
|
|
219
|
+
const selfManaged = !multiUser && isStandaloneBinary();
|
|
220
|
+
const supervisor = multiUser ? null : detectSupervisor({ quiet });
|
|
221
|
+
const autoUpdateEnabled = !multiUser && options.autoUpdate !== false && process.env.AIVIN_AUTO_UPDATE !== '0';
|
|
222
|
+
if (selfManaged) {
|
|
223
|
+
// Trình giữ chạy (VBS / kịch bản sh) đã tự lùi bản mới vì nó sập ngay khi khởi động → bản này (bản cũ) ghi nhận, bỏ qua bản lỗi.
|
|
224
|
+
const supervisorRollback = ingestSupervisorRollback();
|
|
225
|
+
if (supervisorRollback) {
|
|
226
|
+
logActivity({ type: 'self_update_rollback', version: supervisorRollback, by: 'supervisor' });
|
|
227
|
+
say(chalk.yellow(`↩ aivin ${supervisorRollback} sập ngay khi khởi động — đã trả về bản này và sẽ bỏ qua ${supervisorRollback}.`));
|
|
228
|
+
}
|
|
229
|
+
const boot = checkBootAfterUpdate();
|
|
230
|
+
if (boot.action === BootAction.ROLLED_BACK) {
|
|
231
|
+
releaseLock();
|
|
232
|
+
logActivity({ type: 'self_update_rollback', version: boot.version, previous: boot.previous });
|
|
233
|
+
const err = new Error(`aivin ${boot.version} không chạy ổn sau ${MAX_BOOTS_BEFORE_ROLLBACK} lần khởi động — đã trả về ${boot.previous || 'bản trước'}, sẽ bỏ qua bản này. Chạy lại \`aivin remote start\`.`);
|
|
234
|
+
err.code = UPDATE_ROLLED_BACK;
|
|
235
|
+
err.restart = !!supervisor;
|
|
236
|
+
throw err;
|
|
237
|
+
}
|
|
238
|
+
clearStaleInstalledMarker();
|
|
239
|
+
cleanupRetired();
|
|
240
|
+
}
|
|
241
|
+
const access = fullAccess ? DeviceAccess.FULL : DeviceAccess.FOLDERS;
|
|
242
|
+
// Chrome / Edge cho AI Browser (CLI ≥ 1.0.8) — có thì BE cho việc trên web chạy ở trình duyệt của máy này.
|
|
243
|
+
const browser = options.browser === false || multiUser ? null : detectLocalBrowser();
|
|
244
|
+
// Điều khiển giao diện (Windows): cây trợ năng + chuột / bàn phím cho ứng dụng không có dòng lệnh.
|
|
245
|
+
const guiProfile = detectGui({ disabled: options.gui === false, multiUser });
|
|
246
|
+
// Excel / Word / Outlook có trên máy → công cụ office.* qua COM (tự phát hiện, người dùng không cấu hình gì).
|
|
247
|
+
const officeApps = detectOfficeApps({ multiUser });
|
|
248
|
+
// Sàn luật tại máy: chỉ nhận bản `aivin remote policy` đã ký; tệp bị sửa ngoài lệnh đó (agent ghi đè qua shell) chỉ được siết thêm.
|
|
249
|
+
const policyGuard = createPolicyGuard({
|
|
250
|
+
onTamper: (effective) => {
|
|
251
|
+
say(chalk.yellow(`⚠️ Tệp luật tại máy bị sửa ngoài lệnh \`aivin remote policy\` — chỉ áp phần siết thêm (xác nhận: ${effective.confirm}).`));
|
|
252
|
+
logActivity({ type: 'local_policy_tampered', confirm: effective.confirm });
|
|
253
|
+
},
|
|
254
|
+
});
|
|
255
|
+
const profile = {
|
|
256
|
+
...buildDeviceProfile(scanRoots), roots: roots.map((r) => path.resolve(r)), access,
|
|
257
|
+
...(browser ? { browser } : {}), ...(guiProfile ? { gui: guiProfile } : {}), ...(officeApps.length ? { apps: officeApps } : {}),
|
|
258
|
+
// Theo dõi kích hoạt việc (CLI ≥ 1.0.9) — máy tính tổ chức không có.
|
|
259
|
+
...(multiUser ? {} : { watch: true }),
|
|
260
|
+
// Tệp lớn qua HTTP thẳng (fs.upload / fs.download, công cụ BE-only nên BE biết qua cờ này) — máy tính tổ chức không có.
|
|
261
|
+
...(multiUser ? {} : { direct_transfer: true }),
|
|
262
|
+
// Sàn luật tại máy (localPolicy.mjs): BE biết việc nào sẽ phải chờ người bấm trên máy — máy tính tổ chức không có người ngồi trước máy.
|
|
263
|
+
...(multiUser ? {} : { local_confirm: policyGuard.read().confirm }),
|
|
264
|
+
// Tình trạng tự cập nhật (BE gom lại thấy cả đội máy, tự hoãn bản nhiều máy phải lùi) — làm mới mỗi lần chào lại máy chủ.
|
|
265
|
+
...(multiUser ? {} : { update: updateProfile({ enabled: autoUpdateEnabled }) }),
|
|
266
|
+
};
|
|
267
|
+
let creds;
|
|
268
|
+
try {
|
|
269
|
+
creds = envCreds || await ensurePaired({ serverUrl, apiKey, code: options.code, roots, rootsGiven, name: options.name, repair: options.repair, profile });
|
|
270
|
+
} catch (e) {
|
|
271
|
+
releaseLock();
|
|
272
|
+
throw e;
|
|
273
|
+
}
|
|
274
|
+
if (!envCreds && (creds.access !== access || JSON.stringify(creds.roots) !== JSON.stringify(profile.roots))) {
|
|
275
|
+
creds.access = access;
|
|
276
|
+
creds.roots = profile.roots;
|
|
277
|
+
saveDeviceCredentials(creds);
|
|
278
|
+
}
|
|
279
|
+
if (options.code) say(chalk.green(`✅ Đã kết nối máy "${creds.name}" với tài khoản ${creds.account || 'Aivin của bạn'} — quay lại Aivin để chọn máy này.`));
|
|
280
|
+
ensureMemoryLoaded();
|
|
281
|
+
watchMemoryDir();
|
|
282
|
+
const fileIndex = multiUser ? null : createFileIndex(indexRootsFor(roots, fullAccess));
|
|
283
|
+
const useDailyBrowser = options.separateBrowser !== true;
|
|
284
|
+
const browserTunnels = browser ? createBrowserTunnels({ serverUrl, deviceToken: () => creds.device_token, browser, useDailyBrowser, say: (m) => say(chalk.cyan(m)) }) : null;
|
|
285
|
+
// Tiến trình host riêng cho giao diện và cho Office COM (chỉ dựng khi lời gọi đầu tiên cần) — một lệnh COM treo / bị huỷ không làm mất snapshot giao diện.
|
|
286
|
+
const guiHost = guiProfile ? createWindowsHost() : null;
|
|
287
|
+
const officeHost = officeApps.length ? createWindowsHost() : null;
|
|
288
|
+
// Không nói cửa sổ mà focus đang ở linh vật (chủ máy vừa gõ vào ô hỏi) → cửa sổ họ đang dùng lúc hỏi (mascot/ask.mjs).
|
|
289
|
+
const gui = guiProfile ? createGuiController({
|
|
290
|
+
fullAccess, host: guiHost, say: (m) => say(chalk.magenta(m)),
|
|
291
|
+
defaultWindow: () => (mascot.pid() ? { avoid_pid: mascot.pid(), fallback: mascotChat?.userWindow()?.window } : null),
|
|
292
|
+
}) : null;
|
|
293
|
+
// Kho hoàn tác (xoá → thùng rác của kho, ghi đè → giữ bản cũ). Máy tính tổ chức: công cụ tệp chạy dưới tài khoản thành viên, không có kho.
|
|
294
|
+
const undo = multiUser ? null : createUndoStore();
|
|
295
|
+
void undo?.cleanup().catch(() => undefined);
|
|
296
|
+
const processes = createProcessManager();
|
|
297
|
+
// Giữ máy không tự ngủ khi đang có việc (keepAwake.mjs) — máy tính tổ chức (container) không cần.
|
|
298
|
+
const keepAwake = createKeepAwake({
|
|
299
|
+
enabled: !multiUser && options.keepAwake !== false && process.env.AIVIN_REMOTE_KEEP_AWAKE !== '0',
|
|
300
|
+
say: (m) => say(chalk.gray(` ${m}`)),
|
|
301
|
+
});
|
|
302
|
+
let procAwake = false;
|
|
303
|
+
const syncProcAwake = () => {
|
|
304
|
+
const running = !!processes.hasRunning?.();
|
|
305
|
+
if (running === procAwake) return;
|
|
306
|
+
procAwake = running;
|
|
307
|
+
if (running) keepAwake.hold();
|
|
308
|
+
else keepAwake.release();
|
|
309
|
+
};
|
|
310
|
+
const schedules = multiUser ? null : createScheduleManager({ undo });
|
|
311
|
+
// Sự kiện của theo dõi đi lên BE qua socket (đã nối) — `socket` được tạo ngay bên dưới, sự kiện chỉ có sau khi BE đặt danh sách.
|
|
312
|
+
const watches = multiUser ? null : createWatchManager({
|
|
313
|
+
roots, say: (m) => say(chalk.cyan(m)),
|
|
314
|
+
emit: (payload) => { if (socket?.connected) socket.emit(DeviceEvent.EVENT, payload); },
|
|
315
|
+
});
|
|
316
|
+
// Tệp lớn đi HTTP thẳng với vé của BE (fs.upload / fs.download) — máy tính tổ chức không có (gửi HTTP chạy bằng tài khoản của daemon).
|
|
317
|
+
const transfer = multiUser ? null : { serverUrl, deviceToken: () => creds.device_token };
|
|
318
|
+
// Ghi chú cuộc họp + chụp màn hình (meeting/) — Windows, máy cá nhân; tắt: --no-meetings / AIVIN_REMOTE_MEETINGS=0.
|
|
319
|
+
const media = !multiUser && mediaSupported() && options.meetings !== false && process.env.AIVIN_REMOTE_MEETINGS !== '0' ? createMediaHost() : null;
|
|
320
|
+
const meetings = media ? createMeetingManager({
|
|
321
|
+
roots, media, lang: mascotLang(process.env, process.platform, creds?.lang),
|
|
322
|
+
say: (m) => say(chalk.cyan(m)),
|
|
323
|
+
notify: showOSNotification,
|
|
324
|
+
isPaused: isRemotePaused,
|
|
325
|
+
keepAwake,
|
|
326
|
+
// Đang nói chuyện với linh vật → không ghi biên bản họp (và ngược lại, xem micBusy của mascotChat).
|
|
327
|
+
micBusy: () => !!mascotChat?.inCall(),
|
|
328
|
+
// Chuyển chữ từng đoạn qua chính `device:stt` của ô hỏi linh vật; mất mạng thì chờ nối lại (tối đa 10 phút) rồi mới báo lỗi.
|
|
329
|
+
stt: async (audio, lang) => {
|
|
330
|
+
const deadline = Date.now() + 10 * 60_000;
|
|
331
|
+
while (!socket?.connected) {
|
|
332
|
+
if (Date.now() > deadline) throw new Error('offline');
|
|
333
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
334
|
+
}
|
|
335
|
+
return socket.timeout(60_000).emitWithAck(DeviceEvent.STT, { audio, lang });
|
|
336
|
+
},
|
|
337
|
+
// Lượt chat sau họp: qua ô hỏi của linh vật (câu trả lời hiện ở đó); không có linh vật thì gửi thẳng.
|
|
338
|
+
followUp: async (text) => {
|
|
339
|
+
if (!socket?.connected) return { ok: false, error: 'offline' };
|
|
340
|
+
if (mascotChat) {
|
|
341
|
+
if (mascotChat.busy()) return { ok: false, error: 'busy' };
|
|
342
|
+
void mascotChat.ask(text);
|
|
343
|
+
return { ok: true };
|
|
344
|
+
}
|
|
345
|
+
const ack = await socket.timeout(15_000).emitWithAck(DeviceEvent.CHAT, { text, request_id: `meeting-${Date.now()}` });
|
|
346
|
+
return ack?.ok ? { ok: true } : { ok: false, error: ack?.error || 'failed' };
|
|
347
|
+
},
|
|
348
|
+
}) : null;
|
|
349
|
+
const env = { roots, binaries: profile.binaries, projects: profile.projects, fileIndex, browserTunnels, gui, office: officeApps.length ? { host: officeHost, apps: officeApps } : null, undo, processes, schedules, watches, transfer, meetings, media, clipboard: multiUser ? null : createClipboard() };
|
|
350
|
+
const host = multiUser ? createMultiUserHost({ baseEnv: env, say: (m) => say(chalk.gray(m)) }) : null;
|
|
351
|
+
host?.start();
|
|
352
|
+
const tools = buildTools(env);
|
|
353
|
+
const byName = toolMap(tools);
|
|
354
|
+
// Công cụ chủ máy tắt (`aivin remote policy deny`) không vào danh mục — Planner không lập kế hoạch với nó (gọi tới vẫn bị chặn ở sàn luật).
|
|
355
|
+
const deniedTools = new Set(policyGuard.read().deny_tools);
|
|
356
|
+
if (deniedTools.has('gui.act')) deniedTools.add('gui.do');
|
|
357
|
+
const { catalog, hash } = buildCatalog(tools.filter((t) => !deniedTools.has(t.name)));
|
|
358
|
+
const confirmer = multiUser ? null : createLocalConfirmer();
|
|
359
|
+
// Nhiều người dùng: thêm trần song song theo từng thành viên — một người không chiếm hết chỗ của cả tổ chức.
|
|
360
|
+
const scheduler = createScheduler(multiUser ? { scopeLimits: DEFAULT_SCOPE_LIMITS } : undefined);
|
|
361
|
+
// Linh vật trên màn hình (mascot/): việc chính đang làm + nhật ký chi tiết; nút tạm dừng = công tắc ngắt. Máy tính tổ chức: không có.
|
|
362
|
+
const mascot = createMascot({
|
|
363
|
+
enabled: !multiUser && options.mascot !== false && process.env.AIVIN_MASCOT !== '0', lang: creds?.lang,
|
|
364
|
+
onPause: () => setRemotePaused(true),
|
|
365
|
+
onResume: () => setRemotePaused(false),
|
|
366
|
+
say: (m) => say(chalk.gray(` ${m}`)),
|
|
367
|
+
// Ô hỏi của linh vật: gõ / nói → lượt chat trên Aivin qua socket của máy (mascot/ask.mjs, dựng sau khi có socket).
|
|
368
|
+
// Gõ khi Aivin đang hỏi lại → là câu trả lời; nút lựa chọn → trả lời đúng lựa chọn đó.
|
|
369
|
+
onAsk: (text, window) => { void mascotChat?.reply(text, window); },
|
|
370
|
+
onChoose: (id) => { void mascotChat?.choose(id); },
|
|
371
|
+
onCancel: () => { void mascotChat?.cancel(); },
|
|
372
|
+
onNewChat: () => { void mascotChat?.newChat(); },
|
|
373
|
+
onOpenTool: (msg) => { void mascotChat?.openTool(msg); },
|
|
374
|
+
onNotifyFreq: (val) => { mascotChat?.setNotifyFreq(val); },
|
|
375
|
+
// Thả tệp vào bot → đi kèm câu gõ kế tiếp.
|
|
376
|
+
onDrop: (files) => mascotChat?.attach(files),
|
|
377
|
+
// Bấm × trên chip tệp trong ô hỏi → bỏ tệp đó.
|
|
378
|
+
onDetach: (file) => mascotChat?.detach(file),
|
|
379
|
+
// Nói chuyện trực tiếp: mic / loa ở cửa sổ, phiên thoại realtime trên BE (mascot/ask.mjs).
|
|
380
|
+
onVoice: (msg) => {
|
|
381
|
+
if (!mascotChat) return;
|
|
382
|
+
if (msg.t === MascotHostEvent.VOICE_AUDIO) return mascotChat.voiceAudio(msg.audio);
|
|
383
|
+
if (msg.t === MascotHostEvent.VOICE_START) return void mascotChat.voiceStart(msg.window);
|
|
384
|
+
if (msg.t === MascotHostEvent.VOICE_INTERRUPT) return mascotChat.voiceInterrupt();
|
|
385
|
+
if (msg.t === MascotHostEvent.VOICE_STOP) return mascotChat.voiceStop();
|
|
386
|
+
if (msg.t === MascotHostEvent.VOICE_MIC_LOST) return mascotChat.voiceMicLost();
|
|
387
|
+
},
|
|
388
|
+
});
|
|
389
|
+
if (isRemotePaused()) mascot.paused(true);
|
|
390
|
+
const desktopCast = createDesktopCastManager();
|
|
391
|
+
// Công cụ GUI ghi của AI đang chạy → thao tác từ xa của người bị bỏ (và AI chờ người thôi thao tác trước khi bấm, xem handleCall).
|
|
392
|
+
let aiGuiBusy = 0;
|
|
393
|
+
const castGate = createCastInputGate({ isPaused: isRemotePaused, isAiBusy: () => aiGuiBusy > 0 });
|
|
394
|
+
let castBlockedNoticeAt = 0;
|
|
395
|
+
const emitCastStatus = (payload) => { if (socket?.connected) socket.emit(DeviceEvent.DESKTOP_CAST_STATUS, payload); };
|
|
396
|
+
/** Thao tác từ xa (qua máy chủ hoặc kênh WebRTC) — qua cổng chặn rồi mới xuống tiến trình điều khiển. */
|
|
397
|
+
const applyRemoteInput = (raw, viewerId) => {
|
|
398
|
+
const sessionId = desktopCast.sessionId();
|
|
399
|
+
if (!sessionId || (raw?.session_id && raw.session_id !== sessionId)) return;
|
|
400
|
+
const res = castGate.accept(raw);
|
|
401
|
+
if (res.ok) return desktopCast.sendInput(res.cmd);
|
|
402
|
+
if (res.reason !== CastInputRejection.AI_ACTIVE || Date.now() - castBlockedNoticeAt < 2000) return;
|
|
403
|
+
castBlockedNoticeAt = Date.now();
|
|
404
|
+
emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.INPUT_BLOCKED, reason: res.reason });
|
|
405
|
+
};
|
|
406
|
+
// WebRTC chạy ở tiến trình con (thư viện native sập lúc thoát — xem webrtcWorker.mjs), daemon chỉ chuyển tín hiệu / thao tác / JPEG.
|
|
407
|
+
const desktopWebRtc = createDesktopWebRtcWorker({
|
|
408
|
+
command: cliLaunchCommand(),
|
|
409
|
+
emitSignal: (payload) => { if (socket?.connected) socket.emit(DeviceEvent.DESKTOP_CAST_SIGNAL, payload); },
|
|
410
|
+
emitStatus: emitCastStatus,
|
|
411
|
+
onInput: (raw, viewerId) => applyRemoteInput(raw, viewerId),
|
|
412
|
+
// Người xem vừa nối: gửi ngay một khung (màn hình đứng yên thì bộ quay không tự gửi).
|
|
413
|
+
onPeerReady: () => desktopCast.refresh(),
|
|
414
|
+
onState: () => syncCastJpeg(),
|
|
415
|
+
log: (m) => say(chalk.gray(` ${m}`)),
|
|
416
|
+
});
|
|
417
|
+
/**
|
|
418
|
+
* Chỉ nén JPEG khi còn người xem cần: chưa có WebRTC / không có video, hoặc khung thô chưa tới bộ mã hoá (pipe chưa nối).
|
|
419
|
+
* Con trỏ tách khỏi khung chỉ khi mọi người xem đều có video + tự vẽ con trỏ (FE cũ, đường JPEG vẫn thấy con trỏ trong hình).
|
|
420
|
+
*/
|
|
421
|
+
const syncCastJpeg = () => {
|
|
422
|
+
const jpeg = desktopWebRtc.needsJpeg() || !desktopWebRtc.videoLive();
|
|
423
|
+
desktopCast.setJpeg(jpeg);
|
|
424
|
+
desktopCast.setCursorInFrame(jpeg || !desktopWebRtc.localCursor());
|
|
425
|
+
};
|
|
426
|
+
/** Dừng hẳn phiên trên máy (tạm dừng / mất kết nối / tắt daemon); `notify` = báo BE kết thúc phiên. */
|
|
427
|
+
const stopDesktopCast = (reason, notify = true) => {
|
|
428
|
+
const sessionId = desktopCast.sessionId();
|
|
429
|
+
desktopWebRtc.closeAll();
|
|
430
|
+
if (!desktopCast.isActive()) return;
|
|
431
|
+
desktopCast.stop();
|
|
432
|
+
// Nhật ký trên máy của chủ máy: phiên xem + số thao tác đã nhận (cả qua WebRTC, không qua máy chủ).
|
|
433
|
+
logActivity({ type: 'desktop_cast', id: sessionId, reason, inputs: castGate.takeAcceptedCount() });
|
|
434
|
+
if (notify && sessionId) emitCastStatus({ session_id: sessionId, state: CastState.STOPPED, reason, final: true });
|
|
435
|
+
};
|
|
436
|
+
let mascotChat = null;
|
|
437
|
+
|
|
438
|
+
say(chalk.blue('💻 Aivin Device Agent — máy này nhận việc từ agent của bạn'));
|
|
439
|
+
say(chalk.gray(` Máy: ${creds.name} (${creds.device_id})`));
|
|
440
|
+
say(chalk.gray(fullAccess ? ` Quyền: TOÀN QUYỀN máy (${roots.slice(1).join(' ')}) — trừ thư mục cấu hình Aivin` : ` Thư mục: ${roots.join(' | ')}`));
|
|
441
|
+
say(chalk.gray(` Máy chủ: ${serverUrl}`));
|
|
442
|
+
if (creds.seal_failed) say(chalk.yellow(` ⚠️ Token máy đang nằm trong tệp thường (kho bí mật của hệ điều hành lỗi: ${creds.seal_failed.reason}) — chép thư mục .aivin là mang theo được quyền điều khiển máy`));
|
|
443
|
+
if (proxy.url) say(chalk.gray(` Proxy: ${proxy.url} (${proxy.source === 'system' ? 'cài đặt của hệ điều hành' : proxy.source === 'env' ? 'HTTPS_PROXY' : '--proxy'})`));
|
|
444
|
+
else if (proxy.pac) say(chalk.yellow(` Proxy: máy dùng tệp PAC (${proxy.pac}) — Aivin chưa đọc được, nếu không nối được hãy thêm --proxy http://<máy>:<cổng>`));
|
|
445
|
+
say(chalk.gray(` Công cụ: ${catalog.length} (${profile.binaries.join(', ') || 'không phát hiện chương trình nào'})`));
|
|
446
|
+
say(chalk.gray(` Ghi nhớ: ${memoryStats().total} mục — ${memoryStats().dir}`));
|
|
447
|
+
if (officeApps.length) say(chalk.gray(` Office: ${officeApps.join(', ')} — AI làm qua ứng dụng, chạy nền`));
|
|
448
|
+
say(chalk.gray(` Giao diện: ${gui ? 'AI điều khiển được cửa sổ ứng dụng (di chuột / gõ phím để AI dừng; tắt: --no-gui)' : 'không (chỉ Windows, tắt bằng --no-gui)'}`));
|
|
449
|
+
say(chalk.gray(` Trình duyệt: ${!browser ? 'không có Chrome / Edge — AI dùng trình duyệt trên máy chủ'
|
|
450
|
+
: useDailyBrowser ? `${browser.name} hằng ngày của bạn nếu đã bật ${remoteDebuggingPage(browser.id)}, không thì cửa sổ riêng của Aivin`
|
|
451
|
+
: `${browser.name} (cửa sổ riêng của Aivin)`}`));
|
|
452
|
+
say(chalk.gray(` Cuộc họp: ${meetings ? 'AI ghi chú được cuộc họp (âm thanh máy + micro, bạn bấm Cho phép mỗi lần) và chụp màn hình; tắt: --no-meetings' : 'không (chỉ Windows)'}`));
|
|
453
|
+
if (isRemotePaused()) say(chalk.yellow(' ⏸ Đang TẠM DỪNG (aivin remote resume để nhận việc lại)'));
|
|
454
|
+
// `aivin remote meeting start|stop` gõ ở máy → daemon này; buổi ghi / biên bản dở từ lần chạy trước → làm nốt.
|
|
455
|
+
const stopMeetingRequests = meetings ? watchMeetingRequests(meetings) : null;
|
|
456
|
+
|
|
457
|
+
void gui?.prewarm?.();
|
|
458
|
+
fileIndex?.build()
|
|
459
|
+
.then((s) => { say(chalk.gray(` Chỉ mục tệp: ${s.files} tệp (${s.updated} cập nhật, ${s.ms} ms)`)); fileIndex.watch(); })
|
|
460
|
+
.catch((e) => say(chalk.yellow(` ⚠️ Lập chỉ mục tệp lỗi: ${e.message}`)));
|
|
461
|
+
|
|
462
|
+
// Mã phiên chạy của tiến trình này: BE báo socket cũ "bị thay bởi instance X" — chỉ dừng khi X là tiến trình KHÁC (tự nối lại
|
|
463
|
+
// sau khi mạng chập chờn thì không dừng nhầm).
|
|
464
|
+
const instance = randomUUID();
|
|
465
|
+
const socket = io(`${serverUrl}${DEVICE_NAMESPACE}`, {
|
|
466
|
+
auth: { device_token: creds.device_token, protocol: PROTOCOL_VERSION, instance },
|
|
467
|
+
transports: ['websocket'],
|
|
468
|
+
// Proxy công ty (netProxy.mjs): websocket đi qua đường hầm CONNECT; không có proxy → `undefined`, nối thẳng.
|
|
469
|
+
agent: proxyAgentFor(`${serverUrl}${DEVICE_NAMESPACE}`),
|
|
470
|
+
reconnection: true,
|
|
471
|
+
reconnectionDelay: 1000,
|
|
472
|
+
reconnectionDelayMax: multiUser ? MULTI_USER_RECONNECT_DELAY_MAX_MS : RECONNECT_DELAY_MAX_MS,
|
|
473
|
+
randomizationFactor: 0.5,
|
|
474
|
+
});
|
|
475
|
+
|
|
476
|
+
let stopped = false;
|
|
477
|
+
// Lời gọi đang xử lý (kể cả lúc chờ người bấm xác nhận trên máy) — tự cập nhật chỉ chạy lại daemon khi bằng 0.
|
|
478
|
+
let activeCalls = 0;
|
|
479
|
+
let lastActivityAt = Date.now();
|
|
480
|
+
let updater = null;
|
|
481
|
+
// Bản vừa tự cập nhật chạy đủ 10 phút không sập → xác nhận, bỏ bản cũ giữ để tự lùi.
|
|
482
|
+
const confirmTimer = selfManaged ? setTimeout(() => { try { confirmUpdate(); } catch { /* lần sau */ } }, UPDATE_CONFIRM_AFTER_MS) : null;
|
|
483
|
+
confirmTimer?.unref?.();
|
|
484
|
+
// Cloud Computer: `busy` = còn tiến trình nền đang chạy → BE giữ máy không tắt vì rảnh (có trần giờ phía BE).
|
|
485
|
+
const heartbeat = setInterval(() => {
|
|
486
|
+
if (socket.connected) socket.emit(DeviceEvent.HEARTBEAT, multiUser ? { busy: processes.hasRunning() } : {});
|
|
487
|
+
ledger.prune();
|
|
488
|
+
// Kết quả đã gửi mà lỡ ack (BE quá tải) khi socket vẫn nối → gửi lại có giãn nhịp, cùng call_id (callLedger.dueForResend, 02/11/2026).
|
|
489
|
+
if (socket.connected && serverResume) ledger.dueForResend().forEach(sendResult);
|
|
490
|
+
syncProcAwake();
|
|
491
|
+
}, HEARTBEAT_MS);
|
|
492
|
+
|
|
493
|
+
// `aivin remote pause` ở cửa sổ khác: huỷ NGAY việc đang chạy (lệnh shell, đường hầm trình duyệt), không chỉ chặn việc mới.
|
|
494
|
+
let pausedSeen = isRemotePaused();
|
|
495
|
+
const pauseWatch = setInterval(() => {
|
|
496
|
+
const paused = isRemotePaused();
|
|
497
|
+
if (paused && !pausedSeen) {
|
|
498
|
+
say(chalk.yellow('⏸ Đã tạm dừng — huỷ việc đang chạy và đóng trình duyệt AI đang dùng.'));
|
|
499
|
+
void scheduler.cancelAll('Remote control was paused on this device');
|
|
500
|
+
cancelGating([...gating.keys()]);
|
|
501
|
+
browserTunnels?.closeAll();
|
|
502
|
+
guiHost?.close();
|
|
503
|
+
officeHost?.close();
|
|
504
|
+
processes.stopAll();
|
|
505
|
+
// Công tắc ngắt chặn cả xem / điều khiển màn hình từ web, không chỉ việc của AI.
|
|
506
|
+
stopDesktopCast('paused');
|
|
507
|
+
}
|
|
508
|
+
if (paused !== pausedSeen) mascot.paused(paused);
|
|
509
|
+
pausedSeen = paused;
|
|
510
|
+
}, PAUSE_POLL_MS);
|
|
511
|
+
pauseWatch.unref?.();
|
|
512
|
+
|
|
513
|
+
// Sổ lời gọi (callLedger.mjs): kết quả làm xong lúc mất kết nối giữ trên đĩa, gửi khi nối lại (BE vẫn chờ tới hết giờ — mất là agent chạy
|
|
514
|
+
// lại lệnh có tác dụng phụ); lời gọi BE gửi lại cùng `call_id` không chạy lần hai.
|
|
515
|
+
const ledger = createCallLedger({ file: options.outboxFile || REMOTE_OUTBOX_FILE });
|
|
516
|
+
// BE có `resume`: kết quả chỉ bỏ khỏi sổ khi BE xác nhận đã nhận (ack của device:result). BE cũ không ack → gửi là coi như xong.
|
|
517
|
+
let serverResume = false;
|
|
518
|
+
const sendResult = (payload) => {
|
|
519
|
+
if (!socket.connected) return ledger.persist();
|
|
520
|
+
if (!serverResume) {
|
|
521
|
+
socket.emit(DeviceEvent.RESULT, payload);
|
|
522
|
+
return ledger.markSent(payload.call_id);
|
|
523
|
+
}
|
|
524
|
+
ledger.markAttempt(payload.call_id);
|
|
525
|
+
socket.timeout(RESULT_ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.RESULT, payload)
|
|
526
|
+
.then(() => ledger.markSent(payload.call_id), () => ledger.persist());
|
|
527
|
+
};
|
|
528
|
+
const flushUnsent = () => {
|
|
529
|
+
for (const payload of ledger.unsent()) {
|
|
530
|
+
if (!socket.connected) return;
|
|
531
|
+
sendResult(payload);
|
|
532
|
+
}
|
|
533
|
+
};
|
|
534
|
+
|
|
535
|
+
const stop = () => {
|
|
536
|
+
if (stopped) return;
|
|
537
|
+
stopped = true;
|
|
538
|
+
clearInterval(heartbeat);
|
|
539
|
+
clearInterval(pauseWatch);
|
|
540
|
+
clearTimeout(confirmTimer);
|
|
541
|
+
updater?.close();
|
|
542
|
+
mascot.close();
|
|
543
|
+
if (selfManaged) noteCleanExit();
|
|
544
|
+
const draining = scheduler.cancelAll('The Aivin agent on this device stopped');
|
|
545
|
+
cancelGating([...gating.keys()]);
|
|
546
|
+
ledger.persist({ sync: true });
|
|
547
|
+
socket.disconnect();
|
|
548
|
+
browserTunnels?.closeAll();
|
|
549
|
+
// Đóng tệp ghi họp cho đúng; biên bản làm ở lần chạy sau (meetings.recover).
|
|
550
|
+
stopMeetingRequests?.();
|
|
551
|
+
void meetings?.shutdown();
|
|
552
|
+
gui?.close();
|
|
553
|
+
guiHost?.close();
|
|
554
|
+
officeHost?.close();
|
|
555
|
+
stopDesktopCast('device_stopped');
|
|
556
|
+
processes.stopAll();
|
|
557
|
+
keepAwake.close();
|
|
558
|
+
watches?.closeAll();
|
|
559
|
+
host?.close();
|
|
560
|
+
fileIndex?.close();
|
|
561
|
+
stopWatchingMemory();
|
|
562
|
+
releaseLock();
|
|
563
|
+
say(chalk.gray('🛑 Đã dừng nhận việc từ xa.'));
|
|
564
|
+
return draining;
|
|
565
|
+
};
|
|
566
|
+
|
|
567
|
+
// Dừng hẳn (thu hồi / bị thay / token hết hiệu lực): thoát mã 0 — trình giữ chạy (Task Scheduler, launchd, systemd) không chạy lại.
|
|
568
|
+
const stopForGood = () => {
|
|
569
|
+
const draining = stop();
|
|
570
|
+
if (options.handleSignals !== false) Promise.resolve(draining).finally(() => process.exit(0));
|
|
571
|
+
};
|
|
572
|
+
|
|
573
|
+
// Tự cập nhật (autoUpdate.mjs): tệp chạy đóng gói + bản npm (chỉ nhắc). Máy tính tổ chức: tắt.
|
|
574
|
+
updater = createAutoUpdater({
|
|
575
|
+
enabled: autoUpdateEnabled,
|
|
576
|
+
// Chỉ tự thoát để chuyển bản khi chắc có trình giữ chạy mở lại (detectSupervisor) — không thì chỉ nhắc.
|
|
577
|
+
supervised: !!supervisor && options.handleSignals !== false,
|
|
578
|
+
deviceId: creds.device_id,
|
|
579
|
+
// Đang ghi họp / làm biên bản: không tự khởi động lại để cập nhật (mất đoạn ghi).
|
|
580
|
+
isIdle: () => activeCalls === 0 && !processes.hasRunning?.() && !(browserTunnels?.liveCount() > 0) && !meetings?.busy(),
|
|
581
|
+
lastActivityAt: () => lastActivityAt,
|
|
582
|
+
say: (m) => say(chalk.cyan(m)),
|
|
583
|
+
onRestart: async (version) => {
|
|
584
|
+
logActivity({ type: 'self_update', version });
|
|
585
|
+
console.log(chalk.cyan(`⬆ Chuyển sang aivin ${version} — khởi động lại.`));
|
|
586
|
+
// Báo máy chủ trước khi rớt: máy sắp quay lại (không phải mất máy) — BE cũ không biết sự kiện này, hết 2 s thì thôi.
|
|
587
|
+
if (socket.connected) {
|
|
588
|
+
await socket.timeout(RESTARTING_ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.RESTARTING, { reason: 'update', version, expect_back_ms: RESTART_EXPECT_BACK_MS }).catch(() => null);
|
|
589
|
+
}
|
|
590
|
+
Promise.resolve(stop()).finally(() => process.exit(RESTART_EXIT_CODE));
|
|
591
|
+
},
|
|
592
|
+
});
|
|
593
|
+
|
|
594
|
+
const embedTexts = async (texts) => {
|
|
595
|
+
if (!socket.connected) return null;
|
|
596
|
+
const res = await socket.timeout(EMBED_TIMEOUT_MS).emitWithAck(DeviceEvent.EMBED, { texts });
|
|
597
|
+
return res?.ok ? res.vectors : null;
|
|
598
|
+
};
|
|
599
|
+
|
|
600
|
+
/**
|
|
601
|
+
* Xoay vòng token (BE cấp trong ack của HELLO): lưu token mới (kho bí mật của hệ điều hành) RỒI mới báo BE bỏ token cũ — lưu hỏng thì
|
|
602
|
+
* không báo, token cũ vẫn dùng được. Lần nối lại sau dùng token mới (socket.io đọc lại `auth` mỗi lần nối).
|
|
603
|
+
*/
|
|
604
|
+
const rotateToken = async (token) => {
|
|
605
|
+
const previous = creds.device_token;
|
|
606
|
+
try {
|
|
607
|
+
// Giữ token cũ tới khi máy chủ xác nhận (tokenRotation.mjs) — 02/11/2026.
|
|
608
|
+
const fallback = saveDeviceCredentials({ ...creds, device_token: token }, { previousToken: previous });
|
|
609
|
+
if (fallback) say(chalk.yellow(` ⚠️ Kho bí mật của máy lỗi (${fallback}) — token mới nằm trong tệp thường`));
|
|
610
|
+
// Đọc lại thật từ tệp + kho bí mật (không qua bộ nhớ đệm): ghi hỏng mà vẫn báo BE là lần khởi động sau máy bị khoá ngoài.
|
|
611
|
+
if (readStoredTokenFresh() !== token) throw new Error('saved token does not read back');
|
|
612
|
+
} catch (e) {
|
|
613
|
+
try { saveDeviceCredentials({ ...creds, device_token: previous }, { previousToken: null }); } catch { /* giữ nguyên tệp */ }
|
|
614
|
+
say(chalk.yellow(` ⚠️ Không lưu được token mới (${e.message}) — tiếp tục dùng token cũ`));
|
|
615
|
+
return;
|
|
616
|
+
}
|
|
617
|
+
creds.device_token = token;
|
|
618
|
+
socket.auth = { ...socket.auth, device_token: token };
|
|
619
|
+
// Gửi kèm chính token mới: BE chỉ chốt khi băm của nó đúng token đang chờ (chứng minh máy này nhận được token đó).
|
|
620
|
+
const ack = await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.ROTATED, { token }).catch(() => null);
|
|
621
|
+
if (ack?.ok === true) settleRotation(token);
|
|
622
|
+
logActivity({ type: 'token_rotated', deviceId: creds.device_id, confirmed: ack?.ok === true });
|
|
623
|
+
say(chalk.gray(ack?.ok
|
|
624
|
+
? ' 🔑 Đã đổi token máy định kỳ (token cũ hết hiệu lực)'
|
|
625
|
+
: ' 🔑 Đã lưu token mới — máy chủ chưa xác nhận, sẽ chốt ở lần nối lại'));
|
|
626
|
+
};
|
|
627
|
+
|
|
628
|
+
const announce = async () => {
|
|
629
|
+
try {
|
|
630
|
+
if (!multiUser) profile.update = updateProfile({ enabled: autoUpdateEnabled });
|
|
631
|
+
const hello = await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.HELLO, { protocol: PROTOCOL_VERSION, profile, catalog_hash: hash, inflight: ledger.heldIds() });
|
|
632
|
+
const userLang = hello?.user_lang || hello?.lang;
|
|
633
|
+
if (userLang && mascot.enabled) {
|
|
634
|
+
const resolvedLang = mascotLang(process.env, process.platform, userLang);
|
|
635
|
+
if (resolvedLang !== mascot.lang) {
|
|
636
|
+
mascot.setLang(resolvedLang);
|
|
637
|
+
mascotChat?.setLang(resolvedLang);
|
|
638
|
+
if (creds && creds.lang !== resolvedLang) {
|
|
639
|
+
creds.lang = resolvedLang;
|
|
640
|
+
saveDeviceCredentials(creds);
|
|
641
|
+
}
|
|
642
|
+
}
|
|
643
|
+
}
|
|
644
|
+
serverResume = Array.isArray(hello?.features) && hello.features.includes(ServerFeature.RESUME);
|
|
645
|
+
mascotChat?.setServerFeatures(hello?.features);
|
|
646
|
+
// Báo chủ động lỡ trong lúc offline + câu hỏi đang ghim đã đóng ở nơi khác (BE có hộp báo).
|
|
647
|
+
void mascotChat?.syncInbox();
|
|
648
|
+
// Việc máy còn giữ mà BE không còn chờ (đã huỷ / hết giờ lúc máy mất mạng — lệnh huỷ không tới được máy): dừng ngay, bỏ kết quả.
|
|
649
|
+
const orphaned = Array.isArray(hello?.orphaned) ? hello.orphaned.filter((id) => typeof id === 'string') : [];
|
|
650
|
+
if (orphaned.length) {
|
|
651
|
+
say(chalk.gray(` ↯ Huỷ ${orphaned.length} việc máy chủ không còn chờ (đã huỷ / hết giờ lúc mất kết nối)`));
|
|
652
|
+
scheduler.cancel(orphaned);
|
|
653
|
+
cancelGating(orphaned);
|
|
654
|
+
ledger.drop(orphaned);
|
|
655
|
+
}
|
|
656
|
+
if (!envCreds) settleRotation(creds.device_token); // chào được bằng token đang dùng → bỏ token cũ còn giữ (nếu có)
|
|
657
|
+
if (typeof hello?.rotate_token === 'string' && !envCreds) await rotateToken(hello.rotate_token);
|
|
658
|
+
// BE cần bản CLI tối thiểu (tính năng mới phía máy) → kiểm cập nhật ngay thay vì chờ tới lượt.
|
|
659
|
+
if (hello?.cli) updater?.setServerHints(hello.cli);
|
|
660
|
+
if (hello?.need_catalog) await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.CATALOG, { catalog_hash: hash, tools: catalog });
|
|
661
|
+
// BE mới tính vector cho tệp tài liệu (tìm theo nghĩa); BE cũ không báo → chỉ tìm theo từ khoá.
|
|
662
|
+
if (fileIndex && Array.isArray(hello?.features) && hello.features.includes(ServerFeature.EMBED)) fileIndex.setEmbedder(embedTexts);
|
|
663
|
+
// Theo dõi của máy (BE giữ) — nối lại sau khi mất mạng / khởi động lại daemon thì mở lại đúng danh sách.
|
|
664
|
+
if (watches && Array.isArray(hello?.features) && hello.features.includes(ServerFeature.WATCH)) {
|
|
665
|
+
const res = await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.WATCHES, {}).catch(() => null);
|
|
666
|
+
if (Array.isArray(res?.watches)) watches.set(res.watches);
|
|
667
|
+
}
|
|
668
|
+
say(chalk.green('✅ Đã kết nối — sẵn sàng nhận việc.'));
|
|
669
|
+
mascot.connected();
|
|
670
|
+
logActivity({ type: 'connected', serverUrl, deviceId: creds.device_id });
|
|
671
|
+
} catch (e) {
|
|
672
|
+
say(chalk.yellow(`⚠️ Chào máy chủ lỗi (${e.message}) — sẽ thử lại khi nối lại.`));
|
|
673
|
+
}
|
|
674
|
+
};
|
|
675
|
+
|
|
676
|
+
// Nhiều người dùng: stdout vào log docker của máy chủ → không in tham số / thông báo lỗi (đường tệp, nội dung của thành viên), chỉ
|
|
677
|
+
// tên công cụ + vài ký tự đầu của vùng.
|
|
678
|
+
const callLabel = (call) => (host ? `${call.tool} [${String(call.user_scope || '-').slice(0, 5)}]` : call.tool);
|
|
679
|
+
|
|
680
|
+
/**
|
|
681
|
+
* Sàn luật tại máy: công cụ / lệnh chủ máy cấm → ném lỗi; việc cần xác nhận → hộp "Cho phép / Từ chối" trên máy (BE được báo giữ chỗ để
|
|
682
|
+
* không tính hết giờ trong lúc chờ). Máy tính tổ chức: chỉ áp phần cấm (không có người ngồi trước máy để bấm).
|
|
683
|
+
*/
|
|
684
|
+
// Lời gọi đang chờ người bấm xác nhận (chưa vào scheduler nên `scheduler.cancel` không chạm tới): huỷ từ BE / việc mồ côi / tạm dừng /
|
|
685
|
+
// dừng daemon phải đóng hộp ở đây — trước đây hộp vẫn chờ, người bấm "Cho phép" muộn là lệnh chạy dù BE đã thôi chờ (29/10/2026).
|
|
686
|
+
const gating = new Map();
|
|
687
|
+
const cancelGating = (callIds) => {
|
|
688
|
+
for (const id of callIds) gating.get(id)?.abort();
|
|
689
|
+
};
|
|
690
|
+
|
|
691
|
+
const localGate = async (call, tool) => {
|
|
692
|
+
// Công cụ nội bộ cũng qua sàn luật (phần cấm luôn áp; phần hỏi do evaluateLocalPolicy miễn) — 02/11/2026.
|
|
693
|
+
const policy = policyGuard.read();
|
|
694
|
+
const verdict = evaluateLocalPolicy(policy, tool, call.args || {});
|
|
695
|
+
if (verdict.action !== 'confirm' || !confirmer) return;
|
|
696
|
+
const timeoutSec = policy.confirm_timeout_sec;
|
|
697
|
+
const hold = (extraMs, phase = HoldPhase.WAITING) => { if (socket.connected) socket.emit(DeviceEvent.HOLD, { call_id: call.call_id, extra_ms: extraMs, phase }); };
|
|
698
|
+
hold((timeoutSec + 15) * 1000);
|
|
699
|
+
say(chalk.magenta(` ✋ ${call.tool}: chờ bạn bấm xác nhận trên máy (${verdict.reason}, tối đa ${timeoutSec} s)`));
|
|
700
|
+
const purpose = typeof call.purpose === 'string' ? call.purpose.slice(0, 200) : undefined;
|
|
701
|
+
const controller = new AbortController();
|
|
702
|
+
gating.set(call.call_id, controller);
|
|
703
|
+
let result;
|
|
704
|
+
mascot.waitingConfirm(call, tool);
|
|
705
|
+
try {
|
|
706
|
+
result = await confirmer.ask({
|
|
707
|
+
reason: verdict.reason, purpose, detail: describeCall(tool, call.args || {}), timeoutSec, signal: controller.signal,
|
|
708
|
+
// Hộp xếp hàng sau hộp khác: phần đã chờ chưa nằm trong lần xin lùi hạn đầu → xin thêm đúng phần đó.
|
|
709
|
+
onStart: (queuedMs) => { if (queuedMs > 1000) hold(queuedMs); },
|
|
710
|
+
});
|
|
711
|
+
} finally {
|
|
712
|
+
gating.delete(call.call_id);
|
|
713
|
+
}
|
|
714
|
+
logActivity({ type: 'local_confirm', tool: call.tool, id: call.call_id, result });
|
|
715
|
+
mascot.confirmDone(call, result === ConfirmResult.ALLOW);
|
|
716
|
+
// Bấm "Cho phép" đúng lúc chủ máy vừa tạm dừng → không chạy.
|
|
717
|
+
if (result === ConfirmResult.ALLOW && isRemotePaused()) throw new DeviceToolError(DeviceErrorCode.KILL_SWITCH, 'Remote control is paused on this device');
|
|
718
|
+
if (result === ConfirmResult.ALLOW) return hold(0, HoldPhase.STARTED);
|
|
719
|
+
const fail = {
|
|
720
|
+
[ConfirmResult.REJECT]: [DeviceErrorCode.LOCAL_REJECTED, 'The person at this computer rejected this step'],
|
|
721
|
+
[ConfirmResult.TIMEOUT]: [DeviceErrorCode.LOCAL_CONFIRM_TIMEOUT, `Nobody confirmed this step on the computer within ${timeoutSec} s — it needs a click at the computer (the owner requires it for risky steps)`],
|
|
722
|
+
[ConfirmResult.UNAVAILABLE]: [DeviceErrorCode.LOCAL_CONFIRM_UNAVAILABLE, 'This step needs a confirmation at the computer, but no confirmation box could be shown there'],
|
|
723
|
+
[ConfirmResult.CANCELLED]: [DeviceErrorCode.CANCELLED, 'Cancelled while waiting for a confirmation at the computer — the step did not run'],
|
|
724
|
+
}[result];
|
|
725
|
+
throw new DeviceToolError(fail[0], fail[1]);
|
|
726
|
+
};
|
|
727
|
+
|
|
728
|
+
const runCall = async (call, streamer, hooks) => {
|
|
729
|
+
const tool = byName.get(call.tool);
|
|
730
|
+
if (isRemotePaused()) return { tool, outcome: { ok: false, error: 'Remote control is paused on this device', error_code: DeviceErrorCode.KILL_SWITCH, duration_ms: 0 } };
|
|
731
|
+
if (!tool) return { tool, outcome: { ok: false, error: `Unknown tool: ${call.tool}`, error_code: DeviceErrorCode.TOOL_UNKNOWN, duration_ms: 0 } };
|
|
732
|
+
if (!tool.internal) say(chalk.yellow(`⚡ ${callLabel(call)}`), ...(host ? [] : [chalk.gray(JSON.stringify(call.args || {}).slice(0, 160))]));
|
|
733
|
+
let callEnv = env;
|
|
734
|
+
try {
|
|
735
|
+
if (host) {
|
|
736
|
+
callEnv = host.envFor(call.user_scope);
|
|
737
|
+
host.assertQuota(call.tool);
|
|
738
|
+
}
|
|
739
|
+
await localGate(call, tool);
|
|
740
|
+
} catch (e) {
|
|
741
|
+
return { tool, outcome: { ok: false, error: e.message, error_code: e.code || DeviceErrorCode.INVALID_ARGS, duration_ms: 0 } };
|
|
742
|
+
}
|
|
743
|
+
hooks?.started?.();
|
|
744
|
+
// Máy tính tổ chức: công cụ tệp chạy trong tiến trình của thành viên, không chạy bằng root (xem memberFsPool.mjs).
|
|
745
|
+
const handler = host?.runsInWorker(call.tool)
|
|
746
|
+
? (args, ctx) => host.runFs(call.user_scope, call.tool, args, ctx)
|
|
747
|
+
: (args, ctx) => tool.handler(args, ctx, callEnv);
|
|
748
|
+
const outcome = boundedResult(await scheduler.run(
|
|
749
|
+
call,
|
|
750
|
+
{ group: tool.group, lockKeys: tool.lockKeys ? (a) => tool.lockKeys(a, callEnv) : undefined },
|
|
751
|
+
handler,
|
|
752
|
+
{ onOutput: streamer.push },
|
|
753
|
+
));
|
|
754
|
+
return { tool, outcome };
|
|
755
|
+
};
|
|
756
|
+
|
|
757
|
+
// Chống làm trùng khi BE gửi lại lô bước dở (xem idempotency.mjs).
|
|
758
|
+
const runOnce = createIdempotentRunner(runCall, (name) => !!byName.get(name)?.read_only, {
|
|
759
|
+
file: options.idemFile || REMOTE_IDEM_FILE,
|
|
760
|
+
deferStart: true,
|
|
761
|
+
onDuplicate: (call) => say(chalk.gray(` ↺ ${callLabel(call)}: đã làm ở lần gửi trước — trả lại kết quả cũ`)),
|
|
762
|
+
});
|
|
763
|
+
|
|
764
|
+
/** Không bao giờ ném / để lọt promise bị từ chối: lỗi bất ngờ vẫn trả kết quả lỗi cho BE. */
|
|
765
|
+
const handleCall = async (call) => {
|
|
766
|
+
const streamer = createStreamer(socket, call.call_id);
|
|
767
|
+
let tool;
|
|
768
|
+
let outcome;
|
|
769
|
+
activeCalls++;
|
|
770
|
+
lastActivityAt = Date.now();
|
|
771
|
+
mascot.callStarted(call, byName.get(call.tool));
|
|
772
|
+
keepAwake.hold();
|
|
773
|
+
const def = byName.get(call.tool);
|
|
774
|
+
const guiWrite = def?.group === ToolGroup.GUI && !def?.read_only;
|
|
775
|
+
try {
|
|
776
|
+
if (guiWrite) {
|
|
777
|
+
// Người đang điều khiển từ web → AI chờ người thôi tay (tối đa 3 s) rồi mới bấm; trong lúc AI bấm, thao tác từ web bị bỏ.
|
|
778
|
+
await castGate.waitHumanIdle();
|
|
779
|
+
aiGuiBusy++;
|
|
780
|
+
}
|
|
781
|
+
({ tool, outcome } = await runOnce(call, streamer));
|
|
782
|
+
} catch (e) {
|
|
783
|
+
outcome = { ok: false, error: e?.message || String(e), error_code: e?.code || DeviceErrorCode.EXECUTION_FAILED, duration_ms: 0 };
|
|
784
|
+
} finally {
|
|
785
|
+
if (guiWrite) aiGuiBusy--;
|
|
786
|
+
keepAwake.release();
|
|
787
|
+
syncProcAwake();
|
|
788
|
+
}
|
|
789
|
+
try {
|
|
790
|
+
streamer.flush();
|
|
791
|
+
const payload = { call_id: call.call_id, ...outcome };
|
|
792
|
+
ledger.finish(call.call_id, payload, { persistNow: !socket.connected });
|
|
793
|
+
sendResult(payload);
|
|
794
|
+
logActivity({ type: 'tool_call', tool: call.tool, id: call.call_id, success: outcome.ok, error: outcome.error, ms: outcome.duration_ms });
|
|
795
|
+
if (!tool?.internal) {
|
|
796
|
+
const failed = host ? outcome.error_code : outcome.error;
|
|
797
|
+
say(outcome.ok ? chalk.green(` ✓ ${callLabel(call)} (${outcome.duration_ms} ms)`) : chalk.red(` ✗ ${callLabel(call)}: ${failed}`));
|
|
798
|
+
}
|
|
799
|
+
} catch (e) {
|
|
800
|
+
console.error(chalk.red(`⚠️ Gửi kết quả ${call.tool} lỗi: ${e?.message || e}`));
|
|
801
|
+
} finally {
|
|
802
|
+
activeCalls--;
|
|
803
|
+
lastActivityAt = Date.now();
|
|
804
|
+
mascot.callFinished(call, tool, outcome);
|
|
805
|
+
}
|
|
806
|
+
};
|
|
807
|
+
|
|
808
|
+
/** Bọc trình xử lý sự kiện socket: một gói hỏng không được làm sập daemon (socket.io không bắt lỗi trong listener). */
|
|
809
|
+
const guarded = (event, fn) => (...args) => {
|
|
810
|
+
try {
|
|
811
|
+
const r = fn(...args);
|
|
812
|
+
if (r && typeof r.catch === 'function') r.catch((e) => console.error(chalk.red(`⚠️ Xử lý ${event} lỗi: ${e?.message || e}`)));
|
|
813
|
+
} catch (e) {
|
|
814
|
+
console.error(chalk.red(`⚠️ Xử lý ${event} lỗi: ${e?.message || e}`));
|
|
815
|
+
}
|
|
816
|
+
};
|
|
817
|
+
|
|
818
|
+
socket.on('connect', guarded('connect', async () => { await announce(); flushUnsent(); }));
|
|
819
|
+
let serverKicks = 0;
|
|
820
|
+
socket.on('disconnect', guarded('disconnect', (reason) => {
|
|
821
|
+
if (stopped) return;
|
|
822
|
+
say(chalk.yellow(`⚠️ Mất kết nối (${reason}) — tự nối lại...`));
|
|
823
|
+
// Không quay màn hình khi không ai nhận được; nối lại thì BE mời phát lại cho người xem còn chờ.
|
|
824
|
+
stopDesktopCast('disconnected', false);
|
|
825
|
+
logActivity({ type: 'disconnected', reason });
|
|
826
|
+
mascot.disconnected();
|
|
827
|
+
mascotChat?.voiceDisconnected();
|
|
828
|
+
// Server chủ động cắt (BE khởi động lại, socket khác của máy này vừa thay chỗ…) → socket.io-client KHÔNG tự nối lại; nối tay, giãn nhịp.
|
|
829
|
+
if (reason === 'io server disconnect') {
|
|
830
|
+
const delay = Math.min(30_000, 1000 * 2 ** Math.min(serverKicks++, 5)) + Math.floor(Math.random() * 500);
|
|
831
|
+
setTimeout(() => { if (!stopped) socket.connect(); }, delay);
|
|
832
|
+
}
|
|
833
|
+
}));
|
|
834
|
+
socket.on('connect', () => { serverKicks = 0; });
|
|
835
|
+
socket.on('connect_error', guarded('connect_error', (err) => {
|
|
836
|
+
// Token cũ của máy (đã bị thay ở một lần xoay token mà máy này không làm) → có thể token bị chép: dừng + hướng dẫn ghép lại.
|
|
837
|
+
if (err?.message === 'DEVICE_TOKEN_RETIRED') {
|
|
838
|
+
console.log(chalk.red('❌ Token của máy này đã được đổi bởi một kết nối khác. Nếu không phải bạn, token có thể đã bị chép — chạy `aivin remote start --repair` để ghép lại (bản chép mất hiệu lực).'));
|
|
839
|
+
stopForGood();
|
|
840
|
+
return;
|
|
841
|
+
}
|
|
842
|
+
if (err?.message === 'DEVICE_UNAUTHORIZED') {
|
|
843
|
+
// Token xoay vòng chưa được chốt → thử lại bằng token cũ trước khi xoá ghép máy (02/11/2026).
|
|
844
|
+
if (!envCreds && fallBackToPreviousToken({ creds, socket, isStopped: () => stopped })) return void say(chalk.yellow(' ⚠️ Máy chủ chưa nhận token mới — nối lại bằng token cũ'));
|
|
845
|
+
const replaced = !clearDeviceCredentials(creds.device_token);
|
|
846
|
+
console.log(chalk.red(replaced
|
|
847
|
+
? '❌ Máy này vừa được ghép lại bởi một cửa sổ khác — cửa sổ này dừng, cửa sổ mới tiếp tục nhận việc.'
|
|
848
|
+
: '❌ Token của máy không còn hiệu lực (đã thu hồi hoặc ghép lại ở nơi khác). Chạy `aivin remote start` để ghép lại.'));
|
|
849
|
+
stopForGood();
|
|
850
|
+
return;
|
|
851
|
+
}
|
|
852
|
+
say(chalk.gray(` (chưa nối được: ${err?.message} — thử lại...)`));
|
|
853
|
+
}));
|
|
854
|
+
socket.on(DeviceEvent.REPLACED, guarded(DeviceEvent.REPLACED, (payload) => {
|
|
855
|
+
if (!payload?.by_instance || payload.by_instance === instance) return;
|
|
856
|
+
console.log(chalk.red('❌ Máy này vừa được mở nhận việc ở một cửa sổ hoặc máy khác — cửa sổ này dừng để hai bên không tranh nhau. Nếu không phải bạn, token có thể đã bị chép: chạy `aivin remote start --repair` để ghép lại.'));
|
|
857
|
+
stopForGood();
|
|
858
|
+
}));
|
|
859
|
+
socket.on(DeviceEvent.REVOKED, guarded(DeviceEvent.REVOKED, () => {
|
|
860
|
+
clearDeviceCredentials(creds.device_token);
|
|
861
|
+
console.log(chalk.red('❌ Máy này đã bị thu hồi quyền điều khiển từ xa.'));
|
|
862
|
+
stopForGood();
|
|
863
|
+
}));
|
|
864
|
+
socket.on(DeviceEvent.CALLS, guarded(DeviceEvent.CALLS, (payload) => {
|
|
865
|
+
// Chỉ nhận / ACK lời gọi đúng dạng — `{ calls: [null] }` từng làm sập daemon (null.call_id trong listener).
|
|
866
|
+
const calls = (Array.isArray(payload?.calls) ? payload.calls : []).filter(isValidDeviceCall);
|
|
867
|
+
if (!calls.length) return;
|
|
868
|
+
socket.emit(DeviceEvent.ACK, { call_ids: calls.map((c) => c.call_id) });
|
|
869
|
+
// BE gửi lại cùng `call_id` (máy rớt mạng trước khi ACK / kết quả tới nơi): đang chạy thì thôi, đã xong thì gửi lại kết quả cũ.
|
|
870
|
+
calls.forEach((call) => {
|
|
871
|
+
const prior = ledger.admit(call);
|
|
872
|
+
if (!prior) return void handleCall(call);
|
|
873
|
+
say(chalk.gray(` ↺ ${callLabel(call)}: máy chủ gửi lại — ${prior.state === CallState.RUNNING ? 'đang chạy' : 'trả lại kết quả đã có'}`));
|
|
874
|
+
if (prior.state === CallState.DONE) sendResult(ledger.reopen(call.call_id));
|
|
875
|
+
});
|
|
876
|
+
}));
|
|
877
|
+
socket.on(DeviceEvent.CANCEL, guarded(DeviceEvent.CANCEL, (payload) => {
|
|
878
|
+
if (!Array.isArray(payload?.call_ids)) return;
|
|
879
|
+
const ids = payload.call_ids.filter((id) => typeof id === 'string');
|
|
880
|
+
scheduler.cancel(ids);
|
|
881
|
+
cancelGating(ids);
|
|
882
|
+
}));
|
|
883
|
+
if (mascot.enabled) {
|
|
884
|
+
mascotChat = createMascotChat({
|
|
885
|
+
socket: () => socket, send: (cmd) => mascot.chat(cmd), lang: mascot.lang,
|
|
886
|
+
onAlert: (alert) => mascot.alert(alert), onPending: (on) => mascot.needsYou(on),
|
|
887
|
+
micBusy: () => !!meetings?.status()?.recording,
|
|
888
|
+
serverUrl: creds?.server_url || serverUrl,
|
|
889
|
+
notifyFreq: loadMascotSettings().notify_freq ?? 1,
|
|
890
|
+
});
|
|
891
|
+
socket.on(DeviceEvent.CHAT_EVENT, guarded(DeviceEvent.CHAT_EVENT, (payload) => mascotChat.onChatEvent(payload)));
|
|
892
|
+
// Báo chủ động: việc của chủ máy (web, chạy nền, automation…) xong / lỗi / cần trả lời.
|
|
893
|
+
socket.on(DeviceEvent.NOTIFY, guarded(DeviceEvent.NOTIFY, (payload) => mascotChat.onNotify(payload)));
|
|
894
|
+
socket.on(DeviceEvent.VOICE_EVENT, guarded(DeviceEvent.VOICE_EVENT, (payload) => mascotChat.onVoiceEvent(payload)));
|
|
895
|
+
}
|
|
896
|
+
socket.on(DeviceEvent.UPDATE, guarded(DeviceEvent.UPDATE, (payload) => {
|
|
897
|
+
if (!updater) return;
|
|
898
|
+
if (payload?.min_version) updater.setMinVersion(payload.min_version);
|
|
899
|
+
if (payload?.latest_version) updater.setServerHints(payload);
|
|
900
|
+
void updater.checkNow({ urgent: true });
|
|
901
|
+
}));
|
|
902
|
+
socket.on(DeviceEvent.DESKTOP_CAST_START, guarded(DeviceEvent.DESKTOP_CAST_START, async (payload) => {
|
|
903
|
+
const sessionId = payload?.session_id;
|
|
904
|
+
const viewerId = payload?.viewer_id;
|
|
905
|
+
if (!sessionId || !viewerId) return;
|
|
906
|
+
// Chủ máy đã tạm dừng điều khiển từ xa → từ chối cả xem màn hình.
|
|
907
|
+
if (isRemotePaused()) {
|
|
908
|
+
emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: 'paused' });
|
|
909
|
+
return;
|
|
910
|
+
}
|
|
911
|
+
const castConfig = {
|
|
912
|
+
max_fps: payload?.max_fps || 15,
|
|
913
|
+
max_width: payload?.max_width || 1366,
|
|
914
|
+
quality: payload?.quality || 65,
|
|
915
|
+
monitor: payload?.monitor ?? -1,
|
|
916
|
+
};
|
|
917
|
+
if (desktopCast.isActive() && desktopCast.sessionId() !== sessionId) stopDesktopCast('replaced', false);
|
|
918
|
+
if (!desktopCast.isActive()) {
|
|
919
|
+
const started = desktopCast.start({
|
|
920
|
+
sessionId,
|
|
921
|
+
maxFps: castConfig.max_fps,
|
|
922
|
+
maxWidth: castConfig.max_width,
|
|
923
|
+
quality: castConfig.quality,
|
|
924
|
+
monitor: castConfig.monitor,
|
|
925
|
+
onFrame: (frame) => {
|
|
926
|
+
desktopWebRtc.push(frame);
|
|
927
|
+
// Còn người xem chưa có kênh WebRTC (đang nối / runtime native không có) → JPEG qua máy chủ; BE chỉ chuyển cho những người đó.
|
|
928
|
+
if (desktopWebRtc.needsFallback() && socket.connected) socket.volatile.emit(DeviceEvent.DESKTOP_CAST_FRAME, frame);
|
|
929
|
+
syncCastJpeg();
|
|
930
|
+
},
|
|
931
|
+
// Mọi người xem đã có video → tiến trình quay thôi nén JPEG, chỉ gửi meta (toạ độ) + khung thô cho bộ mã hoá video.
|
|
932
|
+
onMeta: (meta) => { desktopWebRtc.push(meta); syncCastJpeg(); },
|
|
933
|
+
onCursor: (cursor) => desktopWebRtc.pushCursor(cursor),
|
|
934
|
+
onCursorShape: (shape) => desktopWebRtc.pushCursorShape(shape),
|
|
935
|
+
onCapture: ({ mode, reason }) => say(chalk.gray(` 🖥️ Chụp màn hình: ${mode}${reason ? ` (${reason})` : ''}`)),
|
|
936
|
+
rawPipe: true,
|
|
937
|
+
onReady: (meta) => {
|
|
938
|
+
say(chalk.cyan(` 🖥️ Đang có người xem + điều khiển màn hình máy này từ web (${meta.bounds?.width}x${meta.bounds?.height})`));
|
|
939
|
+
mascot.remoteView(true);
|
|
940
|
+
emitCastStatus({ session_id: sessionId, state: CastState.READY, bounds: meta.bounds });
|
|
941
|
+
},
|
|
942
|
+
onError: (err) => {
|
|
943
|
+
say(chalk.yellow(` ⚠️ Desktop Cast lỗi: ${err?.message || err}`));
|
|
944
|
+
},
|
|
945
|
+
onStop: () => {
|
|
946
|
+
say(chalk.gray(' ⏹ Đã ngừng xem màn hình từ web'));
|
|
947
|
+
mascot.remoteView(false);
|
|
948
|
+
},
|
|
949
|
+
});
|
|
950
|
+
if (!started) return;
|
|
951
|
+
} else {
|
|
952
|
+
desktopCast.config(castConfig);
|
|
953
|
+
}
|
|
954
|
+
const webRtcStarted = payload?.transport === 'webrtc'
|
|
955
|
+
? await desktopWebRtc.start({ sessionId, viewerId, iceServers: payload?.ice_servers || [], videoBitrate: payload?.video_bitrate || null }).catch(() => false)
|
|
956
|
+
: false;
|
|
957
|
+
if (webRtcStarted) desktopWebRtc.attachPipe(desktopCast.pipeName());
|
|
958
|
+
if (!webRtcStarted) emitCastStatus({
|
|
959
|
+
session_id: sessionId, viewer_id: viewerId, state: CastState.DEGRADED, transport: 'jpeg', reason: 'webrtc_runtime_unavailable',
|
|
960
|
+
});
|
|
961
|
+
}));
|
|
962
|
+
socket.on(DeviceEvent.DESKTOP_CAST_STOP, guarded(DeviceEvent.DESKTOP_CAST_STOP, (payload) => {
|
|
963
|
+
if (payload?.session_id && payload.session_id !== desktopCast.sessionId()) return;
|
|
964
|
+
if (payload?.viewer_id) desktopWebRtc.close(payload.viewer_id);
|
|
965
|
+
if (payload?.final !== false) stopDesktopCast('server', false);
|
|
966
|
+
}));
|
|
967
|
+
socket.on(DeviceEvent.DESKTOP_CAST_INPUT, guarded(DeviceEvent.DESKTOP_CAST_INPUT, (payload) => applyRemoteInput(payload)));
|
|
968
|
+
socket.on(DeviceEvent.DESKTOP_CAST_CONFIG, guarded(DeviceEvent.DESKTOP_CAST_CONFIG, (payload) => {
|
|
969
|
+
if (payload?.session_id && payload.session_id !== desktopCast.sessionId()) return;
|
|
970
|
+
const { max_fps, max_width, quality, monitor } = payload || {};
|
|
971
|
+
desktopCast.config({ max_fps, max_width, quality, monitor });
|
|
972
|
+
}));
|
|
973
|
+
socket.on(DeviceEvent.DESKTOP_CAST_SIGNAL, guarded(DeviceEvent.DESKTOP_CAST_SIGNAL, (payload) => {
|
|
974
|
+
void desktopWebRtc.signal(payload).catch(() => undefined);
|
|
975
|
+
}));
|
|
976
|
+
meetings?.recover();
|
|
977
|
+
|
|
978
|
+
// Lưới cuối: promise bị từ chối mà không ai bắt → ghi log, KHÔNG thoát (daemon phục vụ cả tổ chức, chết là mất mọi lời gọi đang chạy).
|
|
979
|
+
if (!unhandledRejectionHooked) {
|
|
980
|
+
unhandledRejectionHooked = true;
|
|
981
|
+
process.on('unhandledRejection', (reason) => console.error(chalk.red(`⚠️ Lỗi không được xử lý: ${reason?.stack || reason?.message || reason}`)));
|
|
982
|
+
// Như trên cho lỗi đồng bộ / sự kiện `error` không ai nghe: một lời gọi không được làm sập cả daemon (thoát 3 lần liền còn kích lùi bản CLI).
|
|
983
|
+
process.on('uncaughtException', (error) => console.error(chalk.red(`⚠️ Lỗi không được xử lý: ${error?.stack || error?.message || error}`)));
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
if (options.handleSignals !== false) {
|
|
987
|
+
// Chờ huỷ xong việc đang chạy (giết cây tiến trình con) rồi mới thoát — trước đây tiến trình con tách rời còn sống sau Ctrl+C.
|
|
988
|
+
const onSignal = () => { Promise.resolve(stop()).finally(() => process.exit(0)); };
|
|
989
|
+
process.once('SIGINT', onSignal);
|
|
990
|
+
process.once('SIGTERM', onSignal);
|
|
991
|
+
}
|
|
992
|
+
|
|
993
|
+
return { stop, socket, profile, env, creds, scheduler, catalog };
|
|
994
|
+
}
|
|
995
|
+
|
|
996
|
+
/**
|
|
997
|
+
* Kiểm nhanh: máy chủ HTTP, đã ghép chưa, BE có thấy máy này online không. KHÔNG tự bắt tay bằng token thiết bị — mỗi máy chỉ một
|
|
998
|
+
* socket, bắt tay thử sẽ đá daemon đang chạy ra.
|
|
999
|
+
*/
|
|
1000
|
+
export async function testRemoteConnection(options = {}) {
|
|
1001
|
+
const creds = loadDeviceCredentials();
|
|
1002
|
+
const serverUrl = resolveServerUrl(options, creds);
|
|
1003
|
+
const apiKey = options.apiKey ?? process.env.API_KEY;
|
|
1004
|
+
const report = { serverUrl, paired: !!creds, deviceId: creds?.device_id, httpOk: false, latencyMs: null, online: null, error: null };
|
|
1005
|
+
const startedAt = Date.now();
|
|
1006
|
+
try {
|
|
1007
|
+
const res = await axios.get(`${serverUrl}/setting/lang/default`, { timeout: 6000, validateStatus: () => true });
|
|
1008
|
+
report.httpOk = res.status < 500;
|
|
1009
|
+
report.latencyMs = Date.now() - startedAt;
|
|
1010
|
+
} catch (e) {
|
|
1011
|
+
report.error = `HTTP: ${e.message}`;
|
|
1012
|
+
}
|
|
1013
|
+
if (!creds || !apiKey) return report;
|
|
1014
|
+
try {
|
|
1015
|
+
const devices = await listDevices({ serverUrl, apiKey });
|
|
1016
|
+
const me = devices.find((d) => d.device_id === creds.device_id);
|
|
1017
|
+
report.online = me ? me.online : false;
|
|
1018
|
+
report.registered = !!me;
|
|
1019
|
+
report.toolsOnServer = me?.tools_count;
|
|
1020
|
+
} catch (e) {
|
|
1021
|
+
report.error = e.message;
|
|
1022
|
+
}
|
|
1023
|
+
return report;
|
|
1024
|
+
}
|