@aivin-labs/cli 1.0.63 → 1.0.65
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/lib/remote/client.mjs +1490 -1456
- package/bin/lib/remote/constants.mjs +16 -0
- package/bin/lib/remote/desktop/cscExe.mjs +72 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +479 -436
- package/bin/lib/remote/desktop/humanIdle.mjs +57 -0
- package/bin/lib/remote/desktop/identifyOverlay.mjs +100 -0
- package/bin/lib/remote/desktop/windowProbe.mjs +68 -0
- package/bin/lib/remote/deviceProfile.mjs +4 -1
- package/bin/lib/remote/localLlm.mjs +514 -0
- package/bin/lib/remote/mascot/hostSource.mjs +7 -4
- package/bin/lib/remote/toolHandlers.mjs +7 -0
- package/package.json +1 -1
|
@@ -1,1456 +1,1490 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import os from 'os';
|
|
3
|
-
import path from 'path';
|
|
4
|
-
import axios from 'axios';
|
|
5
|
-
import chalk from 'chalk';
|
|
6
|
-
import readline from 'readline/promises';
|
|
7
|
-
import { io } from 'socket.io-client';
|
|
8
|
-
import { DEFAULT_AIVIN_BASE_URL } from '../context.mjs';
|
|
9
|
-
import { readActiveServer, resolveServerUrl as normalizeServerUrl, setActiveServer } from '../servers.mjs';
|
|
10
|
-
import { logActivity } from './activityLog.mjs';
|
|
11
|
-
import { DEFAULT_SCOPE_LIMITS, DEVICE_NAMESPACE, KILL_SWITCH_FILE, REMOTE_CONFIG_DIR, CastState, DeviceAccess, DeviceErrorCode, DeviceEvent, HoldPhase, MAX_RESULT_BYTES, PROTOCOL_VERSION, REMOTE_IDEM_FILE, REMOTE_OUTBOX_FILE, ServerFeature, ToolGroup } from './constants.mjs';
|
|
12
|
-
import { CallState, createCallLedger } from './callLedger.mjs';
|
|
13
|
-
import { fallBackToPreviousToken, settleRotation } from './tokenRotation.mjs';
|
|
14
|
-
import { configureProxy, proxyAgentFor } from './netProxy.mjs';
|
|
15
|
-
import { createKeepAwake } from './keepAwake.mjs';
|
|
16
|
-
import { createPolicyGuard, describeCall, evaluateLocalPolicy } from './localPolicy.mjs';
|
|
17
|
-
import { ConfirmResult, createLocalConfirmer } from './localConfirm.mjs';
|
|
18
|
-
import { clearDeviceCredentials, confirmServerCredentialMigration, credentialsFromEnv, listDevices, loadDeviceCredentials, pairDevice, pairDeviceWithCode, readStoredTokenFresh, saveDeviceCredentials } from './credentials.mjs';
|
|
19
|
-
import { ensureMemoryLoaded, memoryStats, stopWatchingMemory, watchMemoryDir } from './deviceMemory.mjs';
|
|
20
|
-
import { buildCatalog, buildDeviceProfile } from './deviceProfile.mjs';
|
|
21
|
-
import { createFileIndex, indexRootsFor } from './fileIndexer.mjs';
|
|
22
|
-
import { createScheduler } from './scheduler.mjs';
|
|
23
|
-
import { acquireDaemonLock, lockHolder } from './daemonLock.mjs';
|
|
24
|
-
import { randomUUID } from 'crypto';
|
|
25
|
-
import { DeviceToolError, fullAccessRoots, isRemotePaused, setRemotePaused } from './sandbox.mjs';
|
|
26
|
-
import { createMascot, HostEvent as MascotHostEvent, loadMascotSettings, saveMascotSettings } from './mascot/index.mjs';
|
|
27
|
-
import { createMascotChat } from './mascot/ask.mjs';
|
|
28
|
-
import { mascotLang } from './mascot/strings.mjs';
|
|
29
|
-
import { refreshDesktopIntegration } from './desktop/index.mjs';
|
|
30
|
-
import { WORK_FOLDER_CONFIRM_SEC, WorkFolderStatus, isAllowedWorkFolder, resolveWorkFolder, withExtraRoots, workFolderConfirmText } from './workFolder.mjs';
|
|
31
|
-
import { showOSNotification } from './notify.mjs';
|
|
32
|
-
import { createMeetingManager, watchMeetingRequests } from './meeting/index.mjs';
|
|
33
|
-
import { createMediaHost, mediaSupported } from './meeting/recorder.mjs';
|
|
34
|
-
import { createClipboard } from './clipboard.mjs';
|
|
35
|
-
import { activeAgentRunner, buildTools, toolMap } from './toolHandlers.mjs';
|
|
36
|
-
import { createBrowserTunnels, detectLocalBrowser } from './browserTunnel.mjs';
|
|
37
|
-
import { createGuiController, detectGui } from './gui/index.mjs';
|
|
38
|
-
import { createWindowsHost } from './gui/windowsHost.mjs';
|
|
39
|
-
import { detectOfficeApps } from './office/index.mjs';
|
|
40
|
-
import { createUndoStore } from './undoStore.mjs';
|
|
41
|
-
import { createProcessManager } from './processes.mjs';
|
|
42
|
-
import { createIdempotentRunner } from './idempotency.mjs';
|
|
43
|
-
import { createWatchManager } from './deviceWatches.mjs';
|
|
44
|
-
import { createScheduleManager } from './schedule.mjs';
|
|
45
|
-
import { remoteDebuggingPage } from './dailyBrowser.mjs';
|
|
46
|
-
import { HOME_BASE, SHARED_DIR, createMultiUserHost, isMultiUserMode } from './multiUser.mjs';
|
|
47
|
-
import { createAutoUpdater } from './autoUpdate.mjs';
|
|
48
|
-
import { castLeadInConfig, createDesktopCastManager } from './desktop/desktopCast.mjs';
|
|
49
|
-
import { createDesktopWebRtcWorker } from './desktop/webrtcWorker.mjs';
|
|
50
|
-
import { CastInputRejection, createCastInputGate } from './desktop/castInput.mjs';
|
|
51
|
-
import { createCastFileDrop, createDropBatches, FileDropReason, revealInExplorer } from './desktop/castFileDrop.mjs';
|
|
52
|
-
import {
|
|
53
|
-
CAST_ACTION_FILE, askCastConsent, checkCastAction, clearCastSession, isCastLocked, lockCast, recordCastSession, unlockCast,
|
|
54
|
-
} from './desktop/castAuth.mjs';
|
|
55
|
-
import { CastConsentDecision, createCastConsent } from './desktop/castConsent.mjs';
|
|
56
|
-
import { castViewerInfo, castViewerLabel, createCastTrust, createDeviceProver } from './desktop/castTrust.mjs';
|
|
57
|
-
import { createCastTouchViewers, shouldDrawCursorInFrame } from './desktop/castTouchViewers.mjs';
|
|
58
|
-
import {
|
|
59
|
-
import {
|
|
60
|
-
import {
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
} from '
|
|
64
|
-
import {
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
const
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
const
|
|
74
|
-
|
|
75
|
-
const
|
|
76
|
-
|
|
77
|
-
const
|
|
78
|
-
/**
|
|
79
|
-
const
|
|
80
|
-
/**
|
|
81
|
-
const
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
const
|
|
92
|
-
/**
|
|
93
|
-
const
|
|
94
|
-
/**
|
|
95
|
-
const
|
|
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
|
-
if (
|
|
131
|
-
if (call.
|
|
132
|
-
if (
|
|
133
|
-
if (call.
|
|
134
|
-
return
|
|
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
|
-
creds
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
const
|
|
209
|
-
const
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
const
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
const
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
}
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
const
|
|
232
|
-
const
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
const
|
|
236
|
-
const
|
|
237
|
-
const
|
|
238
|
-
//
|
|
239
|
-
|
|
240
|
-
const
|
|
241
|
-
const
|
|
242
|
-
|
|
243
|
-
//
|
|
244
|
-
const
|
|
245
|
-
const
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
const
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
const
|
|
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
|
-
const
|
|
279
|
-
//
|
|
280
|
-
const
|
|
281
|
-
//
|
|
282
|
-
const
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
...(
|
|
295
|
-
//
|
|
296
|
-
...(multiUser ? {} : {
|
|
297
|
-
//
|
|
298
|
-
...(multiUser ? {} : {
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
}
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
const
|
|
320
|
-
const
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
//
|
|
331
|
-
const
|
|
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
|
-
const
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
const
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
const
|
|
412
|
-
|
|
413
|
-
const
|
|
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
|
-
say(chalk.
|
|
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
|
-
if (desktopWebRtc.needsFallback() && socket.connected)
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
},
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
desktopWebRtc.
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
if (
|
|
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
|
-
say(chalk.gray(`
|
|
727
|
-
say(chalk.gray(`
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
say(chalk.gray(`
|
|
731
|
-
if (
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
//
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
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
|
-
if (
|
|
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
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
const
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
//
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
855
|
-
|
|
856
|
-
|
|
857
|
-
|
|
858
|
-
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
866
|
-
|
|
867
|
-
|
|
868
|
-
|
|
869
|
-
|
|
870
|
-
|
|
871
|
-
|
|
872
|
-
|
|
873
|
-
|
|
874
|
-
|
|
875
|
-
|
|
876
|
-
|
|
877
|
-
|
|
878
|
-
|
|
879
|
-
|
|
880
|
-
|
|
881
|
-
|
|
882
|
-
|
|
883
|
-
|
|
884
|
-
|
|
885
|
-
|
|
886
|
-
|
|
887
|
-
|
|
888
|
-
|
|
889
|
-
|
|
890
|
-
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
894
|
-
|
|
895
|
-
|
|
896
|
-
|
|
897
|
-
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
901
|
-
|
|
902
|
-
|
|
903
|
-
|
|
904
|
-
|
|
905
|
-
|
|
906
|
-
|
|
907
|
-
|
|
908
|
-
|
|
909
|
-
|
|
910
|
-
|
|
911
|
-
|
|
912
|
-
|
|
913
|
-
|
|
914
|
-
|
|
915
|
-
|
|
916
|
-
|
|
917
|
-
|
|
918
|
-
|
|
919
|
-
|
|
920
|
-
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
924
|
-
|
|
925
|
-
|
|
926
|
-
|
|
927
|
-
|
|
928
|
-
|
|
929
|
-
|
|
930
|
-
|
|
931
|
-
|
|
932
|
-
|
|
933
|
-
|
|
934
|
-
|
|
935
|
-
|
|
936
|
-
|
|
937
|
-
|
|
938
|
-
|
|
939
|
-
|
|
940
|
-
|
|
941
|
-
|
|
942
|
-
|
|
943
|
-
|
|
944
|
-
|
|
945
|
-
|
|
946
|
-
|
|
947
|
-
|
|
948
|
-
|
|
949
|
-
|
|
950
|
-
|
|
951
|
-
|
|
952
|
-
|
|
953
|
-
|
|
954
|
-
|
|
955
|
-
|
|
956
|
-
|
|
957
|
-
|
|
958
|
-
|
|
959
|
-
|
|
960
|
-
|
|
961
|
-
|
|
962
|
-
|
|
963
|
-
|
|
964
|
-
|
|
965
|
-
|
|
966
|
-
|
|
967
|
-
|
|
968
|
-
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
976
|
-
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
982
|
-
|
|
983
|
-
|
|
984
|
-
|
|
985
|
-
|
|
986
|
-
|
|
987
|
-
|
|
988
|
-
|
|
989
|
-
|
|
990
|
-
|
|
991
|
-
|
|
992
|
-
|
|
993
|
-
|
|
994
|
-
|
|
995
|
-
};
|
|
996
|
-
|
|
997
|
-
|
|
998
|
-
|
|
999
|
-
|
|
1000
|
-
|
|
1001
|
-
|
|
1002
|
-
|
|
1003
|
-
|
|
1004
|
-
|
|
1005
|
-
const
|
|
1006
|
-
|
|
1007
|
-
|
|
1008
|
-
|
|
1009
|
-
|
|
1010
|
-
|
|
1011
|
-
|
|
1012
|
-
|
|
1013
|
-
|
|
1014
|
-
|
|
1015
|
-
|
|
1016
|
-
|
|
1017
|
-
|
|
1018
|
-
|
|
1019
|
-
|
|
1020
|
-
|
|
1021
|
-
|
|
1022
|
-
|
|
1023
|
-
|
|
1024
|
-
|
|
1025
|
-
|
|
1026
|
-
|
|
1027
|
-
|
|
1028
|
-
|
|
1029
|
-
|
|
1030
|
-
|
|
1031
|
-
|
|
1032
|
-
|
|
1033
|
-
|
|
1034
|
-
|
|
1035
|
-
|
|
1036
|
-
|
|
1037
|
-
}
|
|
1038
|
-
|
|
1039
|
-
|
|
1040
|
-
|
|
1041
|
-
|
|
1042
|
-
|
|
1043
|
-
|
|
1044
|
-
|
|
1045
|
-
|
|
1046
|
-
|
|
1047
|
-
|
|
1048
|
-
|
|
1049
|
-
|
|
1050
|
-
|
|
1051
|
-
|
|
1052
|
-
|
|
1053
|
-
|
|
1054
|
-
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
}
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1089
|
-
|
|
1090
|
-
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
|
|
1097
|
-
|
|
1098
|
-
|
|
1099
|
-
|
|
1100
|
-
|
|
1101
|
-
|
|
1102
|
-
|
|
1103
|
-
|
|
1104
|
-
|
|
1105
|
-
|
|
1106
|
-
|
|
1107
|
-
|
|
1108
|
-
|
|
1109
|
-
|
|
1110
|
-
|
|
1111
|
-
|
|
1112
|
-
|
|
1113
|
-
|
|
1114
|
-
|
|
1115
|
-
|
|
1116
|
-
|
|
1117
|
-
|
|
1118
|
-
|
|
1119
|
-
|
|
1120
|
-
|
|
1121
|
-
|
|
1122
|
-
|
|
1123
|
-
|
|
1124
|
-
|
|
1125
|
-
|
|
1126
|
-
|
|
1127
|
-
|
|
1128
|
-
|
|
1129
|
-
|
|
1130
|
-
|
|
1131
|
-
if (
|
|
1132
|
-
|
|
1133
|
-
hold(
|
|
1134
|
-
|
|
1135
|
-
|
|
1136
|
-
|
|
1137
|
-
|
|
1138
|
-
|
|
1139
|
-
|
|
1140
|
-
|
|
1141
|
-
|
|
1142
|
-
|
|
1143
|
-
|
|
1144
|
-
|
|
1145
|
-
|
|
1146
|
-
|
|
1147
|
-
|
|
1148
|
-
|
|
1149
|
-
|
|
1150
|
-
|
|
1151
|
-
|
|
1152
|
-
|
|
1153
|
-
|
|
1154
|
-
|
|
1155
|
-
|
|
1156
|
-
|
|
1157
|
-
|
|
1158
|
-
|
|
1159
|
-
|
|
1160
|
-
|
|
1161
|
-
|
|
1162
|
-
|
|
1163
|
-
|
|
1164
|
-
|
|
1165
|
-
|
|
1166
|
-
|
|
1167
|
-
|
|
1168
|
-
|
|
1169
|
-
|
|
1170
|
-
|
|
1171
|
-
|
|
1172
|
-
|
|
1173
|
-
|
|
1174
|
-
|
|
1175
|
-
|
|
1176
|
-
|
|
1177
|
-
|
|
1178
|
-
|
|
1179
|
-
|
|
1180
|
-
|
|
1181
|
-
|
|
1182
|
-
|
|
1183
|
-
|
|
1184
|
-
|
|
1185
|
-
|
|
1186
|
-
|
|
1187
|
-
|
|
1188
|
-
|
|
1189
|
-
|
|
1190
|
-
|
|
1191
|
-
|
|
1192
|
-
|
|
1193
|
-
|
|
1194
|
-
|
|
1195
|
-
|
|
1196
|
-
|
|
1197
|
-
|
|
1198
|
-
|
|
1199
|
-
|
|
1200
|
-
|
|
1201
|
-
|
|
1202
|
-
|
|
1203
|
-
|
|
1204
|
-
|
|
1205
|
-
|
|
1206
|
-
|
|
1207
|
-
|
|
1208
|
-
|
|
1209
|
-
|
|
1210
|
-
|
|
1211
|
-
|
|
1212
|
-
|
|
1213
|
-
|
|
1214
|
-
|
|
1215
|
-
|
|
1216
|
-
|
|
1217
|
-
|
|
1218
|
-
|
|
1219
|
-
|
|
1220
|
-
|
|
1221
|
-
|
|
1222
|
-
|
|
1223
|
-
|
|
1224
|
-
|
|
1225
|
-
|
|
1226
|
-
|
|
1227
|
-
|
|
1228
|
-
|
|
1229
|
-
|
|
1230
|
-
|
|
1231
|
-
|
|
1232
|
-
|
|
1233
|
-
|
|
1234
|
-
|
|
1235
|
-
|
|
1236
|
-
|
|
1237
|
-
|
|
1238
|
-
|
|
1239
|
-
|
|
1240
|
-
|
|
1241
|
-
|
|
1242
|
-
|
|
1243
|
-
|
|
1244
|
-
|
|
1245
|
-
|
|
1246
|
-
|
|
1247
|
-
|
|
1248
|
-
|
|
1249
|
-
if (
|
|
1250
|
-
|
|
1251
|
-
|
|
1252
|
-
|
|
1253
|
-
|
|
1254
|
-
|
|
1255
|
-
|
|
1256
|
-
|
|
1257
|
-
|
|
1258
|
-
|
|
1259
|
-
|
|
1260
|
-
|
|
1261
|
-
|
|
1262
|
-
|
|
1263
|
-
|
|
1264
|
-
|
|
1265
|
-
|
|
1266
|
-
|
|
1267
|
-
|
|
1268
|
-
|
|
1269
|
-
|
|
1270
|
-
}));
|
|
1271
|
-
socket.on(DeviceEvent.
|
|
1272
|
-
|
|
1273
|
-
const
|
|
1274
|
-
|
|
1275
|
-
|
|
1276
|
-
|
|
1277
|
-
|
|
1278
|
-
|
|
1279
|
-
|
|
1280
|
-
|
|
1281
|
-
|
|
1282
|
-
|
|
1283
|
-
|
|
1284
|
-
|
|
1285
|
-
|
|
1286
|
-
|
|
1287
|
-
|
|
1288
|
-
|
|
1289
|
-
|
|
1290
|
-
|
|
1291
|
-
|
|
1292
|
-
|
|
1293
|
-
|
|
1294
|
-
|
|
1295
|
-
|
|
1296
|
-
|
|
1297
|
-
|
|
1298
|
-
|
|
1299
|
-
|
|
1300
|
-
|
|
1301
|
-
|
|
1302
|
-
})
|
|
1303
|
-
|
|
1304
|
-
|
|
1305
|
-
|
|
1306
|
-
|
|
1307
|
-
|
|
1308
|
-
|
|
1309
|
-
|
|
1310
|
-
|
|
1311
|
-
|
|
1312
|
-
|
|
1313
|
-
|
|
1314
|
-
|
|
1315
|
-
|
|
1316
|
-
|
|
1317
|
-
|
|
1318
|
-
|
|
1319
|
-
const
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
if (
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
if (
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
}
|
|
1352
|
-
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
if (payload?.
|
|
1391
|
-
|
|
1392
|
-
|
|
1393
|
-
|
|
1394
|
-
|
|
1395
|
-
|
|
1396
|
-
|
|
1397
|
-
if (
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1403
|
-
|
|
1404
|
-
|
|
1405
|
-
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1409
|
-
|
|
1410
|
-
|
|
1411
|
-
|
|
1412
|
-
|
|
1413
|
-
|
|
1414
|
-
|
|
1415
|
-
}
|
|
1416
|
-
|
|
1417
|
-
|
|
1418
|
-
|
|
1419
|
-
const
|
|
1420
|
-
|
|
1421
|
-
|
|
1422
|
-
|
|
1423
|
-
|
|
1424
|
-
|
|
1425
|
-
|
|
1426
|
-
|
|
1427
|
-
|
|
1428
|
-
|
|
1429
|
-
|
|
1430
|
-
|
|
1431
|
-
|
|
1432
|
-
|
|
1433
|
-
|
|
1434
|
-
|
|
1435
|
-
|
|
1436
|
-
|
|
1437
|
-
|
|
1438
|
-
|
|
1439
|
-
|
|
1440
|
-
|
|
1441
|
-
|
|
1442
|
-
|
|
1443
|
-
|
|
1444
|
-
|
|
1445
|
-
|
|
1446
|
-
|
|
1447
|
-
|
|
1448
|
-
|
|
1449
|
-
|
|
1450
|
-
|
|
1451
|
-
|
|
1452
|
-
|
|
1453
|
-
|
|
1454
|
-
|
|
1455
|
-
|
|
1456
|
-
}
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import axios from 'axios';
|
|
5
|
+
import chalk from 'chalk';
|
|
6
|
+
import readline from 'readline/promises';
|
|
7
|
+
import { io } from 'socket.io-client';
|
|
8
|
+
import { DEFAULT_AIVIN_BASE_URL } from '../context.mjs';
|
|
9
|
+
import { readActiveServer, resolveServerUrl as normalizeServerUrl, setActiveServer } from '../servers.mjs';
|
|
10
|
+
import { logActivity } from './activityLog.mjs';
|
|
11
|
+
import { DEFAULT_SCOPE_LIMITS, DEVICE_NAMESPACE, KILL_SWITCH_FILE, REMOTE_CONFIG_DIR, CastState, DeviceAccess, DeviceErrorCode, DeviceEvent, HoldPhase, MAX_RESULT_BYTES, PROTOCOL_VERSION, REMOTE_IDEM_FILE, REMOTE_OUTBOX_FILE, ServerFeature, ToolGroup } from './constants.mjs';
|
|
12
|
+
import { CallState, createCallLedger } from './callLedger.mjs';
|
|
13
|
+
import { fallBackToPreviousToken, settleRotation } from './tokenRotation.mjs';
|
|
14
|
+
import { configureProxy, proxyAgentFor } from './netProxy.mjs';
|
|
15
|
+
import { createKeepAwake } from './keepAwake.mjs';
|
|
16
|
+
import { createPolicyGuard, describeCall, evaluateLocalPolicy } from './localPolicy.mjs';
|
|
17
|
+
import { ConfirmResult, createLocalConfirmer } from './localConfirm.mjs';
|
|
18
|
+
import { clearDeviceCredentials, confirmServerCredentialMigration, credentialsFromEnv, listDevices, loadDeviceCredentials, pairDevice, pairDeviceWithCode, readStoredTokenFresh, saveDeviceCredentials } from './credentials.mjs';
|
|
19
|
+
import { ensureMemoryLoaded, memoryStats, stopWatchingMemory, watchMemoryDir } from './deviceMemory.mjs';
|
|
20
|
+
import { buildCatalog, buildDeviceProfile } from './deviceProfile.mjs';
|
|
21
|
+
import { createFileIndex, indexRootsFor } from './fileIndexer.mjs';
|
|
22
|
+
import { createScheduler } from './scheduler.mjs';
|
|
23
|
+
import { acquireDaemonLock, lockHolder } from './daemonLock.mjs';
|
|
24
|
+
import { randomUUID } from 'crypto';
|
|
25
|
+
import { DeviceToolError, fullAccessRoots, isRemotePaused, setRemotePaused } from './sandbox.mjs';
|
|
26
|
+
import { createMascot, HostEvent as MascotHostEvent, loadMascotSettings, saveMascotSettings } from './mascot/index.mjs';
|
|
27
|
+
import { createMascotChat } from './mascot/ask.mjs';
|
|
28
|
+
import { mascotLang } from './mascot/strings.mjs';
|
|
29
|
+
import { refreshDesktopIntegration } from './desktop/index.mjs';
|
|
30
|
+
import { WORK_FOLDER_CONFIRM_SEC, WorkFolderStatus, isAllowedWorkFolder, resolveWorkFolder, withExtraRoots, workFolderConfirmText } from './workFolder.mjs';
|
|
31
|
+
import { showOSNotification } from './notify.mjs';
|
|
32
|
+
import { createMeetingManager, watchMeetingRequests } from './meeting/index.mjs';
|
|
33
|
+
import { createMediaHost, mediaSupported } from './meeting/recorder.mjs';
|
|
34
|
+
import { createClipboard } from './clipboard.mjs';
|
|
35
|
+
import { activeAgentRunner, activeLocalLlm, buildTools, toolMap } from './toolHandlers.mjs';
|
|
36
|
+
import { createBrowserTunnels, detectLocalBrowser } from './browserTunnel.mjs';
|
|
37
|
+
import { createGuiController, detectGui } from './gui/index.mjs';
|
|
38
|
+
import { createWindowsHost } from './gui/windowsHost.mjs';
|
|
39
|
+
import { detectOfficeApps } from './office/index.mjs';
|
|
40
|
+
import { createUndoStore } from './undoStore.mjs';
|
|
41
|
+
import { createProcessManager } from './processes.mjs';
|
|
42
|
+
import { createIdempotentRunner } from './idempotency.mjs';
|
|
43
|
+
import { createWatchManager } from './deviceWatches.mjs';
|
|
44
|
+
import { createScheduleManager } from './schedule.mjs';
|
|
45
|
+
import { remoteDebuggingPage } from './dailyBrowser.mjs';
|
|
46
|
+
import { HOME_BASE, SHARED_DIR, createMultiUserHost, isMultiUserMode } from './multiUser.mjs';
|
|
47
|
+
import { createAutoUpdater } from './autoUpdate.mjs';
|
|
48
|
+
import { castLeadInConfig, createDesktopCastManager } from './desktop/desktopCast.mjs';
|
|
49
|
+
import { createDesktopWebRtcWorker } from './desktop/webrtcWorker.mjs';
|
|
50
|
+
import { CastInputRejection, createCastInputGate } from './desktop/castInput.mjs';
|
|
51
|
+
import { createCastFileDrop, createDropBatches, FileDropReason, revealInExplorer } from './desktop/castFileDrop.mjs';
|
|
52
|
+
import {
|
|
53
|
+
CAST_ACTION_FILE, askCastConsent, checkCastAction, clearCastSession, isCastLocked, lockCast, recordCastSession, unlockCast,
|
|
54
|
+
} from './desktop/castAuth.mjs';
|
|
55
|
+
import { CastConsentDecision, createCastConsent } from './desktop/castConsent.mjs';
|
|
56
|
+
import { castViewerInfo, castViewerLabel, createCastTrust, createDeviceProver } from './desktop/castTrust.mjs';
|
|
57
|
+
import { createCastTouchViewers, shouldDrawCursorInFrame } from './desktop/castTouchViewers.mjs';
|
|
58
|
+
import { prepareHumanIdle, readHumanIdleMs } from './desktop/humanIdle.mjs';
|
|
59
|
+
import { prepareIdentify, showIdentify } from './desktop/identifyOverlay.mjs';
|
|
60
|
+
import { findWindowTitle, prepareWindowProbe } from './desktop/windowProbe.mjs';
|
|
61
|
+
import { isOwnAddress } from './desktop/desktopWebRtc.mjs';
|
|
62
|
+
import { createConfirmBarrier } from './confirmBarrier.mjs';
|
|
63
|
+
import { newInputTag } from './humanInput.mjs';
|
|
64
|
+
import {
|
|
65
|
+
BootAction, MAX_BOOTS_BEFORE_ROLLBACK, RESTART_EXIT_CODE, UPDATE_CONFIRM_AFTER_MS, UPDATE_ROLLED_BACK, checkBootAfterUpdate, cleanupRetired, clearStaleInstalledMarker,
|
|
66
|
+
confirmUpdate, ingestSupervisorRollback, isStandaloneBinary, noteCleanExit, updateProfile,
|
|
67
|
+
} from '../selfUpdate.mjs';
|
|
68
|
+
import { cliLaunchCommand, detectSupervisor } from './autoStart.mjs';
|
|
69
|
+
|
|
70
|
+
const HEARTBEAT_MS = 20_000;
|
|
71
|
+
// 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
|
|
72
|
+
// 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).
|
|
73
|
+
const RECONNECT_DELAY_MAX_MS = 10_000;
|
|
74
|
+
const MULTI_USER_RECONNECT_DELAY_MAX_MS = 2_000;
|
|
75
|
+
const STREAM_FLUSH_MS = 150;
|
|
76
|
+
const STREAM_FLUSH_BYTES = 16 * 1024;
|
|
77
|
+
const ACK_TIMEOUT_MS = 10_000;
|
|
78
|
+
/** 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. */
|
|
79
|
+
const EMBED_TIMEOUT_MS = 60_000;
|
|
80
|
+
/** 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. */
|
|
81
|
+
const PAUSE_POLL_MS = 2000;
|
|
82
|
+
/** 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. */
|
|
83
|
+
const RESULT_ACK_TIMEOUT_MS = 15_000;
|
|
84
|
+
/** 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. */
|
|
85
|
+
const RESTARTING_ACK_TIMEOUT_MS = 2_000;
|
|
86
|
+
const RESTART_EXPECT_BACK_MS = 30_000;
|
|
87
|
+
/**
|
|
88
|
+
* Mất kết nối máy chủ giữa phiên xem màn hình: giữ phiên bấy nhiêu lâu (người xem WebRTC vẫn xem được — kênh đi thẳng). Phải dài hơn nhịp nối
|
|
89
|
+
* lại tối đa (10 s + 50 % ngẫu nhiên) — trước đây 8 s nên gần như mỗi lần máy chủ deploy / mạng chập chờn là phiên bị giết.
|
|
90
|
+
*/
|
|
91
|
+
const CAST_DISCONNECT_GRACE_MS = 20_000;
|
|
92
|
+
/** Nối lại khi phiên vẫn chạy: máy chủ phải mời phát lại / dừng phiên trong bấy nhiêu lâu, không thì phiên đã hết hạn ở máy chủ → dừng. */
|
|
93
|
+
const CAST_RECONFIRM_MS = 20_000;
|
|
94
|
+
/** Tiến trình quay sập: tự mở lại tối đa bấy nhiêu lần mỗi phút trước khi kết thúc phiên. */
|
|
95
|
+
const CAST_MAX_RESTARTS_PER_MIN = 2;
|
|
96
|
+
/** Lý do dừng chỉ là GIÁN ĐOẠN (phiên ở máy chủ còn, được mời phát lại): giữ đồng ý của chủ máy, không hỏi lại. */
|
|
97
|
+
const CAST_RESUMABLE_REASONS = new Set(['disconnected']);
|
|
98
|
+
/** Lý do dừng do chủ máy / daemon: đóng luôn mọi hộp xin xem đang mở. */
|
|
99
|
+
const CAST_SHUTDOWN_REASONS = new Set(['paused', 'device_stopped', 'user_revoked']);
|
|
100
|
+
|
|
101
|
+
/** 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). */
|
|
102
|
+
function createStreamer(socket, callId) {
|
|
103
|
+
const buffers = { stdout: '', stderr: '' };
|
|
104
|
+
let timer = null;
|
|
105
|
+
const flush = () => {
|
|
106
|
+
clearTimeout(timer);
|
|
107
|
+
timer = null;
|
|
108
|
+
for (const stream of Object.keys(buffers)) {
|
|
109
|
+
if (!buffers[stream]) continue;
|
|
110
|
+
if (socket.connected) socket.emit(DeviceEvent.STREAM, { call_id: callId, stream, chunk: buffers[stream] });
|
|
111
|
+
buffers[stream] = '';
|
|
112
|
+
}
|
|
113
|
+
};
|
|
114
|
+
const push = (stream, chunk) => {
|
|
115
|
+
buffers[stream] = (buffers[stream] || '') + chunk;
|
|
116
|
+
if (buffers[stream].length >= STREAM_FLUSH_BYTES) flush();
|
|
117
|
+
else if (!timer) timer = setTimeout(flush, STREAM_FLUSH_MS);
|
|
118
|
+
};
|
|
119
|
+
return { push, flush };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
let unhandledRejectionHooked = false;
|
|
123
|
+
const MAX_CALL_ID = 64;
|
|
124
|
+
const MAX_TOOL_NAME = 128;
|
|
125
|
+
|
|
126
|
+
const isPlainObject = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
|
|
127
|
+
|
|
128
|
+
/** 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ố). */
|
|
129
|
+
export function isValidDeviceCall(call) {
|
|
130
|
+
if (!isPlainObject(call)) return false;
|
|
131
|
+
if (typeof call.call_id !== 'string' || !call.call_id || call.call_id.length > MAX_CALL_ID) return false;
|
|
132
|
+
if (typeof call.tool !== 'string' || !call.tool || call.tool.length > MAX_TOOL_NAME) return false;
|
|
133
|
+
if (call.args !== undefined && call.args !== null && !isPlainObject(call.args)) return false;
|
|
134
|
+
if (call.timeout_ms !== undefined && call.timeout_ms !== null && !Number.isFinite(call.timeout_ms)) return false;
|
|
135
|
+
if (call.user_scope !== undefined && call.user_scope !== null && typeof call.user_scope !== 'string') return false;
|
|
136
|
+
if (call.idem_key !== undefined && call.idem_key !== null && (typeof call.idem_key !== 'string' || call.idem_key.length > 80)) return false;
|
|
137
|
+
if (call.purpose !== undefined && call.purpose !== null && typeof call.purpose !== 'string') return false;
|
|
138
|
+
return true;
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
function boundedResult(outcome) {
|
|
142
|
+
if (!outcome.ok) return outcome;
|
|
143
|
+
let size;
|
|
144
|
+
try { size = Buffer.byteLength(JSON.stringify(outcome.result ?? null)); } catch { size = MAX_RESULT_BYTES + 1; }
|
|
145
|
+
if (size <= MAX_RESULT_BYTES) return outcome;
|
|
146
|
+
return { ok: false, error: `Result too large (${size} bytes) — read smaller ranges`, error_code: DeviceErrorCode.OUTPUT_TOO_LARGE, duration_ms: outcome.duration_ms };
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
/**
|
|
150
|
+
* 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
|
|
151
|
+
* 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,
|
|
152
|
+
* 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ủ
|
|
153
|
+
* thì dùng `--server` (hoặc `--repair`).
|
|
154
|
+
*/
|
|
155
|
+
export function resolveServerUrl(options, saved, env = process.env) {
|
|
156
|
+
const explicit = options.server || options.serverUrl;
|
|
157
|
+
const url = explicit || (options.code ? DEFAULT_AIVIN_BASE_URL : null)
|
|
158
|
+
|| readActiveServer()
|
|
159
|
+
|| (options.repair ? undefined : saved?.server_url)
|
|
160
|
+
|| env.AIVIN_BASE_URL || env.AIVIN_SERVER
|
|
161
|
+
|| DEFAULT_AIVIN_BASE_URL;
|
|
162
|
+
return normalizeServerUrl(url);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* 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à
|
|
167
|
+
* 02/11/2026). Không có terminal (lệnh do agent / script chạy) thì từ chối.
|
|
168
|
+
*/
|
|
169
|
+
async function confirmServerChange(saved, serverUrl) {
|
|
170
|
+
if (!saved?.server_url || saved.server_url === serverUrl) return;
|
|
171
|
+
if (!process.stdin.isTTY || !process.stdout.isTTY) {
|
|
172
|
+
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.`);
|
|
173
|
+
}
|
|
174
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout });
|
|
175
|
+
try {
|
|
176
|
+
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 ý: `));
|
|
177
|
+
if (!/^\s*(co|có|yes|y)\s*$/i.test(answer)) throw new Error('Đã huỷ — máy giữ kết nối cũ.');
|
|
178
|
+
} finally {
|
|
179
|
+
rl.close();
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
/**
|
|
184
|
+
* 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;
|
|
185
|
+
* không thì ghép mới bằng API key đang đăng nhập.
|
|
186
|
+
*/
|
|
187
|
+
async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name, repair, profile }) {
|
|
188
|
+
const current = loadDeviceCredentials();
|
|
189
|
+
await confirmServerChange(current, serverUrl);
|
|
190
|
+
setActiveServer(serverUrl);
|
|
191
|
+
let creds = loadDeviceCredentials(serverUrl);
|
|
192
|
+
if (code) {
|
|
193
|
+
creds = await pairDeviceWithCode({ serverUrl, code, roots, name, profile });
|
|
194
|
+
} else if (!creds || repair) {
|
|
195
|
+
creds = await pairDevice({ serverUrl, apiKey, roots, name, profile });
|
|
196
|
+
} else if (rootsGiven && JSON.stringify(roots) !== JSON.stringify(creds.roots)) {
|
|
197
|
+
creds.roots = roots;
|
|
198
|
+
saveDeviceCredentials(creds);
|
|
199
|
+
}
|
|
200
|
+
return creds;
|
|
201
|
+
}
|
|
202
|
+
|
|
203
|
+
/**
|
|
204
|
+
* `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,
|
|
205
|
+
* 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).
|
|
206
|
+
*/
|
|
207
|
+
export async function pairWithCodeOnly(options) {
|
|
208
|
+
const saved = loadDeviceCredentials();
|
|
209
|
+
const serverUrl = resolveServerUrl(options, saved);
|
|
210
|
+
await confirmServerChange(saved, serverUrl);
|
|
211
|
+
configureProxy({ explicit: options.proxy });
|
|
212
|
+
const fullAccess = !options.dir && !!options.fullAccess;
|
|
213
|
+
const roots = (fullAccess ? fullAccessRoots() : [options.dir || process.cwd()]).map((r) => path.resolve(r));
|
|
214
|
+
const access = fullAccess ? DeviceAccess.FULL : DeviceAccess.FOLDERS;
|
|
215
|
+
const profile = { ...buildDeviceProfile(fullAccess ? [os.homedir()] : roots), roots, access };
|
|
216
|
+
const creds = await pairDeviceWithCode({ serverUrl, code: options.code, roots, name: options.name, profile });
|
|
217
|
+
setActiveServer(serverUrl);
|
|
218
|
+
saveDeviceCredentials({ ...creds, access });
|
|
219
|
+
const stale = lockHolder();
|
|
220
|
+
if (stale) try { process.kill(stale); } catch { /* vừa tự thoát */ }
|
|
221
|
+
return { creds, stopped: stale };
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
/**
|
|
225
|
+
* 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
|
|
226
|
+
* 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
|
|
227
|
+
* trường là sàn cứng trên máy — BE không đổi được.
|
|
228
|
+
*/
|
|
229
|
+
export async function startRemoteClient(options = {}) {
|
|
230
|
+
// 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.
|
|
231
|
+
const multiUser = isMultiUserMode(options);
|
|
232
|
+
const envCreds = multiUser ? credentialsFromEnv() : null;
|
|
233
|
+
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).');
|
|
234
|
+
if (multiUser && process.platform === 'win32') throw new Error('--multi-user chỉ chạy trên Linux (container máy tính tổ chức).');
|
|
235
|
+
const savedHint = envCreds || loadDeviceCredentials();
|
|
236
|
+
const serverUrl = resolveServerUrl(options, savedHint);
|
|
237
|
+
const saved = envCreds || loadDeviceCredentials(serverUrl);
|
|
238
|
+
// Trước mọi lời gọi mạng (ghép máy cũng đi qua proxy).
|
|
239
|
+
const proxy = configureProxy({ explicit: options.proxy });
|
|
240
|
+
const apiKey = options.apiKey ?? process.env.API_KEY;
|
|
241
|
+
const rootsGiven = Boolean(options.dir) && !multiUser;
|
|
242
|
+
// 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.
|
|
243
|
+
// 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.
|
|
244
|
+
const fullAccess = multiUser || (!rootsGiven && (!!options.fullAccess || (!options.code && saved?.access === DeviceAccess.FULL)));
|
|
245
|
+
const roots = multiUser ? [HOME_BASE, SHARED_DIR] : fullAccess ? fullAccessRoots()
|
|
246
|
+
: withExtraRoots(rootsGiven ? [path.resolve(options.dir)] : (saved?.access !== DeviceAccess.FULL && saved?.roots?.length ? saved.roots : [process.cwd()]), saved?.extra_roots);
|
|
247
|
+
// 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.
|
|
248
|
+
const scanRoots = multiUser ? [] : fullAccess ? [os.homedir()] : roots;
|
|
249
|
+
const quiet = !!options.quiet;
|
|
250
|
+
const say = (...args) => { if (!quiet) console.log(...args); };
|
|
251
|
+
|
|
252
|
+
// 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).
|
|
253
|
+
const releaseLock = acquireDaemonLock({ takeOver: !!options.code });
|
|
254
|
+
// 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
|
|
255
|
+
// 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.
|
|
256
|
+
const selfManaged = !multiUser && isStandaloneBinary();
|
|
257
|
+
const supervisor = multiUser ? null : detectSupervisor({ quiet });
|
|
258
|
+
const autoUpdateEnabled = !multiUser && options.autoUpdate !== false && process.env.AIVIN_AUTO_UPDATE !== '0';
|
|
259
|
+
if (selfManaged) {
|
|
260
|
+
// 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.
|
|
261
|
+
const supervisorRollback = ingestSupervisorRollback();
|
|
262
|
+
if (supervisorRollback) {
|
|
263
|
+
logActivity({ type: 'self_update_rollback', version: supervisorRollback, by: 'supervisor' });
|
|
264
|
+
say(chalk.yellow(`↩ aivin ${supervisorRollback} sập ngay khi khởi động — đã trả về bản này và sẽ bỏ qua ${supervisorRollback}.`));
|
|
265
|
+
}
|
|
266
|
+
const boot = checkBootAfterUpdate();
|
|
267
|
+
if (boot.action === BootAction.ROLLED_BACK) {
|
|
268
|
+
releaseLock();
|
|
269
|
+
logActivity({ type: 'self_update_rollback', version: boot.version, previous: boot.previous });
|
|
270
|
+
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\`.`);
|
|
271
|
+
err.code = UPDATE_ROLLED_BACK;
|
|
272
|
+
err.restart = !!supervisor;
|
|
273
|
+
throw err;
|
|
274
|
+
}
|
|
275
|
+
clearStaleInstalledMarker();
|
|
276
|
+
cleanupRetired();
|
|
277
|
+
}
|
|
278
|
+
const access = fullAccess ? DeviceAccess.FULL : DeviceAccess.FOLDERS;
|
|
279
|
+
// 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.
|
|
280
|
+
const browser = options.browser === false || multiUser ? null : detectLocalBrowser();
|
|
281
|
+
// Đ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.
|
|
282
|
+
const guiProfile = detectGui({ disabled: options.gui === false, multiUser });
|
|
283
|
+
// 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ì).
|
|
284
|
+
const officeApps = detectOfficeApps({ multiUser });
|
|
285
|
+
// 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.
|
|
286
|
+
const policyGuard = createPolicyGuard({
|
|
287
|
+
onTamper: (effective) => {
|
|
288
|
+
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}).`));
|
|
289
|
+
logActivity({ type: 'local_policy_tampered', confirm: effective.confirm });
|
|
290
|
+
},
|
|
291
|
+
});
|
|
292
|
+
const profile = {
|
|
293
|
+
...buildDeviceProfile(scanRoots), roots: roots.map((r) => path.resolve(r)), access,
|
|
294
|
+
...(browser ? { browser } : {}), ...(guiProfile ? { gui: guiProfile } : {}), ...(officeApps.length ? { apps: officeApps } : {}),
|
|
295
|
+
// Theo dõi kích hoạt việc (CLI ≥ 1.0.9) — máy tính tổ chức không có.
|
|
296
|
+
...(multiUser ? {} : { watch: true }),
|
|
297
|
+
// 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ó.
|
|
298
|
+
...(multiUser ? {} : { direct_transfer: true }),
|
|
299
|
+
// 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.
|
|
300
|
+
...(multiUser ? {} : { local_confirm: policyGuard.read().confirm }),
|
|
301
|
+
// 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ủ.
|
|
302
|
+
...(multiUser ? {} : { update: updateProfile({ enabled: autoUpdateEnabled }) }),
|
|
303
|
+
};
|
|
304
|
+
let creds;
|
|
305
|
+
try {
|
|
306
|
+
creds = envCreds || await ensurePaired({ serverUrl, apiKey, code: options.code, roots, rootsGiven, name: options.name, repair: options.repair, profile });
|
|
307
|
+
} catch (e) {
|
|
308
|
+
releaseLock();
|
|
309
|
+
throw e;
|
|
310
|
+
}
|
|
311
|
+
if (!envCreds && (creds.access !== access || JSON.stringify(creds.roots) !== JSON.stringify(profile.roots))) {
|
|
312
|
+
creds.access = access;
|
|
313
|
+
creds.roots = profile.roots;
|
|
314
|
+
saveDeviceCredentials(creds);
|
|
315
|
+
}
|
|
316
|
+
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.`));
|
|
317
|
+
ensureMemoryLoaded();
|
|
318
|
+
watchMemoryDir();
|
|
319
|
+
const fileIndex = multiUser ? null : createFileIndex(indexRootsFor(roots, fullAccess));
|
|
320
|
+
const useDailyBrowser = options.dailyBrowser === true;
|
|
321
|
+
const browserTunnels = browser ? createBrowserTunnels({ serverUrl, deviceToken: () => creds.device_token, browser, useDailyBrowser, say: (m) => say(chalk.cyan(m)) }) : null;
|
|
322
|
+
// 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.
|
|
323
|
+
const guiHost = guiProfile ? createWindowsHost() : null;
|
|
324
|
+
const officeHost = officeApps.length ? createWindowsHost() : null;
|
|
325
|
+
// 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).
|
|
326
|
+
const gui = guiProfile ? createGuiController({
|
|
327
|
+
fullAccess, host: guiHost, say: (m) => say(chalk.magenta(m)),
|
|
328
|
+
defaultWindow: () => (mascot.pid() ? { avoid_pid: mascot.pid(), fallback: mascotChat?.userWindow()?.window } : null),
|
|
329
|
+
}) : null;
|
|
330
|
+
// 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.
|
|
331
|
+
const undo = multiUser ? null : createUndoStore();
|
|
332
|
+
void undo?.cleanup().catch(() => undefined);
|
|
333
|
+
const processes = createProcessManager();
|
|
334
|
+
// 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.
|
|
335
|
+
const keepAwake = createKeepAwake({
|
|
336
|
+
enabled: !multiUser && options.keepAwake !== false && process.env.AIVIN_REMOTE_KEEP_AWAKE !== '0',
|
|
337
|
+
say: (m) => say(chalk.gray(` ${m}`)),
|
|
338
|
+
});
|
|
339
|
+
// Phiên xem + điều khiển màn hình: giữ cả màn hình sáng — chỉ xem không thao tác thì máy không tự khoá giữa phiên (màn hình khoá không mở
|
|
340
|
+
// lại được từ xa).
|
|
341
|
+
const castAwake = createKeepAwake({
|
|
342
|
+
enabled: !multiUser && options.keepAwake !== false && process.env.AIVIN_REMOTE_KEEP_AWAKE !== '0',
|
|
343
|
+
display: true, startDelayMs: 0, idleMs: 5_000,
|
|
344
|
+
say: (m) => say(chalk.gray(` ${m}`)),
|
|
345
|
+
});
|
|
346
|
+
let castAwakeHeld = false;
|
|
347
|
+
const holdCastAwake = (on) => {
|
|
348
|
+
if (on === castAwakeHeld) return;
|
|
349
|
+
castAwakeHeld = on;
|
|
350
|
+
if (on) castAwake.hold();
|
|
351
|
+
else castAwake.release();
|
|
352
|
+
};
|
|
353
|
+
let procAwake = false;
|
|
354
|
+
const syncProcAwake = () => {
|
|
355
|
+
const running = !!processes.hasRunning?.();
|
|
356
|
+
if (running === procAwake) return;
|
|
357
|
+
procAwake = running;
|
|
358
|
+
if (running) keepAwake.hold();
|
|
359
|
+
else keepAwake.release();
|
|
360
|
+
};
|
|
361
|
+
const schedules = multiUser ? null : createScheduleManager({ undo });
|
|
362
|
+
// 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.
|
|
363
|
+
const watches = multiUser ? null : createWatchManager({
|
|
364
|
+
roots, say: (m) => say(chalk.cyan(m)),
|
|
365
|
+
emit: (payload) => { if (socket?.connected) socket.emit(DeviceEvent.EVENT, payload); },
|
|
366
|
+
});
|
|
367
|
+
// 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).
|
|
368
|
+
const transfer = multiUser ? null : { serverUrl, deviceToken: () => creds.device_token };
|
|
369
|
+
// 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.
|
|
370
|
+
const media = !multiUser && mediaSupported() && options.meetings !== false && process.env.AIVIN_REMOTE_MEETINGS !== '0' ? createMediaHost() : null;
|
|
371
|
+
const meetings = media ? createMeetingManager({
|
|
372
|
+
roots, media, lang: mascotLang(process.env, process.platform, creds?.lang),
|
|
373
|
+
say: (m) => say(chalk.cyan(m)),
|
|
374
|
+
notify: showOSNotification,
|
|
375
|
+
isPaused: isRemotePaused,
|
|
376
|
+
keepAwake,
|
|
377
|
+
// Đ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).
|
|
378
|
+
micBusy: () => !!mascotChat?.inCall(),
|
|
379
|
+
// 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.
|
|
380
|
+
stt: async (audio, lang) => {
|
|
381
|
+
const deadline = Date.now() + 10 * 60_000;
|
|
382
|
+
while (!socket?.connected) {
|
|
383
|
+
if (Date.now() > deadline) throw new Error('offline');
|
|
384
|
+
await new Promise((r) => setTimeout(r, 5000));
|
|
385
|
+
}
|
|
386
|
+
return socket.timeout(60_000).emitWithAck(DeviceEvent.STT, { audio, lang });
|
|
387
|
+
},
|
|
388
|
+
// 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.
|
|
389
|
+
followUp: async (text) => {
|
|
390
|
+
if (!socket?.connected) return { ok: false, error: 'offline' };
|
|
391
|
+
if (mascotChat) {
|
|
392
|
+
if (mascotChat.busy()) return { ok: false, error: 'busy' };
|
|
393
|
+
void mascotChat.ask(text);
|
|
394
|
+
return { ok: true };
|
|
395
|
+
}
|
|
396
|
+
const ack = await socket.timeout(15_000).emitWithAck(DeviceEvent.CHAT, { text, request_id: `meeting-${Date.now()}` });
|
|
397
|
+
return ack?.ok ? { ok: true } : { ok: false, error: ack?.error || 'failed' };
|
|
398
|
+
},
|
|
399
|
+
}) : null;
|
|
400
|
+
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() };
|
|
401
|
+
const host = multiUser ? createMultiUserHost({ baseEnv: env, say: (m) => say(chalk.gray(m)) }) : null;
|
|
402
|
+
host?.start();
|
|
403
|
+
const tools = buildTools(env);
|
|
404
|
+
const byName = toolMap(tools);
|
|
405
|
+
// Mô hình trên máy (`llm.complete`, công cụ BE-only nên BE biết qua cờ này) — BE dùng cho tier nặng khi phiên chat gắn với máy này.
|
|
406
|
+
if (byName.has('llm.complete')) {
|
|
407
|
+
const agents = activeLocalLlm()?.info().agents || [];
|
|
408
|
+
if (agents.length) profile.local_llm = { provider: agents[0].id, agents: agents.map((a) => a.id) };
|
|
409
|
+
}
|
|
410
|
+
// 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).
|
|
411
|
+
const deniedTools = new Set(policyGuard.read().deny_tools);
|
|
412
|
+
if (deniedTools.has('gui.act')) deniedTools.add('gui.do');
|
|
413
|
+
const { catalog, hash } = buildCatalog(tools.filter((t) => !deniedTools.has(t.name)));
|
|
414
|
+
const confirmer = multiUser ? null : createLocalConfirmer();
|
|
415
|
+
// 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.
|
|
416
|
+
const scheduler = createScheduler(multiUser ? { scopeLimits: DEFAULT_SCOPE_LIMITS } : undefined);
|
|
417
|
+
const earlyDrops = [];
|
|
418
|
+
let earlyWorkDir = null;
|
|
419
|
+
let announceProfile = null;
|
|
420
|
+
const applyWorkDir = (dir) => { if (mascotChat) mascotChat.setWorkDir(dir); else earlyWorkDir = dir; };
|
|
421
|
+
/** Chủ máy đồng ý mở thêm thư mục: có hiệu lực ngay (công cụ đọc env.roots lúc gọi), báo BE hồ sơ mới, lưu cho các lần chạy sau. */
|
|
422
|
+
const grantRoot = (dir) => {
|
|
423
|
+
roots.push(dir);
|
|
424
|
+
profile.roots.push(dir);
|
|
425
|
+
creds.roots = profile.roots;
|
|
426
|
+
creds.extra_roots = [...new Set([...(creds.extra_roots || []), dir])];
|
|
427
|
+
saveDeviceCredentials(creds);
|
|
428
|
+
logActivity({ type: 'folder_allowed', path: dir, by: 'owner_confirm' });
|
|
429
|
+
say(chalk.cyan(` Đã cho phép thêm thư mục: ${dir}`));
|
|
430
|
+
void announceProfile?.();
|
|
431
|
+
};
|
|
432
|
+
const chooseWorkFolder = async (dir) => {
|
|
433
|
+
const res = await resolveWorkFolder(dir, {
|
|
434
|
+
roots,
|
|
435
|
+
confirm: async (folder) => (await confirmer.ask({ ...workFolderConfirmText(folder, mascotLang(process.env, process.platform, creds?.lang)), timeoutSec: WORK_FOLDER_CONFIRM_SEC })) === ConfirmResult.ALLOW,
|
|
436
|
+
});
|
|
437
|
+
if (res.status === WorkFolderStatus.DENIED) return void mascotChat?.workDirDenied(res.path);
|
|
438
|
+
if (res.status === WorkFolderStatus.NEEDS_ROOT) grantRoot(res.path);
|
|
439
|
+
applyWorkDir(res.path);
|
|
440
|
+
};
|
|
441
|
+
// 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ó.
|
|
442
|
+
const mascot = createMascot({
|
|
443
|
+
enabled: !multiUser && options.mascot !== false && process.env.AIVIN_MASCOT !== '0', lang: creds?.lang,
|
|
444
|
+
// Nút tạm dừng trên linh vật: hiệu lực ngay (huỷ việc, dừng xem màn hình), không chờ lượt kiểm định kỳ.
|
|
445
|
+
onPause: () => { setRemotePaused(true); checkPauseNow(); },
|
|
446
|
+
onResume: () => { setRemotePaused(false); checkPauseNow(); },
|
|
447
|
+
say: (m) => say(chalk.gray(` ${m}`)),
|
|
448
|
+
// Ô 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).
|
|
449
|
+
// 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 đó.
|
|
450
|
+
onAsk: (text, window) => { void mascotChat?.reply(text, window); },
|
|
451
|
+
onChoose: (id) => { void mascotChat?.choose(id); },
|
|
452
|
+
onCancel: () => { void mascotChat?.cancel(); },
|
|
453
|
+
onNewChat: () => { void mascotChat?.newChat(); },
|
|
454
|
+
onOpenTool: (msg) => { void mascotChat?.openTool(msg); },
|
|
455
|
+
onNotifyFreq: (val) => { mascotChat?.setNotifyFreq(val); },
|
|
456
|
+
// Thả tệp vào bot → đi kèm câu gõ kế tiếp.
|
|
457
|
+
// "Gửi cho AIVIN Bot" từ Explorer có thể tới trước khi ô hỏi dựng xong (daemon vừa được khay mở) → giữ lại, dựng xong thì đính.
|
|
458
|
+
onDrop: (files) => (mascotChat ? mascotChat.attach(files) : earlyDrops.push(...files)),
|
|
459
|
+
// "Làm việc ở đây với AIVIN Bot": thư mục ngoài quyền thì hỏi chủ máy trước (workFolder.mjs).
|
|
460
|
+
onWorkFolder: (dir) => { void chooseWorkFolder(dir).catch((e) => say(chalk.yellow(`⚠️ Không đặt được thư mục làm việc: ${e?.message || e}`))); },
|
|
461
|
+
// Bấm × trên chip tệp trong ô hỏi → bỏ tệp đó.
|
|
462
|
+
onDetach: (file) => mascotChat?.detach(file),
|
|
463
|
+
// Nói chuyện trực tiếp: mic / loa ở cửa sổ, phiên thoại realtime trên BE (mascot/ask.mjs).
|
|
464
|
+
onVoice: (msg) => {
|
|
465
|
+
if (!mascotChat) return;
|
|
466
|
+
if (msg.t === MascotHostEvent.VOICE_AUDIO) return mascotChat.voiceAudio(msg.audio);
|
|
467
|
+
if (msg.t === MascotHostEvent.VOICE_START) return void mascotChat.voiceStart(msg.window);
|
|
468
|
+
if (msg.t === MascotHostEvent.VOICE_INTERRUPT) return mascotChat.voiceInterrupt();
|
|
469
|
+
if (msg.t === MascotHostEvent.VOICE_STOP) return mascotChat.voiceStop();
|
|
470
|
+
if (msg.t === MascotHostEvent.VOICE_MIC_LOST) return mascotChat.voiceMicLost();
|
|
471
|
+
},
|
|
472
|
+
});
|
|
473
|
+
if (isRemotePaused()) mascot.paused(true);
|
|
474
|
+
// Máy cài ứng dụng Aivin rồi chỉ tự cập nhật: bắt kịp Aivin.exe + "Mở bằng / Gửi cho AIVIN Bot" của bản này (biên dịch vài giây → chạy sau).
|
|
475
|
+
if (!multiUser && process.platform === 'win32') {
|
|
476
|
+
const refresh = setTimeout(() => {
|
|
477
|
+
try {
|
|
478
|
+
const done = refreshDesktopIntegration({ lang: mascotLang() });
|
|
479
|
+
if (done.length) say(chalk.gray(` Ứng dụng Aivin trên máy: đã cập nhật ${done.join(', ')}`));
|
|
480
|
+
} catch (e) {
|
|
481
|
+
say(chalk.yellow(`⚠️ Chưa cập nhật được ứng dụng Aivin trên máy (Mở bằng / Gửi cho AIVIN Bot): ${String(e?.message || e).trim()}`));
|
|
482
|
+
}
|
|
483
|
+
}, 10_000);
|
|
484
|
+
refresh.unref?.();
|
|
485
|
+
}
|
|
486
|
+
const desktopCast = createDesktopCastManager();
|
|
487
|
+
// 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).
|
|
488
|
+
let aiGuiBusy = 0;
|
|
489
|
+
const castGate = createCastInputGate({ isPaused: isRemotePaused, isAiBusy: () => aiGuiBusy > 0 });
|
|
490
|
+
let castBlockedNoticeAt = 0;
|
|
491
|
+
const emitCastStatus = (payload) => { if (socket?.connected) socket.emit(DeviceEvent.DESKTOP_CAST_STATUS, payload); };
|
|
492
|
+
/** 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. */
|
|
493
|
+
const applyRemoteInput = (raw, viewerId) => {
|
|
494
|
+
const sessionId = desktopCast.sessionId();
|
|
495
|
+
if (!sessionId || (raw?.session_id && raw.session_id !== sessionId)) return;
|
|
496
|
+
const viewer = viewerId || (typeof raw?.viewer_id === 'string' ? raw.viewer_id : '');
|
|
497
|
+
const res = castGate.accept(raw, viewer);
|
|
498
|
+
if (res.ok) return desktopCast.sendInput(res.cmd);
|
|
499
|
+
// Chỉ báo khi AI đang bấm: FE hiện "AI đang thao tác" cho mọi `input_blocked`, báo cả OTHER_VIEWER là nói sai cho người xem.
|
|
500
|
+
if (res.reason !== CastInputRejection.AI_ACTIVE || Date.now() - castBlockedNoticeAt < 2000) return;
|
|
501
|
+
castBlockedNoticeAt = Date.now();
|
|
502
|
+
emitCastStatus({ session_id: sessionId, viewer_id: viewer || undefined, state: CastState.INPUT_BLOCKED, reason: res.reason });
|
|
503
|
+
};
|
|
504
|
+
/** Một người xem rời: chỉ nhả nút người đó còn giữ (người khác đang kéo không bị nhả theo). */
|
|
505
|
+
const releaseViewerInput = (viewerId) => {
|
|
506
|
+
for (const button of castGate.releaseViewer(viewerId)) desktopCast.sendInput({ action: 'mouseup', button });
|
|
507
|
+
};
|
|
508
|
+
/** AI sắp bấm / người xem rời giữa lúc đang kéo: nhả nút + phím bổ trợ trên máy, gói nhả của người xem có thể không bao giờ tới. */
|
|
509
|
+
const releaseCastInput = () => { if (castGate.takeHeldInput()) desktopCast.sendInput({ action: 'release_all' }); };
|
|
510
|
+
const castTrust = createCastTrust();
|
|
511
|
+
const castProver = createDeviceProver({ send: emitCastStatus });
|
|
512
|
+
const castConsent = createCastConsent({
|
|
513
|
+
trust: castTrust,
|
|
514
|
+
ask: ({ viewerDevice, viewerInfo, locked, canTrust, signal }) => askCastConsent({ viewerDevice: viewerDevice || 'Thiết bị từ xa', viewerInfo, repeatedAfterBlock: locked, canTrust, signal }),
|
|
515
|
+
getMode: () => policyGuard.read().cast_consent,
|
|
516
|
+
isLocked: isCastLocked,
|
|
517
|
+
unlock: unlockCast,
|
|
518
|
+
onWaiting: ({ sessionId, viewerId, viewerDevice }) => {
|
|
519
|
+
say(chalk.yellow(` ⚠️ Thiết bị "${viewerDevice || viewerId}" xin xem màn hình — chờ bấm "Cho phép" trên máy này`));
|
|
520
|
+
emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.AWAITING_CONSENT });
|
|
521
|
+
},
|
|
522
|
+
});
|
|
523
|
+
const castDropBatches = createDropBatches();
|
|
524
|
+
const castFileDrop = createCastFileDrop({
|
|
525
|
+
reply: (viewerId, msg) => desktopWebRtc.replyFile(viewerId, msg),
|
|
526
|
+
checkAllowed: () => (isRemotePaused() ? FileDropReason.PAUSED : aiGuiBusy > 0 ? FileDropReason.AI_ACTIVE : null),
|
|
527
|
+
onSaved: ({ viewerId, path: file, name, bytes, reveal, paste, image, drop, batch, last, x, y, rx, ry }) => {
|
|
528
|
+
say(chalk.cyan(` 📥 Đã nhận tệp từ web: ${file}`));
|
|
529
|
+
logActivity({ type: 'desktop_cast_file', id: desktopCast.sessionId(), name, bytes });
|
|
530
|
+
if (drop) {
|
|
531
|
+
const paths = castDropBatches.add({ viewerId, batch, path: file, last });
|
|
532
|
+
// Kiểm lại lúc thả: chủ máy có thể vừa tạm dừng, AI có thể vừa bắt đầu bấm trong lúc tệp đang truyền.
|
|
533
|
+
if (paths && !isRemotePaused() && aiGuiBusy === 0) desktopCast.sendInput({ action: 'drop_files', paths, x, y, rx, ry });
|
|
534
|
+
} else if (paste) {
|
|
535
|
+
// Như thả: chủ máy vừa tạm dừng / AI vừa bắt đầu bấm trong lúc tệp đang truyền → không dán (con trỏ đang là của AI).
|
|
536
|
+
if (isRemotePaused() || aiGuiBusy > 0) return void emitCastStatus({ session_id: desktopCast.sessionId(), state: CastState.PASTE_FAILED });
|
|
537
|
+
desktopCast.sendInput({
|
|
538
|
+
action: 'paste_file',
|
|
539
|
+
path: file,
|
|
540
|
+
as_image: image === true,
|
|
541
|
+
x,
|
|
542
|
+
y,
|
|
543
|
+
rx,
|
|
544
|
+
ry,
|
|
545
|
+
click: Number.isFinite(x) && Number.isFinite(y),
|
|
546
|
+
});
|
|
547
|
+
} else if (reveal && aiGuiBusy === 0 && !isRemotePaused()) {
|
|
548
|
+
revealInExplorer(file);
|
|
549
|
+
}
|
|
550
|
+
},
|
|
551
|
+
});
|
|
552
|
+
// 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.
|
|
553
|
+
const desktopWebRtc = createDesktopWebRtcWorker({
|
|
554
|
+
command: cliLaunchCommand(),
|
|
555
|
+
emitSignal: (payload) => { if (socket?.connected) socket.emit(DeviceEvent.DESKTOP_CAST_SIGNAL, payload); },
|
|
556
|
+
emitStatus: emitCastStatus,
|
|
557
|
+
onInput: (raw, viewerId) => applyRemoteInput(raw, viewerId),
|
|
558
|
+
onFile: (viewerId, msg, sessionId) => { if (sessionId === desktopCast.sessionId()) castFileDrop.message(viewerId, msg); },
|
|
559
|
+
onFileChunk: (viewerId, bytes) => castFileDrop.chunk(viewerId, bytes),
|
|
560
|
+
// 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).
|
|
561
|
+
onPeerReady: () => desktopCast.refresh(),
|
|
562
|
+
onState: () => syncCastJpeg(),
|
|
563
|
+
log: (m) => say(chalk.gray(` ${m}`)),
|
|
564
|
+
});
|
|
565
|
+
/**
|
|
566
|
+
* 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).
|
|
567
|
+
* Con trỏ tách khỏi khung 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),
|
|
568
|
+
* hoặc khi tất cả đều xem bằng màn hình cảm ứng.
|
|
569
|
+
*/
|
|
570
|
+
const syncCastJpeg = () => {
|
|
571
|
+
const jpeg = desktopWebRtc.needsJpeg() || !desktopWebRtc.videoLive();
|
|
572
|
+
desktopCast.setJpeg(jpeg);
|
|
573
|
+
desktopCast.setCursorInFrame(shouldDrawCursorInFrame({ jpeg, localCursor: desktopWebRtc.localCursor(), allTouch: castTouchViewers.allTouch() }));
|
|
574
|
+
desktopCast.setAudio(desktopWebRtc.needsAudio());
|
|
575
|
+
};
|
|
576
|
+
const castTouchViewers = createCastTouchViewers();
|
|
577
|
+
/** Phiên daemon tự dừng (khác với tiến trình quay tự thoát / sập) — `onStop` của phiên phân biệt hai trường hợp. */
|
|
578
|
+
const castStopsRequested = new Set();
|
|
579
|
+
/**
|
|
580
|
+
* 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. `endedSessionId`: tiến trình quay của
|
|
581
|
+
* phiên đó đã tự thoát (sập, màn hình đổi…) — dọn kênh người xem + báo BE, không thì người xem đứng hình mà thao tác rơi im lặng.
|
|
582
|
+
*/
|
|
583
|
+
const stopDesktopCast = (reason, notify = true, endedSessionId = null) => {
|
|
584
|
+
const sessionId = endedSessionId || desktopCast.sessionId();
|
|
585
|
+
clearCastSession();
|
|
586
|
+
// Gián đoạn (rớt mạng): máy chủ giữ phiên và mời phát lại đúng phiên đó — giữ đồng ý, chủ máy đang ở xa không bị khoá
|
|
587
|
+
// ngoài. Kết thúc hẳn: quên.
|
|
588
|
+
if (sessionId) {
|
|
589
|
+
if (CAST_RESUMABLE_REASONS.has(reason)) castConsent.suspend(sessionId);
|
|
590
|
+
else castConsent.forget(sessionId);
|
|
591
|
+
}
|
|
592
|
+
if (CAST_SHUTDOWN_REASONS.has(reason)) {
|
|
593
|
+
castConsent.cancelAll();
|
|
594
|
+
castProver.cancel();
|
|
595
|
+
}
|
|
596
|
+
clearTimeout(castDisconnectTimer);
|
|
597
|
+
castDisconnectTimer = null;
|
|
598
|
+
clearTimeout(castReconfirmTimer);
|
|
599
|
+
castReconfirmTimer = null;
|
|
600
|
+
castTouchViewers.clear();
|
|
601
|
+
desktopWebRtc.closeAll();
|
|
602
|
+
void castFileDrop.closeAll();
|
|
603
|
+
castGate.takeHeldInput(); // Tiến trình điều khiển tự nhả khi dừng.
|
|
604
|
+
holdCastAwake(false);
|
|
605
|
+
if (!endedSessionId) {
|
|
606
|
+
if (!desktopCast.isActive()) return;
|
|
607
|
+
castStopsRequested.add(sessionId);
|
|
608
|
+
desktopCast.stop();
|
|
609
|
+
}
|
|
610
|
+
mascot.remoteView(false);
|
|
611
|
+
// 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ủ).
|
|
612
|
+
logActivity({ type: 'desktop_cast', id: sessionId, reason, inputs: castGate.takeAcceptedCount() });
|
|
613
|
+
if (notify && sessionId) emitCastStatus({ session_id: sessionId, state: CastState.STOPPED, reason, final: true });
|
|
614
|
+
};
|
|
615
|
+
/**
|
|
616
|
+
* Mã đánh dấu thao tác của phiên đang phát (humanInput.mjs): thao tác của người đang điều khiển từ xa duyệt được hộp xác nhận, AI thì không.
|
|
617
|
+
* Kể cả chế độ không cần người ở máy: chủ máy ở xa không còn cách nào khác để duyệt, và ai điều khiển được phiên cũng đã gõ được lệnh thẳng vào máy.
|
|
618
|
+
*/
|
|
619
|
+
let castInputTag = null;
|
|
620
|
+
const castTrustTag = () => (castInputTag && desktopCast.isActive() ? castInputTag : null);
|
|
621
|
+
/** Mở tiến trình quay cho một phiên (lần đầu, hoặc mở lại khi tiến trình sập). `false` khi máy không quay được. */
|
|
622
|
+
function startCapture({ sessionId, viewerId, viewerDevice, viewerPlace = '', castConfig }) {
|
|
623
|
+
return !!desktopCast.start({
|
|
624
|
+
sessionId,
|
|
625
|
+
inputTag: castInputTag,
|
|
626
|
+
maxFps: castConfig.max_fps,
|
|
627
|
+
maxWidth: castConfig.max_width,
|
|
628
|
+
quality: castConfig.quality,
|
|
629
|
+
monitor: castConfig.monitor,
|
|
630
|
+
onFrame: (frame) => {
|
|
631
|
+
desktopWebRtc.push(frame);
|
|
632
|
+
// 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 đó.
|
|
633
|
+
// Binary thay base64: nhẹ hơn khoảng một phần ba; JPEG đã nén nên không nén thêm.
|
|
634
|
+
if (desktopWebRtc.needsFallback() && socket.connected) {
|
|
635
|
+
socket.volatile.compress(false).emit(DeviceEvent.DESKTOP_CAST_FRAME, { ...frame, image: Buffer.from(frame.image, 'base64') });
|
|
636
|
+
}
|
|
637
|
+
syncCastJpeg();
|
|
638
|
+
},
|
|
639
|
+
// 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.
|
|
640
|
+
onMeta: (meta) => {
|
|
641
|
+
desktopWebRtc.push(meta);
|
|
642
|
+
// Màn hình đứng yên không có ảnh: người xem qua máy chủ vẫn cần gói giữ nhịp để biết máy còn sống.
|
|
643
|
+
if (desktopWebRtc.needsFallback() && socket.connected) socket.volatile.emit(DeviceEvent.DESKTOP_CAST_FRAME, meta);
|
|
644
|
+
syncCastJpeg();
|
|
645
|
+
},
|
|
646
|
+
onCursor: (cursor) => desktopWebRtc.pushCursor(cursor),
|
|
647
|
+
onCursorShape: (shape) => desktopWebRtc.pushCursorShape(shape),
|
|
648
|
+
onInputFocus: (focus) => {
|
|
649
|
+
desktopWebRtc.pushInputFocus?.(focus);
|
|
650
|
+
// Người xem chưa có kênh WebRTC không nhận được tin trên → gửi qua máy chủ để điện thoại vẫn tự mở bàn phím.
|
|
651
|
+
if (desktopWebRtc.needsFallback() && socket.connected) {
|
|
652
|
+
socket.emit(DeviceEvent.DESKTOP_CAST_INPUT_FOCUS, { session_id: sessionId, editable: focus?.editable === true });
|
|
653
|
+
}
|
|
654
|
+
},
|
|
655
|
+
onPasteFailed: () => emitCastStatus({ session_id: sessionId, state: CastState.PASTE_FAILED }),
|
|
656
|
+
onDropRefused: () => emitCastStatus({ session_id: sessionId, state: CastState.DROP_REFUSED }),
|
|
657
|
+
onCapture: ({ mode, reason }) => say(chalk.gray(` 🖥️ Chụp màn hình: ${mode}${reason ? ` (${reason})` : ''}`)),
|
|
658
|
+
onClipboard: (clip) => desktopWebRtc.pushClipboard?.(clip),
|
|
659
|
+
onSecureDesktop: (sec) => {
|
|
660
|
+
desktopWebRtc.pushSecureDesktop?.(sec);
|
|
661
|
+
emitCastStatus({ session_id: sessionId, state: 'secure_desktop', active: sec?.active === true });
|
|
662
|
+
},
|
|
663
|
+
rawPipe: true,
|
|
664
|
+
onReady: (meta) => {
|
|
665
|
+
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})`));
|
|
666
|
+
mascot.remoteView(true, { device: viewerDevice });
|
|
667
|
+
holdCastAwake(true);
|
|
668
|
+
recordCastSession({ active: true, sessionId, viewerId, viewerDevice, viewerPlace });
|
|
669
|
+
emitCastStatus({ session_id: sessionId, state: CastState.READY, bounds: meta.bounds });
|
|
670
|
+
},
|
|
671
|
+
onError: (err) => {
|
|
672
|
+
say(chalk.yellow(` ⚠️ Desktop Cast lỗi: ${err?.message || err}`));
|
|
673
|
+
},
|
|
674
|
+
onStop: () => {
|
|
675
|
+
say(chalk.gray(' ⏹ Đã ngừng xem màn hình từ web'));
|
|
676
|
+
const requested = castStopsRequested.delete(sessionId);
|
|
677
|
+
// Phiên mới đã thay chỗ: không đụng tới linh vật / tệp phiên / người xem của phiên mới.
|
|
678
|
+
if (desktopCast.isActive()) return;
|
|
679
|
+
if (requested) {
|
|
680
|
+
mascot.remoteView(false);
|
|
681
|
+
clearCastSession();
|
|
682
|
+
return;
|
|
683
|
+
}
|
|
684
|
+
// Tiến trình quay tự thoát (sập, lỗi chụp…) mà daemon không yêu cầu: mở lại ngay cho cùng phiên — người xem giữ kết nối WebRTC, chỉ
|
|
685
|
+
// đổi nguồn hình. Sập liên tục thì kết thúc phiên cho đúng (người xem mở lại được ngay, không đứng hình).
|
|
686
|
+
const now = Date.now();
|
|
687
|
+
while (castRestarts.length && now - castRestarts[0] > 60_000) castRestarts.shift();
|
|
688
|
+
if (!stopped && !isRemotePaused() && castRestarts.length < CAST_MAX_RESTARTS_PER_MIN) {
|
|
689
|
+
castRestarts.push(now);
|
|
690
|
+
say(chalk.yellow(' ⚠️ Tiến trình xem màn hình dừng bất ngờ — mở lại'));
|
|
691
|
+
// Tiến trình cũ chết không kịp nhả nút chuột đang giữ: nhả trên tiến trình mới.
|
|
692
|
+
const hadHeld = castGate.takeHeldInput();
|
|
693
|
+
if (startCapture({ sessionId, viewerId, viewerDevice, viewerPlace, castConfig })) {
|
|
694
|
+
desktopWebRtc.attachPipe(desktopCast.pipeName());
|
|
695
|
+
if (hadHeld) for (const button of [0, 1, 2]) desktopCast.sendInput({ action: 'mouseup', button });
|
|
696
|
+
return;
|
|
697
|
+
}
|
|
698
|
+
}
|
|
699
|
+
say(chalk.yellow(' ⚠️ Tiến trình xem màn hình dừng bất ngờ — đã báo người xem'));
|
|
700
|
+
stopDesktopCast('capture_stopped', true, sessionId);
|
|
701
|
+
},
|
|
702
|
+
});
|
|
703
|
+
}
|
|
704
|
+
let mascotChat = null;
|
|
705
|
+
let castDisconnectTimer = null;
|
|
706
|
+
let castReconfirmTimer = null;
|
|
707
|
+
const castRestarts = [];
|
|
708
|
+
// Tệp phiên của lần chạy trước (daemon chết giữa phiên) — khay sẽ hiện "Ngắt…" cho một phiên không còn.
|
|
709
|
+
clearCastSession();
|
|
710
|
+
/** Chủ máy bấm "Ngắt" ở khay / `aivin remote disconnect`: chạy ngay khi tệp lệnh xuất hiện (fs.watch), đọc định kỳ chỉ để dự phòng. */
|
|
711
|
+
const checkCastActionNow = () => {
|
|
712
|
+
const action = checkCastAction();
|
|
713
|
+
// Gỡ thiết bị tin cậy ở khay. Chỉ siết quyền lại, người đang xem (nếu có) không bị ngắt.
|
|
714
|
+
if (action?.action === 'untrust') return void castTrust.remove(action.key);
|
|
715
|
+
if (action?.action === 'untrust_all') return void castTrust.removeAll();
|
|
716
|
+
if (action?.action !== 'stop_and_block') return;
|
|
717
|
+
castConsent.revokeSessionTrust(desktopCast.sessionId());
|
|
718
|
+
lockCast({ viewerDevice: action.viewer_device });
|
|
719
|
+
say(chalk.yellow(' ⏹ Đã ngắt người đang xem. Phiên sau phải bấm "Cho phép" trên máy này.'));
|
|
720
|
+
stopDesktopCast('user_revoked');
|
|
721
|
+
};
|
|
722
|
+
const castActionTimer = setInterval(checkCastActionNow, 1000);
|
|
723
|
+
castActionTimer.unref?.();
|
|
724
|
+
|
|
725
|
+
say(chalk.blue('💻 Aivin Device Agent — máy này nhận việc từ agent của bạn'));
|
|
726
|
+
say(chalk.gray(` Máy: ${creds.name} (${creds.device_id})`));
|
|
727
|
+
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(' | ')}`));
|
|
728
|
+
say(chalk.gray(` Máy chủ: ${serverUrl}`));
|
|
729
|
+
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`));
|
|
730
|
+
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'})`));
|
|
731
|
+
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>`));
|
|
732
|
+
say(chalk.gray(` Công cụ: ${catalog.length} (${profile.binaries.join(', ') || 'không phát hiện chương trình nào'})`));
|
|
733
|
+
say(chalk.gray(` Ghi nhớ: ${memoryStats().total} mục — ${memoryStats().dir}`));
|
|
734
|
+
if (officeApps.length) say(chalk.gray(` Office: ${officeApps.join(', ')} — AI làm qua ứng dụng, chạy nền`));
|
|
735
|
+
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)'}`));
|
|
736
|
+
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ủ'
|
|
737
|
+
: 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`
|
|
738
|
+
: `${browser.name} (cửa sổ riêng của Aivin)`}`));
|
|
739
|
+
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)'}`));
|
|
740
|
+
if (isRemotePaused()) say(chalk.yellow(' ⏸ Đang TẠM DỪNG (aivin remote resume để nhận việc lại)'));
|
|
741
|
+
// `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.
|
|
742
|
+
const stopMeetingRequests = meetings ? watchMeetingRequests(meetings) : null;
|
|
743
|
+
|
|
744
|
+
void gui?.prewarm?.();
|
|
745
|
+
void desktopCast.prewarm?.();
|
|
746
|
+
fileIndex?.build()
|
|
747
|
+
.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(); })
|
|
748
|
+
.catch((e) => say(chalk.yellow(` ⚠️ Lập chỉ mục tệp lỗi: ${e.message}`)));
|
|
749
|
+
|
|
750
|
+
// 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
|
|
751
|
+
// sau khi mạng chập chờn thì không dừng nhầm).
|
|
752
|
+
const instance = randomUUID();
|
|
753
|
+
const socket = io(`${serverUrl}${DEVICE_NAMESPACE}`, {
|
|
754
|
+
auth: { device_token: creds.device_token, protocol: PROTOCOL_VERSION, instance },
|
|
755
|
+
transports: ['websocket'],
|
|
756
|
+
// Proxy công ty (netProxy.mjs): websocket đi qua đường hầm CONNECT; không có proxy → `undefined`, nối thẳng.
|
|
757
|
+
agent: proxyAgentFor(`${serverUrl}${DEVICE_NAMESPACE}`),
|
|
758
|
+
reconnection: true,
|
|
759
|
+
reconnectionDelay: 1000,
|
|
760
|
+
reconnectionDelayMax: multiUser ? MULTI_USER_RECONNECT_DELAY_MAX_MS : RECONNECT_DELAY_MAX_MS,
|
|
761
|
+
randomizationFactor: 0.5,
|
|
762
|
+
});
|
|
763
|
+
|
|
764
|
+
let stopped = false;
|
|
765
|
+
// 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.
|
|
766
|
+
let activeCalls = 0;
|
|
767
|
+
let lastActivityAt = Date.now();
|
|
768
|
+
let updater = null;
|
|
769
|
+
// 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.
|
|
770
|
+
const confirmTimer = selfManaged ? setTimeout(() => { try { confirmUpdate(); } catch { /* lần sau */ } }, UPDATE_CONFIRM_AFTER_MS) : null;
|
|
771
|
+
confirmTimer?.unref?.();
|
|
772
|
+
// 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).
|
|
773
|
+
const heartbeat = setInterval(() => {
|
|
774
|
+
if (socket.connected) socket.emit(DeviceEvent.HEARTBEAT, multiUser ? { busy: processes.hasRunning() } : {});
|
|
775
|
+
ledger.prune();
|
|
776
|
+
// 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).
|
|
777
|
+
if (socket.connected && serverResume) ledger.dueForResend().forEach(sendResult);
|
|
778
|
+
syncProcAwake();
|
|
779
|
+
}, HEARTBEAT_MS);
|
|
780
|
+
|
|
781
|
+
// `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.
|
|
782
|
+
let pausedSeen = isRemotePaused();
|
|
783
|
+
function checkPauseNow() {
|
|
784
|
+
if (stopped) return;
|
|
785
|
+
const paused = isRemotePaused();
|
|
786
|
+
if (paused && !pausedSeen) {
|
|
787
|
+
say(chalk.yellow('⏸ Đã tạm dừng — huỷ việc đang chạy và đóng trình duyệt AI đang dùng.'));
|
|
788
|
+
void scheduler.cancelAll('Remote control was paused on this device');
|
|
789
|
+
cancelGating([...gating.keys()]);
|
|
790
|
+
browserTunnels?.closeAll();
|
|
791
|
+
guiHost?.close();
|
|
792
|
+
officeHost?.close();
|
|
793
|
+
processes.stopAll();
|
|
794
|
+
activeAgentRunner()?.stopAll('Remote control was paused on this device');
|
|
795
|
+
activeLocalLlm()?.stopAll();
|
|
796
|
+
// 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.
|
|
797
|
+
stopDesktopCast('paused');
|
|
798
|
+
}
|
|
799
|
+
if (paused !== pausedSeen) mascot.paused(paused);
|
|
800
|
+
pausedSeen = paused;
|
|
801
|
+
}
|
|
802
|
+
const pauseWatch = setInterval(checkPauseNow, PAUSE_POLL_MS);
|
|
803
|
+
pauseWatch.unref?.();
|
|
804
|
+
// `aivin remote pause` / nút ở khay / lệnh ngắt cast ở cửa sổ khác: phản ứng ngay khi tệp đổi (fs.watch), không đợi tới 1–2 s của lượt kiểm
|
|
805
|
+
// định kỳ — trong lúc đó màn hình vẫn đang phát cho người xem. Tên tệp có thể vắng (Windows) → kiểm cả hai.
|
|
806
|
+
let configWatcher = null;
|
|
807
|
+
try {
|
|
808
|
+
const killName = path.basename(KILL_SWITCH_FILE);
|
|
809
|
+
const actionName = path.basename(CAST_ACTION_FILE);
|
|
810
|
+
configWatcher = fs.watch(REMOTE_CONFIG_DIR, { persistent: false }, (_event, name) => {
|
|
811
|
+
const file = name ? String(name) : '';
|
|
812
|
+
if (!file || file === killName) checkPauseNow();
|
|
813
|
+
if (!file || file === actionName) checkCastActionNow();
|
|
814
|
+
});
|
|
815
|
+
configWatcher.on('error', () => undefined);
|
|
816
|
+
} catch { /* không theo dõi được thư mục: còn kiểm định kỳ */ }
|
|
817
|
+
|
|
818
|
+
// 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
|
|
819
|
+
// 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.
|
|
820
|
+
const ledger = createCallLedger({ file: options.outboxFile || REMOTE_OUTBOX_FILE });
|
|
821
|
+
// 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.
|
|
822
|
+
let serverResume = false;
|
|
823
|
+
const sendResult = (payload) => {
|
|
824
|
+
if (!socket.connected) return ledger.persist();
|
|
825
|
+
if (!serverResume) {
|
|
826
|
+
socket.emit(DeviceEvent.RESULT, payload);
|
|
827
|
+
return ledger.markSent(payload.call_id);
|
|
828
|
+
}
|
|
829
|
+
ledger.markAttempt(payload.call_id);
|
|
830
|
+
socket.timeout(RESULT_ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.RESULT, payload)
|
|
831
|
+
.then(() => ledger.markSent(payload.call_id), () => ledger.persist());
|
|
832
|
+
};
|
|
833
|
+
const flushUnsent = () => {
|
|
834
|
+
for (const payload of ledger.unsent()) {
|
|
835
|
+
if (!socket.connected) return;
|
|
836
|
+
sendResult(payload);
|
|
837
|
+
}
|
|
838
|
+
};
|
|
839
|
+
|
|
840
|
+
const stop = () => {
|
|
841
|
+
if (stopped) return;
|
|
842
|
+
stopped = true;
|
|
843
|
+
clearInterval(heartbeat);
|
|
844
|
+
clearInterval(pauseWatch);
|
|
845
|
+
clearInterval(castActionTimer);
|
|
846
|
+
try { configWatcher?.close(); } catch { /* đã đóng */ }
|
|
847
|
+
clearTimeout(confirmTimer);
|
|
848
|
+
clearTimeout(castDisconnectTimer);
|
|
849
|
+
clearTimeout(castReconfirmTimer);
|
|
850
|
+
// Báo người xem phiên kết thúc khi socket còn nối — trước đây dừng sau `socket.disconnect()` nên STOPPED không bao giờ đi, người xem đứng
|
|
851
|
+
// hình tới khi máy chủ tự hết hạn phiên.
|
|
852
|
+
stopDesktopCast('device_stopped');
|
|
853
|
+
updater?.close();
|
|
854
|
+
mascot.close();
|
|
855
|
+
if (selfManaged) noteCleanExit();
|
|
856
|
+
const draining = scheduler.cancelAll('The Aivin agent on this device stopped');
|
|
857
|
+
cancelGating([...gating.keys()]);
|
|
858
|
+
ledger.persist({ sync: true });
|
|
859
|
+
socket.disconnect();
|
|
860
|
+
browserTunnels?.closeAll();
|
|
861
|
+
// Đóng tệp ghi họp cho đúng; biên bản làm ở lần chạy sau (meetings.recover).
|
|
862
|
+
stopMeetingRequests?.();
|
|
863
|
+
void meetings?.shutdown();
|
|
864
|
+
gui?.close();
|
|
865
|
+
guiHost?.close();
|
|
866
|
+
officeHost?.close();
|
|
867
|
+
processes.stopAll();
|
|
868
|
+
// Job của agent lập trình: dừng + ghi hồ sơ (`stopped`) — lần chạy sau `agent.status` vẫn đọc được, nói tiếp bằng session_id.
|
|
869
|
+
activeAgentRunner()?.stopAll();
|
|
870
|
+
activeLocalLlm()?.stopAll();
|
|
871
|
+
keepAwake.close();
|
|
872
|
+
castAwake.close();
|
|
873
|
+
watches?.closeAll();
|
|
874
|
+
host?.close();
|
|
875
|
+
fileIndex?.close();
|
|
876
|
+
stopWatchingMemory();
|
|
877
|
+
releaseLock();
|
|
878
|
+
say(chalk.gray('🛑 Đã dừng nhận việc từ xa.'));
|
|
879
|
+
return draining;
|
|
880
|
+
};
|
|
881
|
+
|
|
882
|
+
// 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.
|
|
883
|
+
const stopForGood = () => {
|
|
884
|
+
const draining = stop();
|
|
885
|
+
if (options.handleSignals !== false) Promise.resolve(draining).finally(() => process.exit(0));
|
|
886
|
+
};
|
|
887
|
+
|
|
888
|
+
// 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.
|
|
889
|
+
updater = createAutoUpdater({
|
|
890
|
+
enabled: autoUpdateEnabled,
|
|
891
|
+
// 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.
|
|
892
|
+
supervised: !!supervisor && options.handleSignals !== false,
|
|
893
|
+
deviceId: creds.device_id,
|
|
894
|
+
// Đ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).
|
|
895
|
+
// Đang có người xem màn hình: khởi động lại là cắt phiên (và mất đồng ý của chủ máy — nằm trong bộ nhớ).
|
|
896
|
+
// Job của agent lập trình chạy nền sau khi `agent.run` đã trả lời (activeCalls về 0) — vẫn là bận: khởi động lại là giết job.
|
|
897
|
+
isIdle: () => activeCalls === 0 && !processes.hasRunning?.() && !activeAgentRunner()?.hasRunning() && !(browserTunnels?.liveCount() > 0) && !meetings?.busy() && !desktopCast.isActive(),
|
|
898
|
+
lastActivityAt: () => lastActivityAt,
|
|
899
|
+
say: (m) => say(chalk.cyan(m)),
|
|
900
|
+
onRestart: async (version) => {
|
|
901
|
+
logActivity({ type: 'self_update', version });
|
|
902
|
+
console.log(chalk.cyan(`⬆ Chuyển sang aivin ${version} — khởi động lại.`));
|
|
903
|
+
// 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.
|
|
904
|
+
if (socket.connected) {
|
|
905
|
+
await socket.timeout(RESTARTING_ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.RESTARTING, { reason: 'update', version, expect_back_ms: RESTART_EXPECT_BACK_MS }).catch(() => null);
|
|
906
|
+
}
|
|
907
|
+
Promise.resolve(stop()).finally(() => process.exit(RESTART_EXIT_CODE));
|
|
908
|
+
},
|
|
909
|
+
});
|
|
910
|
+
|
|
911
|
+
const embedTexts = async (texts) => {
|
|
912
|
+
if (!socket.connected) return null;
|
|
913
|
+
const res = await socket.timeout(EMBED_TIMEOUT_MS).emitWithAck(DeviceEvent.EMBED, { texts });
|
|
914
|
+
return res?.ok ? res.vectors : null;
|
|
915
|
+
};
|
|
916
|
+
|
|
917
|
+
/**
|
|
918
|
+
* 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ì
|
|
919
|
+
* 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).
|
|
920
|
+
*/
|
|
921
|
+
const rotateToken = async (token) => {
|
|
922
|
+
const previous = creds.device_token;
|
|
923
|
+
try {
|
|
924
|
+
// Giữ token cũ tới khi máy chủ xác nhận (tokenRotation.mjs) — 02/11/2026.
|
|
925
|
+
const fallback = saveDeviceCredentials({ ...creds, device_token: token }, { previousToken: previous });
|
|
926
|
+
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`));
|
|
927
|
+
// Đọ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.
|
|
928
|
+
if (readStoredTokenFresh(serverUrl) !== token) throw new Error('saved token does not read back');
|
|
929
|
+
} catch (e) {
|
|
930
|
+
try { saveDeviceCredentials({ ...creds, device_token: previous }, { previousToken: null }); } catch { /* giữ nguyên tệp */ }
|
|
931
|
+
say(chalk.yellow(` ⚠️ Không lưu được token mới (${e.message}) — tiếp tục dùng token cũ`));
|
|
932
|
+
return;
|
|
933
|
+
}
|
|
934
|
+
creds.device_token = token;
|
|
935
|
+
socket.auth = { ...socket.auth, device_token: token };
|
|
936
|
+
// 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 đó).
|
|
937
|
+
const ack = await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.ROTATED, { token }).catch(() => null);
|
|
938
|
+
if (ack?.ok === true) settleRotation(token, serverUrl);
|
|
939
|
+
logActivity({ type: 'token_rotated', deviceId: creds.device_id, confirmed: ack?.ok === true });
|
|
940
|
+
say(chalk.gray(ack?.ok
|
|
941
|
+
? ' 🔑 Đã đổi token máy định kỳ (token cũ hết hiệu lực)'
|
|
942
|
+
: ' 🔑 Đã lưu token mới — máy chủ chưa xác nhận, sẽ chốt ở lần nối lại'));
|
|
943
|
+
};
|
|
944
|
+
|
|
945
|
+
const announce = async () => {
|
|
946
|
+
try {
|
|
947
|
+
if (!multiUser) profile.update = updateProfile({ enabled: autoUpdateEnabled });
|
|
948
|
+
const hello = await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.HELLO, { protocol: PROTOCOL_VERSION, profile, catalog_hash: hash, inflight: ledger.heldIds() });
|
|
949
|
+
const userLang = hello?.user_lang || hello?.lang;
|
|
950
|
+
if (userLang && mascot.enabled) {
|
|
951
|
+
const resolvedLang = mascotLang(process.env, process.platform, userLang);
|
|
952
|
+
if (resolvedLang !== mascot.lang) {
|
|
953
|
+
mascot.setLang(resolvedLang);
|
|
954
|
+
mascotChat?.setLang(resolvedLang);
|
|
955
|
+
if (creds && creds.lang !== resolvedLang) {
|
|
956
|
+
creds.lang = resolvedLang;
|
|
957
|
+
saveDeviceCredentials(creds);
|
|
958
|
+
}
|
|
959
|
+
}
|
|
960
|
+
}
|
|
961
|
+
serverResume = Array.isArray(hello?.features) && hello.features.includes(ServerFeature.RESUME);
|
|
962
|
+
mascotChat?.setServerFeatures(hello?.features);
|
|
963
|
+
// 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).
|
|
964
|
+
void mascotChat?.syncInbox();
|
|
965
|
+
// 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ả.
|
|
966
|
+
const orphaned = Array.isArray(hello?.orphaned) ? hello.orphaned.filter((id) => typeof id === 'string') : [];
|
|
967
|
+
if (orphaned.length) {
|
|
968
|
+
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)`));
|
|
969
|
+
scheduler.cancel(orphaned);
|
|
970
|
+
cancelGating(orphaned);
|
|
971
|
+
ledger.drop(orphaned);
|
|
972
|
+
}
|
|
973
|
+
if (!envCreds) settleRotation(creds.device_token, serverUrl); // chào được bằng token đang dùng → bỏ token cũ còn giữ (nếu có)
|
|
974
|
+
if (typeof hello?.rotate_token === 'string' && !envCreds) await rotateToken(hello.rotate_token);
|
|
975
|
+
// 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.
|
|
976
|
+
if (hello?.cli) updater?.setServerHints(hello.cli);
|
|
977
|
+
if (hello?.need_catalog) await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.CATALOG, { catalog_hash: hash, tools: catalog });
|
|
978
|
+
// 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á.
|
|
979
|
+
if (fileIndex && Array.isArray(hello?.features) && hello.features.includes(ServerFeature.EMBED)) fileIndex.setEmbedder(embedTexts);
|
|
980
|
+
// 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.
|
|
981
|
+
if (watches && Array.isArray(hello?.features) && hello.features.includes(ServerFeature.WATCH)) {
|
|
982
|
+
const res = await socket.timeout(ACK_TIMEOUT_MS).emitWithAck(DeviceEvent.WATCHES, {}).catch(() => null);
|
|
983
|
+
if (Array.isArray(res?.watches)) watches.set(res.watches);
|
|
984
|
+
}
|
|
985
|
+
say(chalk.green('✅ Đã kết nối — sẵn sàng nhận việc.'));
|
|
986
|
+
mascot.connected();
|
|
987
|
+
logActivity({ type: 'connected', serverUrl, deviceId: creds.device_id });
|
|
988
|
+
} catch (e) {
|
|
989
|
+
say(chalk.yellow(`⚠️ Chào máy chủ lỗi (${e.message}) — sẽ thử lại khi nối lại.`));
|
|
990
|
+
}
|
|
991
|
+
};
|
|
992
|
+
|
|
993
|
+
// 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ỉ
|
|
994
|
+
// tên công cụ + vài ký tự đầu của vùng.
|
|
995
|
+
const callLabel = (call) => (host ? `${call.tool} [${String(call.user_scope || '-').slice(0, 5)}]` : call.tool);
|
|
996
|
+
|
|
997
|
+
/**
|
|
998
|
+
* 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ỗ để
|
|
999
|
+
* 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).
|
|
1000
|
+
*/
|
|
1001
|
+
// 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 /
|
|
1002
|
+
// 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).
|
|
1003
|
+
const gating = new Map();
|
|
1004
|
+
const cancelGating = (callIds) => {
|
|
1005
|
+
for (const id of callIds) gating.get(id)?.abort();
|
|
1006
|
+
};
|
|
1007
|
+
// Có hộp xác nhận đang chờ → lời gọi có tác dụng khác chưa bắt đầu (confirmBarrier.mjs): không lời gọi nào cùng lô bấm hộ được "Cho phép".
|
|
1008
|
+
const confirmBarrier = createConfirmBarrier();
|
|
1009
|
+
const emitHold = (callId, extraMs, phase) => { if (socket.connected) socket.emit(DeviceEvent.HOLD, { call_id: callId, extra_ms: extraMs, phase }); };
|
|
1010
|
+
|
|
1011
|
+
const localGate = async (call, tool) => {
|
|
1012
|
+
// 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.
|
|
1013
|
+
const policy = policyGuard.read();
|
|
1014
|
+
const verdict = evaluateLocalPolicy(policy, tool, call.args || {});
|
|
1015
|
+
if (verdict.action !== 'confirm' || !confirmer) return;
|
|
1016
|
+
const timeoutSec = policy.confirm_timeout_sec;
|
|
1017
|
+
const hold = (extraMs, phase = HoldPhase.WAITING) => emitHold(call.call_id, extraMs, phase);
|
|
1018
|
+
hold((timeoutSec + 15) * 1000);
|
|
1019
|
+
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)`));
|
|
1020
|
+
const purpose = typeof call.purpose === 'string' ? call.purpose.slice(0, 200) : undefined;
|
|
1021
|
+
const controller = new AbortController();
|
|
1022
|
+
gating.set(call.call_id, controller);
|
|
1023
|
+
const releaseBarrier = confirmBarrier.hold();
|
|
1024
|
+
let result;
|
|
1025
|
+
mascot.waitingConfirm(call, tool);
|
|
1026
|
+
try {
|
|
1027
|
+
result = await confirmer.ask({
|
|
1028
|
+
reason: verdict.reason, purpose, detail: describeCall(tool, call.args || {}), timeoutSec, signal: controller.signal,
|
|
1029
|
+
// 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 đó.
|
|
1030
|
+
onStart: (queuedMs) => { if (queuedMs > 1000) hold(queuedMs); },
|
|
1031
|
+
// Người đang điều khiển từ xa vẫn duyệt được; AI thì không (humanInput.mjs).
|
|
1032
|
+
trustTag: castTrustTag(),
|
|
1033
|
+
});
|
|
1034
|
+
} finally {
|
|
1035
|
+
gating.delete(call.call_id);
|
|
1036
|
+
releaseBarrier();
|
|
1037
|
+
}
|
|
1038
|
+
logActivity({ type: 'local_confirm', tool: call.tool, id: call.call_id, result });
|
|
1039
|
+
mascot.confirmDone(call, result === ConfirmResult.ALLOW);
|
|
1040
|
+
// Bấm "Cho phép" đúng lúc chủ máy vừa tạm dừng → không chạy.
|
|
1041
|
+
if (result === ConfirmResult.ALLOW && isRemotePaused()) throw new DeviceToolError(DeviceErrorCode.KILL_SWITCH, 'Remote control is paused on this device');
|
|
1042
|
+
if (result === ConfirmResult.ALLOW) return hold(0, HoldPhase.STARTED);
|
|
1043
|
+
const fail = {
|
|
1044
|
+
[ConfirmResult.REJECT]: [DeviceErrorCode.LOCAL_REJECTED, 'The person at this computer rejected this step'],
|
|
1045
|
+
[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)`],
|
|
1046
|
+
[ConfirmResult.UNAVAILABLE]: [DeviceErrorCode.LOCAL_CONFIRM_UNAVAILABLE, 'This step needs a confirmation at the computer, but no confirmation box could be shown there'],
|
|
1047
|
+
[ConfirmResult.CANCELLED]: [DeviceErrorCode.CANCELLED, 'Cancelled while waiting for a confirmation at the computer — the step did not run'],
|
|
1048
|
+
}[result];
|
|
1049
|
+
throw new DeviceToolError(fail[0], fail[1]);
|
|
1050
|
+
};
|
|
1051
|
+
|
|
1052
|
+
/** Lời gọi có tác dụng chờ các hộp xác nhận đang mở được trả lời (xin BE lùi hạn trong lúc chờ; lệnh huỷ dừng được lúc chờ). */
|
|
1053
|
+
const waitConfirmBarrier = async (call) => {
|
|
1054
|
+
if (!confirmBarrier.pending()) return;
|
|
1055
|
+
emitHold(call.call_id, (policyGuard.read().confirm_timeout_sec + 15) * 1000, HoldPhase.WAITING);
|
|
1056
|
+
const controller = new AbortController();
|
|
1057
|
+
gating.set(call.call_id, controller);
|
|
1058
|
+
let clear;
|
|
1059
|
+
try {
|
|
1060
|
+
clear = await confirmBarrier.waitClear(controller.signal);
|
|
1061
|
+
} finally {
|
|
1062
|
+
gating.delete(call.call_id);
|
|
1063
|
+
}
|
|
1064
|
+
if (!clear) throw new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled while waiting for a confirmation box on this computer to be answered — the step did not run');
|
|
1065
|
+
emitHold(call.call_id, 0, HoldPhase.STARTED);
|
|
1066
|
+
};
|
|
1067
|
+
|
|
1068
|
+
const failOutcome = (tool, e, code = DeviceErrorCode.INVALID_ARGS) => ({ tool, outcome: { ok: false, error: e.message, error_code: e.code || code, duration_ms: 0 } });
|
|
1069
|
+
|
|
1070
|
+
const runCall = async (call, streamer, hooks) => {
|
|
1071
|
+
const tool = byName.get(call.tool);
|
|
1072
|
+
if (isRemotePaused()) return { tool, outcome: { ok: false, error: 'Remote control is paused on this device', error_code: DeviceErrorCode.KILL_SWITCH, duration_ms: 0 } };
|
|
1073
|
+
if (!tool) return { tool, outcome: { ok: false, error: `Unknown tool: ${call.tool}`, error_code: DeviceErrorCode.TOOL_UNKNOWN, duration_ms: 0 } };
|
|
1074
|
+
if (!tool.internal) say(chalk.yellow(`⚡ ${callLabel(call)}`), ...(host ? [] : [chalk.gray(JSON.stringify(call.args || {}).slice(0, 160))]));
|
|
1075
|
+
let callEnv = env;
|
|
1076
|
+
try {
|
|
1077
|
+
if (host) {
|
|
1078
|
+
callEnv = host.envFor(call.user_scope);
|
|
1079
|
+
host.assertQuota(call.tool);
|
|
1080
|
+
}
|
|
1081
|
+
await localGate(call, tool);
|
|
1082
|
+
if (!tool.read_only) await waitConfirmBarrier(call);
|
|
1083
|
+
// Chủ máy có thể vừa tạm dừng trong lúc chờ hộp xác nhận (của chính lời gọi này hoặc của lời gọi khác).
|
|
1084
|
+
if (isRemotePaused()) throw new DeviceToolError(DeviceErrorCode.KILL_SWITCH, 'Remote control is paused on this device');
|
|
1085
|
+
} catch (e) {
|
|
1086
|
+
return failOutcome(tool, e);
|
|
1087
|
+
}
|
|
1088
|
+
// Công cụ GUI ghi: chờ người điều khiển từ web thôi tay rồi mới chặn thao tác của họ — SAU hộp xác nhận, không thì người đang điều khiển
|
|
1089
|
+
// từ xa bị chặn đúng lúc cần bấm "Cho phép" trên hộp đó (luôn hết giờ).
|
|
1090
|
+
const guiWrite = tool.group === ToolGroup.GUI && !tool.read_only;
|
|
1091
|
+
if (guiWrite) {
|
|
1092
|
+
try {
|
|
1093
|
+
await waitForHumanToYield(call);
|
|
1094
|
+
} catch (e) {
|
|
1095
|
+
return failOutcome(tool, e, DeviceErrorCode.NOT_STARTED);
|
|
1096
|
+
}
|
|
1097
|
+
releaseCastInput();
|
|
1098
|
+
aiGuiBusy++;
|
|
1099
|
+
}
|
|
1100
|
+
try {
|
|
1101
|
+
hooks?.started?.();
|
|
1102
|
+
// 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).
|
|
1103
|
+
const handler = host?.runsInWorker(call.tool)
|
|
1104
|
+
? (args, ctx) => host.runFs(call.user_scope, call.tool, args, ctx)
|
|
1105
|
+
: (args, ctx) => tool.handler(args, ctx, callEnv);
|
|
1106
|
+
const outcome = boundedResult(await scheduler.run(
|
|
1107
|
+
call,
|
|
1108
|
+
{ group: tool.group, lockKeys: tool.lockKeys ? (a) => tool.lockKeys(a, callEnv) : undefined },
|
|
1109
|
+
handler,
|
|
1110
|
+
{ onOutput: streamer.push },
|
|
1111
|
+
));
|
|
1112
|
+
return { tool, outcome };
|
|
1113
|
+
} finally {
|
|
1114
|
+
if (guiWrite) aiGuiBusy--;
|
|
1115
|
+
}
|
|
1116
|
+
};
|
|
1117
|
+
|
|
1118
|
+
// Chống làm trùng khi BE gửi lại lô bước dở (xem idempotency.mjs).
|
|
1119
|
+
const runOnce = createIdempotentRunner(runCall, (name) => !!byName.get(name)?.read_only, {
|
|
1120
|
+
file: options.idemFile || REMOTE_IDEM_FILE,
|
|
1121
|
+
deferStart: true,
|
|
1122
|
+
onDuplicate: (call) => say(chalk.gray(` ↺ ${callLabel(call)}: đã làm ở lần gửi trước — trả lại kết quả cũ`)),
|
|
1123
|
+
});
|
|
1124
|
+
|
|
1125
|
+
/**
|
|
1126
|
+
* Trước khi AI bấm: chờ người thôi tay. Người đang tạm cầm lái từ web thì chờ lâu hơn hạn của lời gọi nên xin BE lùi hạn, và đăng ký vào
|
|
1127
|
+
* `gating` để lệnh huỷ dừng được lúc đang chờ. Không thì người vừa trả quyền xong là bước đã huỷ vẫn bấm.
|
|
1128
|
+
*/
|
|
1129
|
+
const waitForHumanToYield = async (call) => {
|
|
1130
|
+
const holdMs = castGate.takeoverWaitMs();
|
|
1131
|
+
if (!holdMs) return void await castGate.waitHumanIdle();
|
|
1132
|
+
const hold = (extraMs, phase) => emitHold(call.call_id, extraMs, phase);
|
|
1133
|
+
hold(holdMs, HoldPhase.WAITING);
|
|
1134
|
+
const controller = new AbortController();
|
|
1135
|
+
gating.set(call.call_id, controller);
|
|
1136
|
+
let yielded;
|
|
1137
|
+
try {
|
|
1138
|
+
yielded = await castGate.waitHumanIdle({ signal: controller.signal });
|
|
1139
|
+
} finally {
|
|
1140
|
+
gating.delete(call.call_id);
|
|
1141
|
+
}
|
|
1142
|
+
if (controller.signal.aborted) throw new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled while waiting for the person controlling this computer — the step did not run');
|
|
1143
|
+
if (!yielded) throw new DeviceToolError(DeviceErrorCode.NOT_STARTED, 'The person is still controlling this computer from the web — the step did not run, try again later');
|
|
1144
|
+
hold(0, HoldPhase.STARTED);
|
|
1145
|
+
};
|
|
1146
|
+
|
|
1147
|
+
const guiActivity = (call, outcome) => {
|
|
1148
|
+
const { method, action, window_class: windowClass } = outcome.result || {};
|
|
1149
|
+
return call.tool.startsWith('gui.') && method ? { method, action, window_class: windowClass } : {};
|
|
1150
|
+
};
|
|
1151
|
+
|
|
1152
|
+
/** 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. */
|
|
1153
|
+
const handleCall = async (call) => {
|
|
1154
|
+
const streamer = createStreamer(socket, call.call_id);
|
|
1155
|
+
let tool;
|
|
1156
|
+
let outcome;
|
|
1157
|
+
activeCalls++;
|
|
1158
|
+
lastActivityAt = Date.now();
|
|
1159
|
+
mascot.callStarted(call, byName.get(call.tool));
|
|
1160
|
+
keepAwake.hold();
|
|
1161
|
+
try {
|
|
1162
|
+
// Người đang điều khiển từ web → công cụ GUI ghi của AI chờ người thôi tay rồi mới bấm (trong runCall, sau hộp xác nhận).
|
|
1163
|
+
({ tool, outcome } = await runOnce(call, streamer));
|
|
1164
|
+
} catch (e) {
|
|
1165
|
+
outcome = { ok: false, error: e?.message || String(e), error_code: e?.code || DeviceErrorCode.EXECUTION_FAILED, duration_ms: 0 };
|
|
1166
|
+
} finally {
|
|
1167
|
+
keepAwake.release();
|
|
1168
|
+
syncProcAwake();
|
|
1169
|
+
}
|
|
1170
|
+
try {
|
|
1171
|
+
streamer.flush();
|
|
1172
|
+
// `ran` (scheduler: công cụ đã bắt đầu chưa) chỉ dùng trên máy (idempotency.mjs) — mã lỗi NOT_STARTED / INTERRUPTED đã nói cho BE.
|
|
1173
|
+
const { ran: _ran, ...sent } = outcome;
|
|
1174
|
+
const payload = { call_id: call.call_id, ...sent };
|
|
1175
|
+
ledger.finish(call.call_id, payload, { persistNow: !socket.connected });
|
|
1176
|
+
sendResult(payload);
|
|
1177
|
+
// GUI: thao tác đi đường nào (chạy nền hay chuột / phím thật) và trên loại cửa sổ nào — để biết còn bao nhiêu việc phải mượn chuột.
|
|
1178
|
+
logActivity({ type: 'tool_call', tool: call.tool, id: call.call_id, success: outcome.ok, error: outcome.error, ms: outcome.duration_ms, ...guiActivity(call, outcome) });
|
|
1179
|
+
if (!tool?.internal) {
|
|
1180
|
+
const failed = host ? outcome.error_code : outcome.error;
|
|
1181
|
+
say(outcome.ok ? chalk.green(` ✓ ${callLabel(call)} (${outcome.duration_ms} ms)`) : chalk.red(` ✗ ${callLabel(call)}: ${failed}`));
|
|
1182
|
+
}
|
|
1183
|
+
} catch (e) {
|
|
1184
|
+
console.error(chalk.red(`⚠️ Gửi kết quả ${call.tool} lỗi: ${e?.message || e}`));
|
|
1185
|
+
} finally {
|
|
1186
|
+
activeCalls--;
|
|
1187
|
+
lastActivityAt = Date.now();
|
|
1188
|
+
mascot.callFinished(call, tool, outcome);
|
|
1189
|
+
}
|
|
1190
|
+
};
|
|
1191
|
+
|
|
1192
|
+
/** 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). */
|
|
1193
|
+
const guarded = (event, fn) => (...args) => {
|
|
1194
|
+
try {
|
|
1195
|
+
const r = fn(...args);
|
|
1196
|
+
if (r && typeof r.catch === 'function') r.catch((e) => console.error(chalk.red(`⚠️ Xử lý ${event} lỗi: ${e?.message || e}`)));
|
|
1197
|
+
} catch (e) {
|
|
1198
|
+
console.error(chalk.red(`⚠️ Xử lý ${event} lỗi: ${e?.message || e}`));
|
|
1199
|
+
}
|
|
1200
|
+
};
|
|
1201
|
+
|
|
1202
|
+
// Chưa nối thì thôi: lần chào khi nối mang theo hồ sơ mới.
|
|
1203
|
+
announceProfile = () => (socket.connected ? announce() : undefined);
|
|
1204
|
+
socket.on('connect', guarded('connect', async () => {
|
|
1205
|
+
// Dựng sẵn exe đọc thời gian rảnh tay + exe hiện tên máy (lần đầu ~1–2 s csc) để lần máy chủ hỏi đầu tiên không quá hạn.
|
|
1206
|
+
void prepareHumanIdle().then(() => prepareIdentify()).then(() => prepareWindowProbe());
|
|
1207
|
+
confirmServerCredentialMigration(serverUrl);
|
|
1208
|
+
await announce();
|
|
1209
|
+
flushUnsent();
|
|
1210
|
+
}));
|
|
1211
|
+
let serverKicks = 0;
|
|
1212
|
+
socket.on('disconnect', guarded('disconnect', (reason) => {
|
|
1213
|
+
if (stopped) return;
|
|
1214
|
+
say(chalk.yellow(`⚠️ Mất kết nối (${reason}) — tự nối lại...`));
|
|
1215
|
+
// 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ờ.
|
|
1216
|
+
clearTimeout(castReconfirmTimer);
|
|
1217
|
+
castReconfirmTimer = null;
|
|
1218
|
+
if (!castDisconnectTimer && desktopCast.isActive()) {
|
|
1219
|
+
castDisconnectTimer = setTimeout(() => { castDisconnectTimer = null; stopDesktopCast('disconnected', false); }, CAST_DISCONNECT_GRACE_MS);
|
|
1220
|
+
}
|
|
1221
|
+
logActivity({ type: 'disconnected', reason });
|
|
1222
|
+
mascot.disconnected();
|
|
1223
|
+
mascotChat?.voiceDisconnected();
|
|
1224
|
+
// 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.
|
|
1225
|
+
if (reason === 'io server disconnect') {
|
|
1226
|
+
const delay = Math.min(RECONNECT_DELAY_MAX_MS, 1000 * 2 ** Math.min(serverKicks++, 5)) + Math.floor(Math.random() * 500);
|
|
1227
|
+
setTimeout(() => { if (!stopped) socket.connect(); }, delay);
|
|
1228
|
+
}
|
|
1229
|
+
}));
|
|
1230
|
+
socket.on('connect', () => {
|
|
1231
|
+
serverKicks = 0;
|
|
1232
|
+
clearTimeout(castDisconnectTimer);
|
|
1233
|
+
castDisconnectTimer = null;
|
|
1234
|
+
// Phiên còn chạy qua lần rớt mạng: máy chủ (còn giữ phiên) sẽ mời phát lại; im lặng = phiên đã hết hạn ở máy chủ → dừng, không quay màn
|
|
1235
|
+
// hình cho không ai.
|
|
1236
|
+
clearTimeout(castReconfirmTimer);
|
|
1237
|
+
castReconfirmTimer = desktopCast.isActive() ? setTimeout(() => {
|
|
1238
|
+
castReconfirmTimer = null;
|
|
1239
|
+
if (desktopCast.isActive()) stopDesktopCast('session_expired');
|
|
1240
|
+
}, CAST_RECONFIRM_MS) : null;
|
|
1241
|
+
});
|
|
1242
|
+
socket.on('connect_error', guarded('connect_error', (err) => {
|
|
1243
|
+
// 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.
|
|
1244
|
+
if (err?.message === 'DEVICE_TOKEN_RETIRED') {
|
|
1245
|
+
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).'));
|
|
1246
|
+
stopForGood();
|
|
1247
|
+
return;
|
|
1248
|
+
}
|
|
1249
|
+
if (err?.message === 'DEVICE_UNAUTHORIZED') {
|
|
1250
|
+
// 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).
|
|
1251
|
+
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ũ'));
|
|
1252
|
+
const replaced = !clearDeviceCredentials(creds.device_token, serverUrl);
|
|
1253
|
+
console.log(chalk.red(replaced
|
|
1254
|
+
? '❌ 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.'
|
|
1255
|
+
: '❌ 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.'));
|
|
1256
|
+
stopForGood();
|
|
1257
|
+
return;
|
|
1258
|
+
}
|
|
1259
|
+
say(chalk.gray(` (chưa nối được: ${err?.message} — thử lại...)`));
|
|
1260
|
+
}));
|
|
1261
|
+
socket.on(DeviceEvent.REPLACED, guarded(DeviceEvent.REPLACED, (payload) => {
|
|
1262
|
+
if (!payload?.by_instance || payload.by_instance === instance) return;
|
|
1263
|
+
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.'));
|
|
1264
|
+
stopForGood();
|
|
1265
|
+
}));
|
|
1266
|
+
socket.on(DeviceEvent.REVOKED, guarded(DeviceEvent.REVOKED, () => {
|
|
1267
|
+
clearDeviceCredentials(creds.device_token, serverUrl);
|
|
1268
|
+
console.log(chalk.red('❌ Máy này đã bị thu hồi quyền điều khiển từ xa.'));
|
|
1269
|
+
stopForGood();
|
|
1270
|
+
}));
|
|
1271
|
+
socket.on(DeviceEvent.CALLS, guarded(DeviceEvent.CALLS, (payload) => {
|
|
1272
|
+
// 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).
|
|
1273
|
+
const calls = (Array.isArray(payload?.calls) ? payload.calls : []).filter(isValidDeviceCall);
|
|
1274
|
+
if (!calls.length) return;
|
|
1275
|
+
socket.emit(DeviceEvent.ACK, { call_ids: calls.map((c) => c.call_id) });
|
|
1276
|
+
// 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ũ.
|
|
1277
|
+
calls.forEach((call) => {
|
|
1278
|
+
const prior = ledger.admit(call);
|
|
1279
|
+
if (!prior) return void handleCall(call);
|
|
1280
|
+
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ó'}`));
|
|
1281
|
+
if (prior.state === CallState.DONE) sendResult(ledger.reopen(call.call_id));
|
|
1282
|
+
});
|
|
1283
|
+
}));
|
|
1284
|
+
socket.on(DeviceEvent.CANCEL, guarded(DeviceEvent.CANCEL, (payload) => {
|
|
1285
|
+
if (!Array.isArray(payload?.call_ids)) return;
|
|
1286
|
+
const ids = payload.call_ids.filter((id) => typeof id === 'string');
|
|
1287
|
+
scheduler.cancel(ids);
|
|
1288
|
+
cancelGating(ids);
|
|
1289
|
+
}));
|
|
1290
|
+
if (mascot.enabled) {
|
|
1291
|
+
mascotChat = createMascotChat({
|
|
1292
|
+
socket: () => socket, send: (cmd) => mascot.chat(cmd), lang: mascot.lang,
|
|
1293
|
+
onAlert: (alert) => mascot.alert(alert), onPending: (on) => mascot.needsYou(on),
|
|
1294
|
+
micBusy: () => !!meetings?.status()?.recording,
|
|
1295
|
+
serverUrl: creds?.server_url || serverUrl,
|
|
1296
|
+
notifyFreq: loadMascotSettings().notify_freq ?? 1,
|
|
1297
|
+
onWorkDir: (dir) => { try { saveMascotSettings({ work_dir: dir }); } catch { /* lần chạy sau không nhớ thư mục này */ } },
|
|
1298
|
+
});
|
|
1299
|
+
if (earlyDrops.length) mascotChat.attach(earlyDrops.splice(0));
|
|
1300
|
+
// Thư mục làm việc lần trước: chỉ khôi phục khi còn tồn tại và còn trong quyền (quyền có thể đã bị thu lại).
|
|
1301
|
+
const savedWorkDir = loadMascotSettings().work_dir;
|
|
1302
|
+
if (savedWorkDir && isAllowedWorkFolder(savedWorkDir, roots)) mascotChat.setWorkDir(savedWorkDir, { quiet: true });
|
|
1303
|
+
if (earlyWorkDir) mascotChat.setWorkDir(earlyWorkDir);
|
|
1304
|
+
socket.on(DeviceEvent.CHAT_EVENT, guarded(DeviceEvent.CHAT_EVENT, (payload) => mascotChat.onChatEvent(payload)));
|
|
1305
|
+
// 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.
|
|
1306
|
+
socket.on(DeviceEvent.NOTIFY, guarded(DeviceEvent.NOTIFY, (payload) => mascotChat.onNotify(payload)));
|
|
1307
|
+
socket.on(DeviceEvent.QUESTION_CLOSED, guarded(DeviceEvent.QUESTION_CLOSED, (payload) => mascotChat.onQuestionClosed(payload)));
|
|
1308
|
+
socket.on(DeviceEvent.VOICE_EVENT, guarded(DeviceEvent.VOICE_EVENT, (payload) => mascotChat.onVoiceEvent(payload)));
|
|
1309
|
+
}
|
|
1310
|
+
socket.on(DeviceEvent.UPDATE, guarded(DeviceEvent.UPDATE, (payload) => {
|
|
1311
|
+
if (!updater) return;
|
|
1312
|
+
if (payload?.min_version) updater.setMinVersion(payload.min_version);
|
|
1313
|
+
if (payload?.latest_version) updater.setServerHints(payload);
|
|
1314
|
+
updater.requestCheck();
|
|
1315
|
+
}));
|
|
1316
|
+
socket.on(DeviceEvent.DESKTOP_CAST_START, guarded(DeviceEvent.DESKTOP_CAST_START, async (payload) => {
|
|
1317
|
+
const sessionId = payload?.session_id;
|
|
1318
|
+
const viewerId = payload?.viewer_id;
|
|
1319
|
+
const viewerType = payload?.viewer_device || payload?.viewerDevice || payload?.viewer_platform || payload?.viewerPlatform;
|
|
1320
|
+
const deviceKey = typeof payload?.device_key === 'string' ? payload.device_key : '';
|
|
1321
|
+
// `viewer_name` (loại máy + model + trình duyệt) chỉ để hiện; máy chủ đời cũ không gửi thì dùng loại máy.
|
|
1322
|
+
const viewerDevice = castViewerLabel(payload?.viewer_name || viewerType, deviceKey, payload?.viewer_key);
|
|
1323
|
+
// Tài khoản / nơi / IP do máy chủ thấy (trình duyệt không tự khai được): chủ máy nhờ đó biết ai đang xin vào, không chỉ tên máy.
|
|
1324
|
+
const viewerInfo = castViewerInfo(payload, mascotLang());
|
|
1325
|
+
if (!sessionId || !viewerId) return;
|
|
1326
|
+
// Chủ máy đã tạm dừng điều khiển từ xa → từ chối cả xem màn hình.
|
|
1327
|
+
if (isRemotePaused()) {
|
|
1328
|
+
emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: 'paused' });
|
|
1329
|
+
return;
|
|
1330
|
+
}
|
|
1331
|
+
// Quyết định trước khi chụp bất cứ thứ gì; chỉ máy này trả lời được, máy chủ không trả lời thay.
|
|
1332
|
+
const decision = await castConsent.decide({
|
|
1333
|
+
sessionId, viewerId, viewerDevice, viewerKey: payload?.viewer_key, deviceKey, viewerInfo,
|
|
1334
|
+
prove: async () => {
|
|
1335
|
+
const proven = await castProver.prove({ sessionId, viewerId, deviceKey });
|
|
1336
|
+
if (proven === true) say(chalk.cyan(` 🔑 Thiết bị tin cậy "${viewerDevice || viewerId}" vào xem màn hình`));
|
|
1337
|
+
return proven;
|
|
1338
|
+
},
|
|
1339
|
+
});
|
|
1340
|
+
if (decision !== CastConsentDecision.ALLOW) {
|
|
1341
|
+
logActivity({ type: 'desktop_cast_consent', id: sessionId, viewer: viewerDevice || viewerId, ...viewerInfo, result: decision });
|
|
1342
|
+
if (decision === CastConsentDecision.CANCELLED) return;
|
|
1343
|
+
say(chalk.red(` ✕ Không cho xem màn hình (${decision}): ${viewerDevice || viewerId}`));
|
|
1344
|
+
emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: decision });
|
|
1345
|
+
return;
|
|
1346
|
+
}
|
|
1347
|
+
// Chủ máy có thể bấm tạm dừng trong lúc hộp đang mở.
|
|
1348
|
+
if (isRemotePaused()) {
|
|
1349
|
+
emitCastStatus({ session_id: sessionId, viewer_id: viewerId, state: CastState.REFUSED, reason: 'paused' });
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
logActivity({ type: 'desktop_cast_consent', id: sessionId, viewer: viewerDevice || viewerId, ...viewerInfo, result: decision });
|
|
1353
|
+
const castConfig = {
|
|
1354
|
+
max_fps: payload?.max_fps || 15,
|
|
1355
|
+
max_width: payload?.max_width || 1366,
|
|
1356
|
+
quality: payload?.quality || 65,
|
|
1357
|
+
monitor: payload?.monitor ?? -1,
|
|
1358
|
+
};
|
|
1359
|
+
if (desktopCast.isActive() && desktopCast.sessionId() !== sessionId) stopDesktopCast('replaced', false);
|
|
1360
|
+
castTouchViewers.add(viewerId, viewerType);
|
|
1361
|
+
if (desktopCast.sessionId() === sessionId) {
|
|
1362
|
+
clearTimeout(castReconfirmTimer);
|
|
1363
|
+
castReconfirmTimer = null;
|
|
1364
|
+
}
|
|
1365
|
+
if (!desktopCast.isActive()) {
|
|
1366
|
+
castInputTag = newInputTag();
|
|
1367
|
+
castRestarts.length = 0;
|
|
1368
|
+
if (!startCapture({ sessionId, viewerId, viewerDevice, viewerPlace: viewerInfo.place, castConfig })) return;
|
|
1369
|
+
} else {
|
|
1370
|
+
desktopCast.config(castConfig);
|
|
1371
|
+
// Màn hình đứng yên thì ảnh thưa: người mới vào cần một ảnh ngay.
|
|
1372
|
+
desktopCast.refresh();
|
|
1373
|
+
}
|
|
1374
|
+
// Ảnh mở màn (BE chỉ gửi khi người xem mở lại trên mạng đã biết là tốt): một ảnh JPEG nét trong lúc video còn khởi động.
|
|
1375
|
+
const leadIn = castLeadInConfig(payload?.lead_in);
|
|
1376
|
+
if (leadIn) desktopCast.config(leadIn);
|
|
1377
|
+
const webRtcStarted = payload?.transport === 'webrtc'
|
|
1378
|
+
? await desktopWebRtc.start({ sessionId, viewerId, iceServers: payload?.ice_servers || [], videoBitrate: payload?.video_bitrate || null, videoCodecs: Array.isArray(payload?.video_codecs) ? payload.video_codecs : null, audio: payload?.audio !== false }).catch(() => false)
|
|
1379
|
+
: false;
|
|
1380
|
+
// Phiên đã dừng / bị thay trong lúc dựng WebRTC (tới 30 s): không báo trạng thái cho phiên đã chết.
|
|
1381
|
+
if (desktopCast.sessionId() !== sessionId) return;
|
|
1382
|
+
if (webRtcStarted) desktopWebRtc.attachPipe(desktopCast.pipeName());
|
|
1383
|
+
if (!webRtcStarted) emitCastStatus({
|
|
1384
|
+
session_id: sessionId, viewer_id: viewerId, state: CastState.DEGRADED, transport: 'jpeg', reason: 'webrtc_runtime_unavailable',
|
|
1385
|
+
});
|
|
1386
|
+
}));
|
|
1387
|
+
socket.on(DeviceEvent.DESKTOP_CAST_STOP, guarded(DeviceEvent.DESKTOP_CAST_STOP, (payload) => {
|
|
1388
|
+
if (payload?.session_id) castConsent.cancel({ sessionId: payload.session_id, viewerId: payload.viewer_id, final: payload.final !== false, away: payload.away === true });
|
|
1389
|
+
castProver.cancel(payload?.final !== false ? undefined : payload?.viewer_id);
|
|
1390
|
+
if (payload?.session_id && payload.session_id !== desktopCast.sessionId()) {
|
|
1391
|
+
// Phiên đã dừng ở máy (gián đoạn) mà máy chủ kết thúc hẳn: quên đồng ý đang giữ.
|
|
1392
|
+
if (payload.final !== false) castConsent.forget(payload.session_id);
|
|
1393
|
+
return;
|
|
1394
|
+
}
|
|
1395
|
+
clearTimeout(castReconfirmTimer);
|
|
1396
|
+
castReconfirmTimer = null;
|
|
1397
|
+
if (payload?.viewer_id) {
|
|
1398
|
+
castTouchViewers.remove(payload.viewer_id);
|
|
1399
|
+
desktopWebRtc.close(payload.viewer_id);
|
|
1400
|
+
void castFileDrop.close(payload.viewer_id);
|
|
1401
|
+
releaseViewerInput(payload.viewer_id);
|
|
1402
|
+
}
|
|
1403
|
+
if (payload?.final !== false) stopDesktopCast('server', false);
|
|
1404
|
+
}));
|
|
1405
|
+
socket.on(DeviceEvent.DESKTOP_CAST_INPUT, guarded(DeviceEvent.DESKTOP_CAST_INPUT, (payload) => applyRemoteInput(payload)));
|
|
1406
|
+
socket.on(DeviceEvent.DESKTOP_CAST_CONFIG, guarded(DeviceEvent.DESKTOP_CAST_CONFIG, (payload) => {
|
|
1407
|
+
if (payload?.session_id && payload.session_id !== desktopCast.sessionId()) return;
|
|
1408
|
+
const { max_fps, max_width, quality, monitor, audio } = payload || {};
|
|
1409
|
+
desktopCast.config({ max_fps, max_width, quality, monitor, ...(typeof audio === 'boolean' ? { audio } : {}) });
|
|
1410
|
+
if (typeof audio === 'boolean') desktopWebRtc.setAudio(audio);
|
|
1411
|
+
}));
|
|
1412
|
+
socket.on(DeviceEvent.DESKTOP_CAST_TAKEOVER, guarded(DeviceEvent.DESKTOP_CAST_TAKEOVER, (payload) => {
|
|
1413
|
+
if (!payload?.session_id || payload.session_id !== desktopCast.sessionId()) return;
|
|
1414
|
+
castGate.setHumanTakeover(payload.active === true ? { idleMs: Number(payload.idle_ms), maxWaitMs: Number(payload.max_wait_ms) } : null);
|
|
1415
|
+
}));
|
|
1416
|
+
// Máy chủ hỏi máy rảnh tay bao lâu để biết trình duyệt có đang mở ngay trên máy này không (chỉ trả con số, không lộ gì khác).
|
|
1417
|
+
socket.on(DeviceEvent.HUMAN_IDLE, guarded(DeviceEvent.HUMAN_IDLE, async (_payload, ack) => {
|
|
1418
|
+
if (typeof ack !== 'function') return;
|
|
1419
|
+
const idleMs = await readHumanIdleMs();
|
|
1420
|
+
ack(idleMs === null ? { ok: false } : { ok: true, idle_ms: idleMs });
|
|
1421
|
+
}));
|
|
1422
|
+
// Máy chủ hỏi trình duyệt xem màn hình có đang mở ngay trên máy này không (chỉ trả có / không): (1) có cửa sổ mang mã trang vừa gắn vào tiêu
|
|
1423
|
+
// đề tab; (2) IP trình duyệt (máy chủ thấy) đang gắn trên card mạng của máy — IPv6 công cộng là của riêng từng máy, Windows giữ cùng lúc
|
|
1424
|
+
// nhiều địa chỉ tạm nên so ở đây đúng cả khi địa chỉ vừa đổi (máy chủ so với IP lúc máy nối thì trượt).
|
|
1425
|
+
socket.on(DeviceEvent.WINDOW_PROBE, guarded(DeviceEvent.WINDOW_PROBE, async (payload, ack) => {
|
|
1426
|
+
if (typeof ack !== 'function') return;
|
|
1427
|
+
const ips = (Array.isArray(payload?.viewer_ips) ? payload.viewer_ips : []).slice(0, 8).filter((ip) => typeof ip === 'string');
|
|
1428
|
+
const ownIp = ips.some((ip) => isOwnAddress(ip));
|
|
1429
|
+
const found = payload?.nonce ? await findWindowTitle(payload.nonce) : null;
|
|
1430
|
+
ack({ ok: true, found: found === true, own_ip: ownIp, ...(payload?.nonce && found === null ? { title_unknown: true } : {}) });
|
|
1431
|
+
}));
|
|
1432
|
+
// Chủ máy rê chuột lên dòng máy này trên web → hiện tên máy to trên màn hình vài giây (không lấy tiêu điểm, bấm xuyên qua được).
|
|
1433
|
+
socket.on(DeviceEvent.IDENTIFY, guarded(DeviceEvent.IDENTIFY, async (payload) => {
|
|
1434
|
+
if (isRemotePaused()) return;
|
|
1435
|
+
await showIdentify({ name: payload?.name, durationMs: payload?.duration_ms, lang: mascotLang() });
|
|
1436
|
+
}));
|
|
1437
|
+
socket.on(DeviceEvent.DESKTOP_CAST_SIGNAL, guarded(DeviceEvent.DESKTOP_CAST_SIGNAL, (payload) => {
|
|
1438
|
+
if (payload?.type === 'device_proof') return castProver.answer(payload);
|
|
1439
|
+
void desktopWebRtc.signal(payload).catch(() => undefined);
|
|
1440
|
+
}));
|
|
1441
|
+
meetings?.recover();
|
|
1442
|
+
|
|
1443
|
+
// 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).
|
|
1444
|
+
if (!unhandledRejectionHooked) {
|
|
1445
|
+
unhandledRejectionHooked = true;
|
|
1446
|
+
process.on('unhandledRejection', (reason) => console.error(chalk.red(`⚠️ Lỗi không được xử lý: ${reason?.stack || reason?.message || reason}`)));
|
|
1447
|
+
// 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).
|
|
1448
|
+
process.on('uncaughtException', (error) => console.error(chalk.red(`⚠️ Lỗi không được xử lý: ${error?.stack || error?.message || error}`)));
|
|
1449
|
+
}
|
|
1450
|
+
|
|
1451
|
+
if (options.handleSignals !== false) {
|
|
1452
|
+
// 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.
|
|
1453
|
+
const onSignal = () => { Promise.resolve(stop()).finally(() => process.exit(0)); };
|
|
1454
|
+
process.once('SIGINT', onSignal);
|
|
1455
|
+
process.once('SIGTERM', onSignal);
|
|
1456
|
+
}
|
|
1457
|
+
|
|
1458
|
+
return { stop, socket, profile, env, creds, scheduler, catalog };
|
|
1459
|
+
}
|
|
1460
|
+
|
|
1461
|
+
/**
|
|
1462
|
+
* 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
|
|
1463
|
+
* socket, bắt tay thử sẽ đá daemon đang chạy ra.
|
|
1464
|
+
*/
|
|
1465
|
+
export async function testRemoteConnection(options = {}) {
|
|
1466
|
+
const savedHint = loadDeviceCredentials();
|
|
1467
|
+
const serverUrl = resolveServerUrl(options, savedHint);
|
|
1468
|
+
const creds = loadDeviceCredentials(serverUrl);
|
|
1469
|
+
const apiKey = options.apiKey ?? process.env.API_KEY;
|
|
1470
|
+
const report = { serverUrl, paired: !!creds, deviceId: creds?.device_id, httpOk: false, latencyMs: null, online: null, error: null };
|
|
1471
|
+
const startedAt = Date.now();
|
|
1472
|
+
try {
|
|
1473
|
+
const res = await axios.get(`${serverUrl}/setting/lang/default`, { timeout: 6000, validateStatus: () => true });
|
|
1474
|
+
report.httpOk = res.status < 500;
|
|
1475
|
+
report.latencyMs = Date.now() - startedAt;
|
|
1476
|
+
} catch (e) {
|
|
1477
|
+
report.error = `HTTP: ${e.message}`;
|
|
1478
|
+
}
|
|
1479
|
+
if (!creds || !apiKey) return report;
|
|
1480
|
+
try {
|
|
1481
|
+
const devices = await listDevices({ serverUrl, apiKey });
|
|
1482
|
+
const me = devices.find((d) => d.device_id === creds.device_id);
|
|
1483
|
+
report.online = me ? me.online : false;
|
|
1484
|
+
report.registered = !!me;
|
|
1485
|
+
report.toolsOnServer = me?.tools_count;
|
|
1486
|
+
} catch (e) {
|
|
1487
|
+
report.error = e.message;
|
|
1488
|
+
}
|
|
1489
|
+
return report;
|
|
1490
|
+
}
|