@aivin-labs/cli 1.0.51 → 1.0.60
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/bin/cli.mjs +2215 -2211
- package/bin/lib/auth.mjs +119 -88
- package/bin/lib/context.mjs +58 -5
- package/bin/lib/loginHandoff.mjs +87 -0
- package/bin/lib/openFile.mjs +29 -4
- package/bin/lib/remote/agentContract.mjs +370 -0
- package/bin/lib/remote/agentEvidence.mjs +409 -0
- package/bin/lib/remote/autoStart.mjs +640 -623
- package/bin/lib/remote/client.mjs +55 -17
- package/bin/lib/remote/codingAgents.mjs +594 -293
- package/bin/lib/remote/constants.mjs +1 -1
- package/bin/lib/remote/credentials.mjs +131 -125
- package/bin/lib/remote/desktop/castAuth.mjs +44 -19
- package/bin/lib/remote/desktop/castConsent.mjs +79 -14
- package/bin/lib/remote/desktop/castInput.mjs +3 -0
- package/bin/lib/remote/desktop/castTrust.mjs +221 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +483 -443
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +1 -1
- package/bin/lib/remote/desktop/desktopCastSource.mjs +324 -40
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +59 -4
- package/bin/lib/remote/desktop/strings.mjs +26 -0
- package/bin/lib/remote/desktop/traySource.mjs +1512 -1385
- package/bin/lib/remote/desktop/webrtcWorker.mjs +4 -0
- package/bin/lib/remote/dpapiHelper.mjs +91 -0
- package/bin/lib/remote/gui/index.mjs +422 -68
- package/bin/lib/remote/gui/windowsHostSource.mjs +2418 -1530
- package/bin/lib/remote/humanInput.mjs +7 -0
- package/bin/lib/remote/localConfirm.mjs +2 -2
- package/bin/lib/remote/tokenStore.mjs +19 -2
- package/bin/lib/remote/toolHandlers.mjs +861 -859
- package/docs/CLI.md +1606 -1602
- package/package.json +1 -1
|
@@ -1,623 +1,640 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import os from 'os';
|
|
4
|
-
import { execFileSync } from 'child_process';
|
|
5
|
-
import { fileURLToPath } from 'url';
|
|
6
|
-
import { REMOTE_CONFIG_DIR } from './deviceProfile.mjs';
|
|
7
|
-
import { DeviceAccess } from './constants.mjs';
|
|
8
|
-
import { loadDeviceCredentials } from './credentials.mjs';
|
|
9
|
-
import { RESTART_EXIT_CODE, UPDATE_PENDING_FILE, UPDATE_ROLLBACK_FILE } from '../selfUpdate.mjs';
|
|
10
|
-
import {
|
|
11
|
-
DESKTOP_DIR, RUN_KEY, STARTUP_VALUE, TrayLaunch, installDesktop, isDesktopInstalled, launcherExePath, readSavedDaemonArgs, setStartupApproved,
|
|
12
|
-
startMenuShortcutPath, startupState, uninstallDesktop,
|
|
13
|
-
} from './desktop/index.mjs';
|
|
14
|
-
import { fileAssociationsRegistered } from './desktop/fileAssociation.mjs';
|
|
15
|
-
import { clearWorkFolderState } from './workFolder.mjs';
|
|
16
|
-
import { installMacDesktop, isMacDesktopInstalled, macAgentPath, macAppPath, macStartupState, setMacStartup, uninstallMacDesktop } from './desktop/mac.mjs';
|
|
17
|
-
import {
|
|
18
|
-
hasLinuxDesktopSession, installLinuxDesktop, isLinuxDesktopInstalled, linuxAppEntryPath, linuxAutostartPath, linuxStartupState, linuxTrayAvailable,
|
|
19
|
-
setLinuxStartup, uninstallLinuxDesktop,
|
|
20
|
-
} from './desktop/linux.mjs';
|
|
21
|
-
import { mascotLang } from './mascot/strings.mjs';
|
|
22
|
-
|
|
23
|
-
const __filename = fileURLToPath(import.meta.url);
|
|
24
|
-
const __dirname = path.dirname(__filename);
|
|
25
|
-
const CLI_PATH = path.resolve(__dirname, '..', '..', 'cli.mjs');
|
|
26
|
-
|
|
27
|
-
/**
|
|
28
|
-
* Quy ước mã thoát của `aivin remote start` (29/10/2026) cho trình giữ chạy (Task Scheduler + VBS trên Windows, launchd, systemd):
|
|
29
|
-
* 0 = dừng có chủ đích (thu hồi, bị cửa sổ khác thay, đã có tiến trình khác nhận việc, Ctrl+C) → KHÔNG chạy lại; khác 0 = sập / lỗi
|
|
30
|
-
* (mất mạng lúc ghép máy…) → chạy lại sau ít giây, giãn dần tới 5 phút.
|
|
31
|
-
*/
|
|
32
|
-
export const WINDOWS_TASK_NAME = 'Aivin Remote';
|
|
33
|
-
export const WINDOWS_WATCHDOG_FILE = path.join(REMOTE_CONFIG_DIR, 'aivin-remote.vbs');
|
|
34
|
-
const WINDOWS_TASK_XML_FILE = path.join(REMOTE_CONFIG_DIR, 'aivin-remote-task.xml');
|
|
35
|
-
/** macOS / Linux: launchd / systemd chạy kịch bản này (một lần mỗi lần khởi động) thay vì chạy thẳng tệp chạy — để tự lùi bản ngoài tệp chạy. */
|
|
36
|
-
export const POSIX_RUN_SCRIPT_FILE = path.join(REMOTE_CONFIG_DIR, 'aivin-remote-run.sh');
|
|
37
|
-
const FAST_FAIL_FILE = path.join(REMOTE_CONFIG_DIR, 'update-fastfail.txt');
|
|
38
|
-
/** Tự lùi bản ở trình giữ chạy: bản chờ xác nhận thoát lỗi trong chừng này giây, liên tiếp chừng này lần → trả `.prev` về. */
|
|
39
|
-
export const SUPERVISOR_ROLLBACK = Object.freeze({ fastExitSec: 30, failures: 3 });
|
|
40
|
-
|
|
41
|
-
/**
|
|
42
|
-
* Thông tin để trình giữ chạy tự lùi bản — chỉ cho tệp chạy đóng gói (bản npm không có `.prev`). Tự lùi ở NGOÀI tệp chạy bắt được cả bản mới
|
|
43
|
-
* sập ngay lúc nạp mã (trước khi checkBootAfterUpdate trong tệp chạy kịp chạy).
|
|
44
|
-
*/
|
|
45
|
-
function supervisorRollbackPaths(launch) {
|
|
46
|
-
return
|
|
47
|
-
}
|
|
48
|
-
|
|
49
|
-
/** Lệnh chạy CLI: tệp chạy đóng gói (bộ cài install.ps1 / install.sh) là chính nó; bản npm là `node cli.mjs`. */
|
|
50
|
-
export function cliLaunchCommand() {
|
|
51
|
-
return process.env.AIVIN_CLI_BINARY ? [process.execPath] : [process.execPath, CLI_PATH];
|
|
52
|
-
}
|
|
53
|
-
|
|
54
|
-
export const REMOTE_DAEMON_FILE = path.join(REMOTE_CONFIG_DIR, 'remote-daemon.json');
|
|
55
|
-
|
|
56
|
-
/**
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
if (
|
|
63
|
-
|
|
64
|
-
}
|
|
65
|
-
|
|
66
|
-
}
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
if (process.platform === '
|
|
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
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
`
|
|
110
|
-
'
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
'
|
|
116
|
-
|
|
117
|
-
`
|
|
118
|
-
|
|
119
|
-
'
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
'
|
|
129
|
-
'
|
|
130
|
-
'
|
|
131
|
-
'
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
'
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
'
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
'
|
|
157
|
-
'
|
|
158
|
-
'
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
`
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
'
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
'
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
}
|
|
223
|
-
|
|
224
|
-
/**
|
|
225
|
-
*
|
|
226
|
-
*
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
<
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
<
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
</
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
<
|
|
270
|
-
<
|
|
271
|
-
<
|
|
272
|
-
</
|
|
273
|
-
|
|
274
|
-
</
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
}
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
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
|
-
|
|
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
|
-
const
|
|
469
|
-
|
|
470
|
-
const
|
|
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
|
-
<key>
|
|
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
|
-
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import os from 'os';
|
|
4
|
+
import { execFileSync } from 'child_process';
|
|
5
|
+
import { fileURLToPath } from 'url';
|
|
6
|
+
import { REMOTE_CONFIG_DIR } from './deviceProfile.mjs';
|
|
7
|
+
import { DeviceAccess } from './constants.mjs';
|
|
8
|
+
import { loadDeviceCredentials } from './credentials.mjs';
|
|
9
|
+
import { RESTART_EXIT_CODE, UPDATE_PENDING_FILE, UPDATE_ROLLBACK_FILE } from '../selfUpdate.mjs';
|
|
10
|
+
import {
|
|
11
|
+
DESKTOP_DIR, RUN_KEY, STARTUP_VALUE, TrayLaunch, installDesktop, isDesktopInstalled, launcherExePath, readSavedDaemonArgs, setStartupApproved,
|
|
12
|
+
startMenuShortcutPath, startupState, uninstallDesktop,
|
|
13
|
+
} from './desktop/index.mjs';
|
|
14
|
+
import { fileAssociationsRegistered } from './desktop/fileAssociation.mjs';
|
|
15
|
+
import { clearWorkFolderState } from './workFolder.mjs';
|
|
16
|
+
import { installMacDesktop, isMacDesktopInstalled, macAgentPath, macAppPath, macStartupState, setMacStartup, uninstallMacDesktop } from './desktop/mac.mjs';
|
|
17
|
+
import {
|
|
18
|
+
hasLinuxDesktopSession, installLinuxDesktop, isLinuxDesktopInstalled, linuxAppEntryPath, linuxAutostartPath, linuxStartupState, linuxTrayAvailable,
|
|
19
|
+
setLinuxStartup, uninstallLinuxDesktop,
|
|
20
|
+
} from './desktop/linux.mjs';
|
|
21
|
+
import { mascotLang } from './mascot/strings.mjs';
|
|
22
|
+
|
|
23
|
+
const __filename = fileURLToPath(import.meta.url);
|
|
24
|
+
const __dirname = path.dirname(__filename);
|
|
25
|
+
const CLI_PATH = path.resolve(__dirname, '..', '..', 'cli.mjs');
|
|
26
|
+
|
|
27
|
+
/**
|
|
28
|
+
* Quy ước mã thoát của `aivin remote start` (29/10/2026) cho trình giữ chạy (Task Scheduler + VBS trên Windows, launchd, systemd):
|
|
29
|
+
* 0 = dừng có chủ đích (thu hồi, bị cửa sổ khác thay, đã có tiến trình khác nhận việc, Ctrl+C) → KHÔNG chạy lại; khác 0 = sập / lỗi
|
|
30
|
+
* (mất mạng lúc ghép máy…) → chạy lại sau ít giây, giãn dần tới 5 phút.
|
|
31
|
+
*/
|
|
32
|
+
export const WINDOWS_TASK_NAME = 'Aivin Remote';
|
|
33
|
+
export const WINDOWS_WATCHDOG_FILE = path.join(REMOTE_CONFIG_DIR, 'aivin-remote.vbs');
|
|
34
|
+
const WINDOWS_TASK_XML_FILE = path.join(REMOTE_CONFIG_DIR, 'aivin-remote-task.xml');
|
|
35
|
+
/** macOS / Linux: launchd / systemd chạy kịch bản này (một lần mỗi lần khởi động) thay vì chạy thẳng tệp chạy — để tự lùi bản ngoài tệp chạy. */
|
|
36
|
+
export const POSIX_RUN_SCRIPT_FILE = path.join(REMOTE_CONFIG_DIR, 'aivin-remote-run.sh');
|
|
37
|
+
const FAST_FAIL_FILE = path.join(REMOTE_CONFIG_DIR, 'update-fastfail.txt');
|
|
38
|
+
/** Tự lùi bản ở trình giữ chạy: bản chờ xác nhận thoát lỗi trong chừng này giây, liên tiếp chừng này lần → trả `.prev` về. */
|
|
39
|
+
export const SUPERVISOR_ROLLBACK = Object.freeze({ fastExitSec: 30, failures: 3 });
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Thông tin để trình giữ chạy tự lùi bản — chỉ cho tệp chạy đóng gói (bản npm không có `.prev`). Tự lùi ở NGOÀI tệp chạy bắt được cả bản mới
|
|
43
|
+
* sập ngay lúc nạp mã (trước khi checkBootAfterUpdate trong tệp chạy kịp chạy).
|
|
44
|
+
*/
|
|
45
|
+
function supervisorRollbackPaths(launch) {
|
|
46
|
+
return launch.length === 1 ? { exe: launch[0], pendingFile: UPDATE_PENDING_FILE, rollbackFile: UPDATE_ROLLBACK_FILE, fastFailFile: FAST_FAIL_FILE } : null;
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Lệnh chạy CLI: tệp chạy đóng gói (bộ cài install.ps1 / install.sh) là chính nó; bản npm là `node cli.mjs`. */
|
|
50
|
+
export function cliLaunchCommand() {
|
|
51
|
+
return process.env.AIVIN_CLI_BINARY ? [process.execPath] : [process.execPath, CLI_PATH];
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export const REMOTE_DAEMON_FILE = path.join(REMOTE_CONFIG_DIR, 'remote-daemon.json');
|
|
55
|
+
|
|
56
|
+
/**
|
|
57
|
+
* Lệnh trình giữ chạy dùng để mở daemon. Chạy từ mã nguồn (Node) trên máy đã cài tệp chạy đóng gói thì giữ tệp chạy đó: daemon chạy bằng Node
|
|
58
|
+
* không tự cập nhật được và `--quiet` giấu lời nhắc, máy sẽ kẹt ở bản cũ mà không ai biết. `useNode` = chủ ý chạy thử khay với mã nguồn.
|
|
59
|
+
*/
|
|
60
|
+
export function daemonLaunchCommand({ useNode = false, packaged = !!process.env.AIVIN_CLI_BINARY, configFile = REMOTE_DAEMON_FILE } = {}) {
|
|
61
|
+
const launch = cliLaunchCommand();
|
|
62
|
+
if (packaged || useNode) return { launch, keptExe: null };
|
|
63
|
+
let saved = null;
|
|
64
|
+
try { saved = JSON.parse(fs.readFileSync(configFile, 'utf8'))?.nodeExec; } catch { /* chưa bật tự khởi động */ }
|
|
65
|
+
const keep = typeof saved === 'string' && /^aivin(\.exe)?$/i.test(path.basename(saved)) && fs.existsSync(saved);
|
|
66
|
+
return keep ? { launch: [saved], keptExe: saved } : { launch, keptExe: null };
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const keptExeWarning = (exe) => `Lệnh này chạy từ mã nguồn (Node) nên Aivin vẫn dùng tệp đã cài ${exe} để máy còn tự cập nhật. Muốn chạy khay bằng mã nguồn: thêm --use-node (máy sẽ không tự cập nhật nữa).`;
|
|
70
|
+
|
|
71
|
+
/** Tệp tự khởi động chính: Windows = thư mục Startup (dự phòng khi không tạo được tác vụ), macOS = LaunchAgent, Linux = systemd user. */
|
|
72
|
+
export function getAutoStartFilePath() {
|
|
73
|
+
if (process.platform === 'win32') {
|
|
74
|
+
const startupDir = path.join(os.homedir(), 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup');
|
|
75
|
+
return path.join(startupDir, 'aivin-remote.vbs');
|
|
76
|
+
}
|
|
77
|
+
if (process.platform === 'darwin') {
|
|
78
|
+
return path.join(os.homedir(), 'Library', 'LaunchAgents', 'com.aivin.remote.plist');
|
|
79
|
+
}
|
|
80
|
+
return path.join(os.homedir(), '.config', 'systemd', 'user', 'aivin-remote.service');
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** Mọi tệp tự khởi động cần dọn khi tắt. */
|
|
84
|
+
export function getAllAutoStartFilePaths() {
|
|
85
|
+
const paths = [getAutoStartFilePath()];
|
|
86
|
+
if (process.platform === 'win32') paths.push(WINDOWS_WATCHDOG_FILE, WINDOWS_TASK_XML_FILE);
|
|
87
|
+
else paths.push(POSIX_RUN_SCRIPT_FILE);
|
|
88
|
+
if (process.platform === 'linux') {
|
|
89
|
+
paths.push(path.join(os.homedir(), '.config', 'autostart', 'aivin-remote.desktop'));
|
|
90
|
+
}
|
|
91
|
+
return paths;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const xmlEscape = (s) => String(s).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"');
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Kịch bản VBS giữ daemon chạy nền (cửa sổ ẩn): chạy, chờ thoát; mã 0 → thôi; khác 0 → chờ 10 s (giãn gấp đôi tới 5 phút, chạy ổn > 5 phút
|
|
98
|
+
* thì về lại 10 s) rồi chạy lại. Trước 29/10/2026 tệp Startup chỉ chạy một lần lúc đăng nhập — daemon sập là máy offline tới lần đăng nhập sau.
|
|
99
|
+
* Mã 75 (đã cài bản mới / đã tự lùi bản) → chạy lại sau 1 s, không giãn nhịp. Đặt AIVIN_SUPERVISOR cho tiến trình con: daemon biết có
|
|
100
|
+
* trình giữ chạy, tự thoát để chuyển bản được (xem detectSupervisor).
|
|
101
|
+
* `rollback` (tệp chạy đóng gói): bản còn chờ xác nhận (có update-pending.txt) thoát lỗi trong < 30 s, 3 lần liền, mà còn `.prev` → đổi bản
|
|
102
|
+
* hỏng sang `.trash`, trả `.prev` về, ghi phiên bản vào update-rollback.txt (bản cũ đọc ở lần chạy sau, đưa vào danh sách bỏ qua).
|
|
103
|
+
*/
|
|
104
|
+
export function windowsWatchdogScript(argv, { rollback = null } = {}) {
|
|
105
|
+
const cmd = argv.map((part) => `""${part}""`).join(' ');
|
|
106
|
+
const vbsStr = (s) => `"${String(s).replace(/"/g, '""')}"`;
|
|
107
|
+
const { fastExitSec, failures } = SUPERVISOR_ROLLBACK;
|
|
108
|
+
return [
|
|
109
|
+
"' Aivin Device Agent - keeps `aivin remote start` running in the background.",
|
|
110
|
+
"' Exit code 0 = stopped on purpose (revoked, replaced, already running) -> stop; 75 = switch to the newly installed release -> restart now;",
|
|
111
|
+
"' anything else -> restart with backoff. A new release that keeps crashing right away is replaced by the previous one.",
|
|
112
|
+
'Set sh = CreateObject("WScript.Shell")',
|
|
113
|
+
`sh.Environment("Process").Item("${SUPERVISOR_ENV}") = "${Supervisor.WSCRIPT}"`,
|
|
114
|
+
...(rollback ? [
|
|
115
|
+
'Set fso = CreateObject("Scripting.FileSystemObject")',
|
|
116
|
+
`exe = ${vbsStr(rollback.exe)}`,
|
|
117
|
+
`pending = ${vbsStr(rollback.pendingFile)}`,
|
|
118
|
+
`rollback = ${vbsStr(rollback.rollbackFile)}`,
|
|
119
|
+
'fast = 0',
|
|
120
|
+
] : []),
|
|
121
|
+
'delay = 10',
|
|
122
|
+
'Do',
|
|
123
|
+
' started = Now',
|
|
124
|
+
` rc = sh.Run("${cmd}", 0, True)`,
|
|
125
|
+
' If rc = 0 Then Exit Do',
|
|
126
|
+
...(rollback ? [
|
|
127
|
+
` If rc <> ${RESTART_EXIT_CODE} And DateDiff("s", started, Now) < ${fastExitSec} And fso.FileExists(pending) And fso.FileExists(exe & ".prev") Then`,
|
|
128
|
+
' fast = fast + 1',
|
|
129
|
+
' Else',
|
|
130
|
+
' fast = 0',
|
|
131
|
+
' End If',
|
|
132
|
+
` If fast >= ${failures} Then`,
|
|
133
|
+
' fast = 0',
|
|
134
|
+
' On Error Resume Next',
|
|
135
|
+
' Set t = fso.OpenTextFile(pending, 1)',
|
|
136
|
+
' ver = t.ReadLine',
|
|
137
|
+
' t.Close',
|
|
138
|
+
' fso.MoveFile exe, exe & "-" & CLng(Timer * 100) & ".trash"',
|
|
139
|
+
' If Err.Number = 0 Then fso.MoveFile exe & ".prev", exe',
|
|
140
|
+
' If Err.Number = 0 Then',
|
|
141
|
+
' Set t = fso.CreateTextFile(rollback, True)',
|
|
142
|
+
' t.WriteLine ver',
|
|
143
|
+
' t.Close',
|
|
144
|
+
' fso.DeleteFile pending, True',
|
|
145
|
+
' End If',
|
|
146
|
+
' Err.Clear',
|
|
147
|
+
' On Error GoTo 0',
|
|
148
|
+
` rc = ${RESTART_EXIT_CODE}`,
|
|
149
|
+
' End If',
|
|
150
|
+
] : []),
|
|
151
|
+
` If rc = ${RESTART_EXIT_CODE} Then`,
|
|
152
|
+
' WScript.Sleep 1000',
|
|
153
|
+
' Else',
|
|
154
|
+
' If DateDiff("s", started, Now) > 300 Then delay = 10',
|
|
155
|
+
' WScript.Sleep delay * 1000',
|
|
156
|
+
' delay = delay * 2',
|
|
157
|
+
' If delay > 300 Then delay = 300',
|
|
158
|
+
' End If',
|
|
159
|
+
'Loop',
|
|
160
|
+
].join('\r\n') + '\r\n';
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
/**
|
|
164
|
+
* macOS / Linux: kịch bản sh launchd / systemd chạy mỗi lần khởi động (chúng tự chạy lại khi mã thoát khác 0). Đặt AIVIN_SUPERVISOR, chạy
|
|
165
|
+
* daemon một lần, rồi — với tệp chạy đóng gói — tự lùi bản như VBS (đếm lần sập nhanh liên tiếp trong tệp, vì mỗi lần là một tiến trình mới).
|
|
166
|
+
*/
|
|
167
|
+
export function posixRunScript(argv, { supervisor, rollback = null }) {
|
|
168
|
+
const q = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
169
|
+
const { fastExitSec, failures } = SUPERVISOR_ROLLBACK;
|
|
170
|
+
return [
|
|
171
|
+
'#!/bin/sh',
|
|
172
|
+
'# Aivin Device Agent - runs `aivin remote start` once; launchd / systemd restart it on a non-zero exit (75 = switch release).',
|
|
173
|
+
'# A new release that crashes right away, several times in a row, while still unconfirmed is replaced by the previous one.',
|
|
174
|
+
`${SUPERVISOR_ENV}=${q(supervisor)}`,
|
|
175
|
+
`export ${SUPERVISOR_ENV}`,
|
|
176
|
+
...(rollback ? [
|
|
177
|
+
`BIN=${q(rollback.exe)}`,
|
|
178
|
+
`PENDING=${q(rollback.pendingFile)}`,
|
|
179
|
+
`ROLLBACK=${q(rollback.rollbackFile)}`,
|
|
180
|
+
`FAST=${q(rollback.fastFailFile)}`,
|
|
181
|
+
'started=$(date +%s)',
|
|
182
|
+
] : []),
|
|
183
|
+
`${argv.map(q).join(' ')} "$@"`,
|
|
184
|
+
'rc=$?',
|
|
185
|
+
...(rollback ? [
|
|
186
|
+
'elapsed=$(( $(date +%s) - started ))',
|
|
187
|
+
`if [ "$rc" -ne 0 ] && [ "$rc" -ne ${RESTART_EXIT_CODE} ] && [ "$elapsed" -lt ${fastExitSec} ] && [ -f "$PENDING" ] && [ -f "$BIN.prev" ]; then`,
|
|
188
|
+
' n=$(( $(cat "$FAST" 2>/dev/null || echo 0) + 1 ))',
|
|
189
|
+
` if [ "$n" -ge ${failures} ]; then`,
|
|
190
|
+
' if mv -f "$BIN.prev" "$BIN"; then head -n 1 "$PENDING" > "$ROLLBACK"; rm -f "$PENDING"; fi',
|
|
191
|
+
' rm -f "$FAST"',
|
|
192
|
+
` exit ${RESTART_EXIT_CODE}`,
|
|
193
|
+
' fi',
|
|
194
|
+
' echo "$n" > "$FAST"',
|
|
195
|
+
'else',
|
|
196
|
+
' rm -f "$FAST"',
|
|
197
|
+
'fi',
|
|
198
|
+
] : []),
|
|
199
|
+
'exit "$rc"',
|
|
200
|
+
].join('\n') + '\n';
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
function writePosixRunScript(argv, supervisor, launch) {
|
|
204
|
+
fs.mkdirSync(path.dirname(POSIX_RUN_SCRIPT_FILE), { recursive: true });
|
|
205
|
+
fs.writeFileSync(POSIX_RUN_SCRIPT_FILE, posixRunScript(argv, { supervisor, rollback: supervisorRollbackPaths(launch) }), { mode: 0o755 });
|
|
206
|
+
fs.chmodSync(POSIX_RUN_SCRIPT_FILE, 0o755);
|
|
207
|
+
return ['/bin/sh', POSIX_RUN_SCRIPT_FILE];
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
/** Biến môi trường trình giữ chạy của Aivin đặt cho daemon. */
|
|
211
|
+
export const SUPERVISOR_ENV = 'AIVIN_SUPERVISOR';
|
|
212
|
+
export const Supervisor = Object.freeze({ WSCRIPT: 'wscript', TRAY: 'tray', LAUNCHD: 'launchd', SYSTEMD: 'systemd' });
|
|
213
|
+
|
|
214
|
+
function parentCommandLine() {
|
|
215
|
+
try {
|
|
216
|
+
return execFileSync('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `(Get-CimInstance Win32_Process -Filter "ProcessId=${Number(process.ppid)}").CommandLine`], {
|
|
217
|
+
encoding: 'utf8', timeout: 8000, windowsHide: true, stdio: ['ignore', 'pipe', 'ignore'],
|
|
218
|
+
}).trim();
|
|
219
|
+
} catch {
|
|
220
|
+
return '';
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* Daemon có đang chạy dưới trình giữ chạy của Aivin không (thoát mã 75 thì được mở lại). Dấu AIVIN_SUPERVISOR (tệp tự khởi động từ bản có
|
|
226
|
+
* tự cập nhật); tệp tự khởi động cũ không có dấu → launchd: nhãn `com.aivin.remote`; Windows: tiến trình cha là wscript chạy đúng
|
|
227
|
+
* aivin-remote.vbs. systemd cũ không nhận ra được → coi như không có (chỉ nhắc, không tự thoát) — an toàn hơn đoán sai rồi mất máy.
|
|
228
|
+
* Trước đây `--quiet` bị coi là có trình giữ chạy: ai tự chạy `--quiet` trong terminal / script riêng thì daemon tự thoát rồi máy offline.
|
|
229
|
+
*/
|
|
230
|
+
export function detectSupervisor({ env = process.env, platform = process.platform, quiet = false, readParent = parentCommandLine } = {}) {
|
|
231
|
+
const marked = String(env[SUPERVISOR_ENV] || '');
|
|
232
|
+
if (Object.values(Supervisor).includes(marked)) return marked;
|
|
233
|
+
if (!quiet) return null;
|
|
234
|
+
if (platform === 'darwin' && env.XPC_SERVICE_NAME === 'com.aivin.remote') return Supervisor.LAUNCHD;
|
|
235
|
+
if (platform === 'win32' && /\bwscript(\.exe)?\b.*aivin-remote\.vbs/i.test(readParent())) return Supervisor.WSCRIPT;
|
|
236
|
+
return null;
|
|
237
|
+
}
|
|
238
|
+
|
|
239
|
+
/**
|
|
240
|
+
* Tác vụ Task Scheduler của người dùng hiện tại (không cần quyền quản trị): chạy lúc đăng nhập, phiên tương tác (điều khiển giao diện /
|
|
241
|
+
* Office cần màn hình của người dùng), không dừng khi chạy pin, không giới hạn thời gian, không chạy chồng.
|
|
242
|
+
*/
|
|
243
|
+
export function windowsTaskXml({ userId, watchdogFile }) {
|
|
244
|
+
return `<?xml version="1.0" encoding="UTF-16"?>
|
|
245
|
+
<Task version="1.2" xmlns="http://schemas.microsoft.com/windows/2004/02/mit/task">
|
|
246
|
+
<RegistrationInfo>
|
|
247
|
+
<Description>Aivin Device Agent - lets your Aivin agents work on this computer (aivin remote start)</Description>
|
|
248
|
+
</RegistrationInfo>
|
|
249
|
+
<Triggers>
|
|
250
|
+
<LogonTrigger>
|
|
251
|
+
<Enabled>true</Enabled>
|
|
252
|
+
<UserId>${xmlEscape(userId)}</UserId>
|
|
253
|
+
</LogonTrigger>
|
|
254
|
+
</Triggers>
|
|
255
|
+
<Principals>
|
|
256
|
+
<Principal id="Author">
|
|
257
|
+
<UserId>${xmlEscape(userId)}</UserId>
|
|
258
|
+
<LogonType>InteractiveToken</LogonType>
|
|
259
|
+
<RunLevel>LeastPrivilege</RunLevel>
|
|
260
|
+
</Principal>
|
|
261
|
+
</Principals>
|
|
262
|
+
<Settings>
|
|
263
|
+
<MultipleInstancesPolicy>IgnoreNew</MultipleInstancesPolicy>
|
|
264
|
+
<DisallowStartIfOnBatteries>false</DisallowStartIfOnBatteries>
|
|
265
|
+
<StopIfGoingOnBatteries>false</StopIfGoingOnBatteries>
|
|
266
|
+
<AllowHardTerminate>true</AllowHardTerminate>
|
|
267
|
+
<StartWhenAvailable>true</StartWhenAvailable>
|
|
268
|
+
<RunOnlyIfNetworkAvailable>false</RunOnlyIfNetworkAvailable>
|
|
269
|
+
<IdleSettings>
|
|
270
|
+
<StopOnIdleEnd>false</StopOnIdleEnd>
|
|
271
|
+
<RestartOnIdle>false</RestartOnIdle>
|
|
272
|
+
</IdleSettings>
|
|
273
|
+
<AllowStartOnDemand>true</AllowStartOnDemand>
|
|
274
|
+
<Enabled>true</Enabled>
|
|
275
|
+
<Hidden>false</Hidden>
|
|
276
|
+
<ExecutionTimeLimit>PT0S</ExecutionTimeLimit>
|
|
277
|
+
<Priority>7</Priority>
|
|
278
|
+
<RestartOnFailure>
|
|
279
|
+
<Interval>PT1M</Interval>
|
|
280
|
+
<Count>999</Count>
|
|
281
|
+
</RestartOnFailure>
|
|
282
|
+
</Settings>
|
|
283
|
+
<Actions Context="Author">
|
|
284
|
+
<Exec>
|
|
285
|
+
<Command>wscript.exe</Command>
|
|
286
|
+
<Arguments>//B //Nologo "${xmlEscape(watchdogFile)}"</Arguments>
|
|
287
|
+
</Exec>
|
|
288
|
+
</Actions>
|
|
289
|
+
</Task>
|
|
290
|
+
`;
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
/** UTF-16 LE có BOM: wscript đọc đúng đường dẫn có dấu (tên người dùng tiếng Việt…), schtasks /XML nhận đúng khai báo encoding. */
|
|
294
|
+
function writeUtf16(file, text) {
|
|
295
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
296
|
+
fs.writeFileSync(file, Buffer.concat([Buffer.from([0xff, 0xfe]), Buffer.from(text, 'utf16le')]));
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
function windowsUserId() {
|
|
300
|
+
const user = process.env.USERNAME || os.userInfo().username;
|
|
301
|
+
return process.env.USERDOMAIN ? `${process.env.USERDOMAIN}\\${user}` : user;
|
|
302
|
+
}
|
|
303
|
+
|
|
304
|
+
function schtasks(args) {
|
|
305
|
+
return execFileSync('schtasks', args, { encoding: 'utf8', timeout: 15_000, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function windowsTaskExists() {
|
|
309
|
+
try {
|
|
310
|
+
schtasks(['/Query', '/TN', WINDOWS_TASK_NAME]);
|
|
311
|
+
return true;
|
|
312
|
+
} catch {
|
|
313
|
+
return false;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
/** Gỡ cách tự khởi động cũ của Windows (tác vụ Task Scheduler / VBS ở Startup) — tiến trình VBS đang chạy vẫn chạy tới khi tắt máy. */
|
|
318
|
+
function removeLegacyWindowsAutoStart() {
|
|
319
|
+
try { schtasks(['/Delete', '/TN', WINDOWS_TASK_NAME, '/F']); } catch { /* chưa có tác vụ */ }
|
|
320
|
+
for (const file of [getAutoStartFilePath(), WINDOWS_WATCHDOG_FILE, WINDOWS_TASK_XML_FILE]) {
|
|
321
|
+
try { fs.rmSync(file, { force: true }); } catch { /* tệp đang bị khoá */ }
|
|
322
|
+
}
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Dự phòng: tác vụ Task Scheduler chạy kịch bản VBS; máy chặn tạo tác vụ (chính sách công ty) → chép kịch bản vào thư mục Startup. */
|
|
326
|
+
function enableWindowsTask(argv, launch) {
|
|
327
|
+
const script = windowsWatchdogScript(argv, { rollback: supervisorRollbackPaths(launch) });
|
|
328
|
+
writeUtf16(WINDOWS_WATCHDOG_FILE, script);
|
|
329
|
+
const startupFile = getAutoStartFilePath();
|
|
330
|
+
try {
|
|
331
|
+
writeUtf16(WINDOWS_TASK_XML_FILE, windowsTaskXml({ userId: windowsUserId(), watchdogFile: WINDOWS_WATCHDOG_FILE }));
|
|
332
|
+
schtasks(['/Create', '/TN', WINDOWS_TASK_NAME, '/XML', WINDOWS_TASK_XML_FILE, '/F']);
|
|
333
|
+
fs.rmSync(startupFile, { force: true });
|
|
334
|
+
return { filePath: `Task Scheduler: ${WINDOWS_TASK_NAME}`, method: 'task' };
|
|
335
|
+
} catch (e) {
|
|
336
|
+
writeUtf16(startupFile, script);
|
|
337
|
+
return { filePath: startupFile, method: 'startup', warning: `Không tạo được tác vụ Task Scheduler (${String(e?.stderr || e?.message || e).trim()}) — dùng thư mục Startup` };
|
|
338
|
+
} finally {
|
|
339
|
+
fs.rmSync(WINDOWS_TASK_XML_FILE, { force: true });
|
|
340
|
+
}
|
|
341
|
+
}
|
|
342
|
+
|
|
343
|
+
const RUN_ENTRY = `${RUN_KEY}\\${STARTUP_VALUE}`;
|
|
344
|
+
|
|
345
|
+
/**
|
|
346
|
+
* Windows: ứng dụng khay Aivin.exe (desktop/) giữ daemon chạy, mục khởi động ở khoá Run (hiện + bật / tắt được trong Task Manager →
|
|
347
|
+
* Startup apps), lối tắt Start menu. Không dựng được Aivin.exe (máy chặn csc / PowerShell) → lùi về tác vụ Task Scheduler như trước.
|
|
348
|
+
*/
|
|
349
|
+
function enableWindows(argv, launch) {
|
|
350
|
+
try {
|
|
351
|
+
installDesktop({ argv, rollback: supervisorRollbackPaths(launch), lang: mascotLang(), autostart: true, launch: true, launchMode: TrayLaunch.AUTOSTART });
|
|
352
|
+
removeLegacyWindowsAutoStart();
|
|
353
|
+
return { filePath: `${RUN_ENTRY} (Task Manager → Startup apps)`, method: 'run' };
|
|
354
|
+
} catch (e) {
|
|
355
|
+
const res = enableWindowsTask(argv, launch);
|
|
356
|
+
const why = `Không dựng được ứng dụng khay Aivin (${String(e?.message || e).trim()}) — dùng ${res.method === 'task' ? 'Task Scheduler' : 'thư mục Startup'}`;
|
|
357
|
+
return { ...res, warning: [why, res.warning].filter(Boolean).join('; ') };
|
|
358
|
+
}
|
|
359
|
+
}
|
|
360
|
+
|
|
361
|
+
function writeDaemonConfig({ rootDir, filePath, method, nodeExec }) {
|
|
362
|
+
fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
|
|
363
|
+
const daemonConfig = {
|
|
364
|
+
enabled: true,
|
|
365
|
+
platform: process.platform,
|
|
366
|
+
rootDir,
|
|
367
|
+
autoStartFile: filePath,
|
|
368
|
+
...(method ? { method } : {}),
|
|
369
|
+
nodeExec,
|
|
370
|
+
updatedAt: new Date().toISOString(),
|
|
371
|
+
};
|
|
372
|
+
fs.writeFileSync(REMOTE_DAEMON_FILE, JSON.stringify(daemonConfig, null, 2) + '\n', 'utf8');
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* macOS / Linux: biểu tượng thanh menu / khay (desktop/mac.mjs, desktop/linux.mjs) chạy aivin-remote-run.sh — một kịch bản cho cả hai,
|
|
377
|
+
* dấu trình giữ chạy = tray. Đối số daemon lưu riêng (daemon-args.json) để `aivin desktop install` sau giữ `--dir` / `--proxy`.
|
|
378
|
+
*/
|
|
379
|
+
const POSIX_DESKTOP = {
|
|
380
|
+
darwin: {
|
|
381
|
+
install: installMacDesktop, uninstall: uninstallMacDesktop, installed: isMacDesktopInstalled, state: macStartupState, setStartup: setMacStartup,
|
|
382
|
+
entry: () => `${macAgentPath()} (System Settings → General → Login Items)`, app: () => macAppPath(), search: 'Spotlight / Launchpad',
|
|
383
|
+
},
|
|
384
|
+
linux: {
|
|
385
|
+
install: installLinuxDesktop, uninstall: uninstallLinuxDesktop, installed: isLinuxDesktopInstalled, state: linuxStartupState, setStartup: setLinuxStartup,
|
|
386
|
+
entry: () => linuxAutostartPath(), app: () => linuxAppEntryPath(), search: 'menu ứng dụng',
|
|
387
|
+
},
|
|
388
|
+
};
|
|
389
|
+
const DAEMON_ARGS_FILE = path.join(DESKTOP_DIR, 'daemon-args.json');
|
|
390
|
+
|
|
391
|
+
function readPosixDaemonArgs() {
|
|
392
|
+
try {
|
|
393
|
+
const args = JSON.parse(fs.readFileSync(DAEMON_ARGS_FILE, 'utf8'));
|
|
394
|
+
return Array.isArray(args) ? args.map(String) : null;
|
|
395
|
+
} catch {
|
|
396
|
+
return null;
|
|
397
|
+
}
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
function installPosixDesktop(argv, launch, options) {
|
|
401
|
+
const desktop = POSIX_DESKTOP[process.platform];
|
|
402
|
+
const [runShell, runScript] = writePosixRunScript(argv, Supervisor.TRAY, launch);
|
|
403
|
+
fs.mkdirSync(DESKTOP_DIR, { recursive: true });
|
|
404
|
+
fs.writeFileSync(DAEMON_ARGS_FILE, JSON.stringify(argv.slice(argv.indexOf('start') + 1)));
|
|
405
|
+
const res = desktop.install({ runScript, lang: mascotLang(), ...options });
|
|
406
|
+
return { ...res, runShell };
|
|
407
|
+
}
|
|
408
|
+
|
|
409
|
+
/** `aivin remote enable` trên macOS / Linux có màn hình: thanh menu / khay + mục khởi động; lỗi → cách cũ (LaunchAgent / systemd + autostart). */
|
|
410
|
+
function tryPosixDesktop(argv, launch) {
|
|
411
|
+
const desktop = POSIX_DESKTOP[process.platform];
|
|
412
|
+
if (!desktop || (process.platform === 'linux' && !hasLinuxDesktopSession())) return null;
|
|
413
|
+
try {
|
|
414
|
+
installPosixDesktop(argv, launch, { autostart: true, launch: true, launchMode: TrayLaunch.AUTOSTART });
|
|
415
|
+
return { filePath: desktop.entry(), method: 'desktop' };
|
|
416
|
+
} catch (e) {
|
|
417
|
+
return { warning: `Không dựng được ứng dụng Aivin trên màn hình (${String(e?.message || e).trim()}) — dùng cách tự khởi động cũ` };
|
|
418
|
+
}
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
/**
|
|
422
|
+
* `aivin desktop install` (bộ cài install.ps1 / install.sh gọi): Windows = khay + Start menu, macOS = Aivin.app + thanh menu, Linux = menu ứng
|
|
423
|
+
* dụng + khay; (mặc định) khởi động cùng máy. Giữ đối số daemon của lần `aivin remote enable` trước; chưa có thì `remote start --quiet`
|
|
424
|
+
* trần — daemon dùng thư mục / chế độ đã lưu lúc ghép máy.
|
|
425
|
+
*/
|
|
426
|
+
export function installDesktopApp({ autostart = true, launch = true, openPlatform = false, useNode = false } = {}) {
|
|
427
|
+
const { launch: cli, keptExe } = daemonLaunchCommand({ useNode });
|
|
428
|
+
const withWarning = (res) => (keptExe ? { ...res, warning: keptExeWarning(keptExe) } : res);
|
|
429
|
+
if (process.platform === 'win32') {
|
|
430
|
+
const argv = [...cli, 'remote', 'start', ...(readSavedDaemonArgs() || ['--quiet'])];
|
|
431
|
+
const res = installDesktop({ argv, rollback: supervisorRollbackPaths(cli), lang: mascotLang(), autostart, launch, launchMode: openPlatform ? TrayLaunch.OPEN : TrayLaunch.INSTALLED });
|
|
432
|
+
if (autostart) {
|
|
433
|
+
removeLegacyWindowsAutoStart();
|
|
434
|
+
writeDaemonConfig({ rootDir: os.homedir(), filePath: RUN_ENTRY, method: 'run', nodeExec: cli[0] });
|
|
435
|
+
}
|
|
436
|
+
return withWarning(res);
|
|
437
|
+
}
|
|
438
|
+
const desktop = POSIX_DESKTOP[process.platform];
|
|
439
|
+
if (!desktop) throw new Error(`Chưa hỗ trợ ứng dụng Aivin trên màn hình cho ${process.platform}.`);
|
|
440
|
+
const argv = [...cli, 'remote', 'start', ...(readPosixDaemonArgs() || ['--quiet'])];
|
|
441
|
+
const res = installPosixDesktop(argv, cli, { autostart, launch, launchMode: TrayLaunch.INSTALLED });
|
|
442
|
+
if (autostart) writeDaemonConfig({ rootDir: os.homedir(), filePath: desktop.entry(), method: 'desktop', nodeExec: cli[0] });
|
|
443
|
+
return withWarning(res);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
/** `aivin desktop uninstall`: gỡ ứng dụng + mục khởi động (tiến trình daemon nó giữ cũng dừng). */
|
|
447
|
+
export function uninstallDesktopApp() {
|
|
448
|
+
if (process.platform === 'win32') {
|
|
449
|
+
const res = uninstallDesktop();
|
|
450
|
+
clearWorkFolderState();
|
|
451
|
+
return res;
|
|
452
|
+
}
|
|
453
|
+
const desktop = POSIX_DESKTOP[process.platform];
|
|
454
|
+
if (!desktop) return { removed: true };
|
|
455
|
+
const res = desktop.uninstall();
|
|
456
|
+
fs.rmSync(POSIX_RUN_SCRIPT_FILE, { force: true });
|
|
457
|
+
return res;
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
/** `aivin desktop`: đã cài chưa, ở đâu, tìm bằng gì, khởi động cùng máy, (Linux) có biểu tượng khay không. */
|
|
461
|
+
export function desktopAppStatus() {
|
|
462
|
+
if (process.platform === 'win32') {
|
|
463
|
+
return {
|
|
464
|
+
installed: isDesktopInstalled(), app: launcherExePath(), search: fs.existsSync(startMenuShortcutPath()) ? 'Start menu' : null,
|
|
465
|
+
startup: startupState(), tray: true, openWith: fileAssociationsRegistered(),
|
|
466
|
+
};
|
|
467
|
+
}
|
|
468
|
+
const desktop = POSIX_DESKTOP[process.platform];
|
|
469
|
+
if (!desktop) return { installed: false, supported: false };
|
|
470
|
+
const installed = desktop.installed();
|
|
471
|
+
return {
|
|
472
|
+
installed, app: desktop.app(), search: installed ? desktop.search : null, startup: desktop.state(),
|
|
473
|
+
tray: process.platform === 'darwin' ? true : linuxTrayAvailable(),
|
|
474
|
+
};
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/** Kích hoạt tự khởi động cùng máy tính trên mọi hệ điều hành (Windows, macOS, Linux). */
|
|
478
|
+
export function enableAutoStart(options = {}) {
|
|
479
|
+
const rootDir = path.resolve(options.dir || process.cwd());
|
|
480
|
+
// Máy đang TOÀN QUYỀN và không nêu --dir: khởi động không kèm --dir để giữ chế độ đã lưu (kèm --dir là về chế độ một thư mục).
|
|
481
|
+
const keepFullAccess = !options.dir && loadDeviceCredentials()?.access === DeviceAccess.FULL;
|
|
482
|
+
const scopeArgs = [...(keepFullAccess ? [] : ['--dir', rootDir]), ...(options.proxy ? ['--proxy', String(options.proxy)] : [])];
|
|
483
|
+
const { launch, keptExe } = daemonLaunchCommand({ useNode: options.useNode });
|
|
484
|
+
const argv = [...launch, 'remote', 'start', '--quiet', ...scopeArgs];
|
|
485
|
+
const nodeExec = launch[0];
|
|
486
|
+
const logOut = path.join(REMOTE_CONFIG_DIR, 'remote-service.log');
|
|
487
|
+
let filePath = getAutoStartFilePath();
|
|
488
|
+
let extra = {};
|
|
489
|
+
|
|
490
|
+
fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
|
|
491
|
+
|
|
492
|
+
const desktop = process.platform === 'win32' ? null : tryPosixDesktop(argv, launch);
|
|
493
|
+
if (process.platform === 'win32') {
|
|
494
|
+
extra = enableWindows(argv, launch);
|
|
495
|
+
filePath = extra.filePath;
|
|
496
|
+
} else if (desktop?.filePath) {
|
|
497
|
+
extra = desktop;
|
|
498
|
+
filePath = desktop.filePath;
|
|
499
|
+
} else if (process.platform === 'darwin') {
|
|
500
|
+
if (desktop?.warning) extra = { warning: desktop.warning };
|
|
501
|
+
// macOS: LaunchAgent chạy kịch bản sh (tự lùi bản ngoài tệp chạy), chỉ chạy lại khi thoát bất thường (mã khác 0).
|
|
502
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
503
|
+
const runArgv = writePosixRunScript(argv, Supervisor.LAUNCHD, launch);
|
|
504
|
+
const plistContent = `<?xml version="1.0" encoding="UTF-8"?>
|
|
505
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
506
|
+
<plist version="1.0">
|
|
507
|
+
<dict>
|
|
508
|
+
<key>Label</key>
|
|
509
|
+
<string>com.aivin.remote</string>
|
|
510
|
+
<key>ProgramArguments</key>
|
|
511
|
+
<array>
|
|
512
|
+
${runArgv.map((part) => ` <string>${xmlEscape(part)}</string>`).join('\n')}
|
|
513
|
+
</array>
|
|
514
|
+
<key>RunAtLoad</key>
|
|
515
|
+
<true/>
|
|
516
|
+
<key>KeepAlive</key>
|
|
517
|
+
<dict>
|
|
518
|
+
<key>SuccessfulExit</key>
|
|
519
|
+
<false/>
|
|
520
|
+
</dict>
|
|
521
|
+
<key>ThrottleInterval</key>
|
|
522
|
+
<integer>10</integer>
|
|
523
|
+
<key>EnvironmentVariables</key>
|
|
524
|
+
<dict>
|
|
525
|
+
<key>${SUPERVISOR_ENV}</key>
|
|
526
|
+
<string>${Supervisor.LAUNCHD}</string>
|
|
527
|
+
</dict>
|
|
528
|
+
<key>StandardOutPath</key>
|
|
529
|
+
<string>${xmlEscape(logOut)}</string>
|
|
530
|
+
<key>StandardErrorPath</key>
|
|
531
|
+
<string>${xmlEscape(logOut)}</string>
|
|
532
|
+
</dict>
|
|
533
|
+
</plist>
|
|
534
|
+
`;
|
|
535
|
+
fs.writeFileSync(filePath, plistContent, 'utf8');
|
|
536
|
+
} else {
|
|
537
|
+
if (desktop?.warning) extra = { warning: desktop.warning };
|
|
538
|
+
// Linux: dịch vụ người dùng systemd chạy kịch bản sh (chạy lại khi thoát bất thường, tự lùi bản) + tệp XDG autostart cho máy không bật
|
|
539
|
+
// systemd user session (chạy thẳng, không có trình giữ chạy → không tự chuyển bản).
|
|
540
|
+
fs.mkdirSync(path.dirname(filePath), { recursive: true });
|
|
541
|
+
const execLine = argv.map((part) => `"${part}"`).join(' ');
|
|
542
|
+
const runLine = writePosixRunScript(argv, Supervisor.SYSTEMD, launch).map((part) => `"${part}"`).join(' ');
|
|
543
|
+
const serviceContent = `[Unit]
|
|
544
|
+
Description=AIVIN Remote Control Daemon
|
|
545
|
+
After=network.target
|
|
546
|
+
|
|
547
|
+
[Service]
|
|
548
|
+
Type=simple
|
|
549
|
+
ExecStart=${runLine}
|
|
550
|
+
Restart=on-failure
|
|
551
|
+
RestartSec=10
|
|
552
|
+
Environment=${SUPERVISOR_ENV}=${Supervisor.SYSTEMD}
|
|
553
|
+
WorkingDirectory=${rootDir}
|
|
554
|
+
StandardOutput=append:${logOut}
|
|
555
|
+
StandardError=append:${logOut}
|
|
556
|
+
|
|
557
|
+
[Install]
|
|
558
|
+
WantedBy=default.target
|
|
559
|
+
`;
|
|
560
|
+
fs.writeFileSync(filePath, serviceContent, 'utf8');
|
|
561
|
+
|
|
562
|
+
const desktopPath = path.join(os.homedir(), '.config', 'autostart', 'aivin-remote.desktop');
|
|
563
|
+
fs.mkdirSync(path.dirname(desktopPath), { recursive: true });
|
|
564
|
+
const desktopContent = `[Desktop Entry]
|
|
565
|
+
Type=Application
|
|
566
|
+
Name=AIVIN Remote Control
|
|
567
|
+
Exec=${execLine}
|
|
568
|
+
Hidden=false
|
|
569
|
+
NoDisplay=false
|
|
570
|
+
X-GNOME-Autostart-enabled=true
|
|
571
|
+
`;
|
|
572
|
+
fs.writeFileSync(desktopPath, desktopContent, 'utf8');
|
|
573
|
+
}
|
|
574
|
+
|
|
575
|
+
writeDaemonConfig({ rootDir, filePath, method: extra.method, nodeExec });
|
|
576
|
+
|
|
577
|
+
const warning = [extra.warning, keptExe && keptExeWarning(keptExe)].filter(Boolean).join('; ');
|
|
578
|
+
return { success: true, filePath, rootDir, platform: process.platform, ...(warning ? { warning } : {}) };
|
|
579
|
+
}
|
|
580
|
+
|
|
581
|
+
/** Huỷ tự khởi động (tiến trình đang chạy vẫn chạy tới khi tắt). */
|
|
582
|
+
export function disableAutoStart() {
|
|
583
|
+
if (process.platform === 'win32') {
|
|
584
|
+
try { schtasks(['/Delete', '/TN', WINDOWS_TASK_NAME, '/F']); } catch { /* chưa có tác vụ */ }
|
|
585
|
+
// Khoá Run: đánh dấu tắt như Task Manager — mục vẫn hiện "Disabled", bật lại được ở đó / menu khay / `aivin remote enable`.
|
|
586
|
+
if (startupState().registered) setStartupApproved(false);
|
|
587
|
+
}
|
|
588
|
+
// macOS / Linux đã cài ứng dụng: chỉ tắt mục khởi động (bật lại được ở menu / Login Items / Startup Applications); giữ kịch bản chạy cho app.
|
|
589
|
+
const desktop = POSIX_DESKTOP[process.platform];
|
|
590
|
+
const keepRunScript = Boolean(desktop?.installed());
|
|
591
|
+
if (keepRunScript) desktop.setStartup(false);
|
|
592
|
+
for (const filePath of getAllAutoStartFilePaths()) {
|
|
593
|
+
if (keepRunScript && filePath === POSIX_RUN_SCRIPT_FILE) continue;
|
|
594
|
+
try { fs.rmSync(filePath, { force: true }); } catch { /* tệp đang bị khoá */ }
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
if (fs.existsSync(REMOTE_DAEMON_FILE)) {
|
|
598
|
+
try {
|
|
599
|
+
const current = JSON.parse(fs.readFileSync(REMOTE_DAEMON_FILE, 'utf8'));
|
|
600
|
+
current.enabled = false;
|
|
601
|
+
current.updatedAt = new Date().toISOString();
|
|
602
|
+
fs.writeFileSync(REMOTE_DAEMON_FILE, JSON.stringify(current, null, 2) + '\n', 'utf8');
|
|
603
|
+
} catch {
|
|
604
|
+
// Bỏ qua lỗi đọc ghi cấu hình
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
return { success: true };
|
|
609
|
+
}
|
|
610
|
+
|
|
611
|
+
/** Trạng thái tự khởi động của máy. */
|
|
612
|
+
export function getAutoStartStatus() {
|
|
613
|
+
const startupFile = getAutoStartFilePath();
|
|
614
|
+
let daemonConfig = null;
|
|
615
|
+
if (fs.existsSync(REMOTE_DAEMON_FILE)) {
|
|
616
|
+
try {
|
|
617
|
+
daemonConfig = JSON.parse(fs.readFileSync(REMOTE_DAEMON_FILE, 'utf8'));
|
|
618
|
+
} catch {
|
|
619
|
+
daemonConfig = null;
|
|
620
|
+
}
|
|
621
|
+
}
|
|
622
|
+
// Windows: khoá Run là nguồn sự thật — người dùng có thể bật / tắt ở Task Manager hay menu khay, không qua aivin.
|
|
623
|
+
const run = process.platform === 'win32' ? startupState() : null;
|
|
624
|
+
if (run?.registered) {
|
|
625
|
+
return { enabled: run.enabled, filePath: RUN_ENTRY, rootDir: daemonConfig?.rootDir || process.cwd(), updatedAt: daemonConfig?.updatedAt || null };
|
|
626
|
+
}
|
|
627
|
+
const desktop = POSIX_DESKTOP[process.platform];
|
|
628
|
+
if (desktop?.installed() && desktop.state().registered) {
|
|
629
|
+
return { enabled: desktop.state().enabled, filePath: desktop.entry(), rootDir: daemonConfig?.rootDir || process.cwd(), updatedAt: daemonConfig?.updatedAt || null };
|
|
630
|
+
}
|
|
631
|
+
const task = process.platform === 'win32' && daemonConfig?.method === 'task' && windowsTaskExists();
|
|
632
|
+
const installed = task || fs.existsSync(startupFile);
|
|
633
|
+
|
|
634
|
+
return {
|
|
635
|
+
enabled: Boolean(installed && daemonConfig?.enabled !== false),
|
|
636
|
+
filePath: task ? `Task Scheduler: ${WINDOWS_TASK_NAME}` : startupFile,
|
|
637
|
+
rootDir: daemonConfig?.rootDir || process.cwd(),
|
|
638
|
+
updatedAt: daemonConfig?.updatedAt || null,
|
|
639
|
+
};
|
|
640
|
+
}
|