@aivin-labs/cli 1.0.11 → 1.0.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +325 -288
- package/bin/cli.mjs +163 -17
- package/bin/lib/localPreview.mjs +437 -0
- package/bin/lib/openFile.mjs +235 -0
- package/bin/lib/previewCache.mjs +71 -0
- package/bin/lib/remote/atomicFile.mjs +32 -0
- package/bin/lib/remote/autoStart.mjs +2 -1
- package/bin/lib/remote/autoUpdate.mjs +12 -0
- package/bin/lib/remote/browserTunnel.mjs +47 -8
- package/bin/lib/remote/callLedger.mjs +94 -14
- package/bin/lib/remote/cdpPolicy.mjs +14 -2
- package/bin/lib/remote/client.mjs +1024 -808
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +2 -2
- package/bin/lib/remote/constants.mjs +261 -234
- package/bin/lib/remote/credentials.mjs +81 -4
- package/bin/lib/remote/daemonLock.mjs +57 -17
- package/bin/lib/remote/dailyBrowser.mjs +8 -2
- package/bin/lib/remote/desktop/castInput.mjs +98 -0
- package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
- package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
- package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
- package/bin/lib/remote/desktop/index.mjs +58 -7
- package/bin/lib/remote/desktop/linux.mjs +1 -1
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
- package/bin/lib/remote/desktop/mac.mjs +2 -2
- package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
- package/bin/lib/remote/desktop/strings.mjs +28 -2
- package/bin/lib/remote/desktop/traySource.mjs +905 -527
- package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
- package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +85 -0
- package/bin/lib/remote/fileIndexer.mjs +773 -399
- package/bin/lib/remote/folderRules.mjs +143 -0
- package/bin/lib/remote/gitSafe.mjs +31 -0
- package/bin/lib/remote/gui/index.mjs +170 -19
- package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
- package/bin/lib/remote/gui/windowsHost.mjs +12 -3
- package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
- package/bin/lib/remote/httpTransfer.mjs +64 -3
- package/bin/lib/remote/idempotency.mjs +49 -20
- package/bin/lib/remote/localPolicy.mjs +81 -9
- package/bin/lib/remote/mascot/ask.mjs +207 -42
- package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +658 -512
- package/bin/lib/remote/mascot/blocks.mjs +201 -0
- package/bin/lib/remote/mascot/bot.mjs +54 -5
- package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
- package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
- package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
- package/bin/lib/remote/mascot/fileChips.mjs +62 -0
- package/bin/lib/remote/mascot/hostSource.mjs +331 -52
- package/bin/lib/remote/mascot/hotkey.mjs +31 -7
- package/bin/lib/remote/mascot/images.mjs +111 -0
- package/bin/lib/remote/mascot/index.mjs +663 -493
- package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
- package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
- package/bin/lib/remote/mascot/mood.mjs +57 -0
- package/bin/lib/remote/mascot/rigSource.mjs +648 -609
- package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
- package/bin/lib/remote/mascot/strings.mjs +456 -375
- package/bin/lib/remote/mascot/ui.mjs +27 -7
- package/bin/lib/remote/multiUser.mjs +7 -2
- package/bin/lib/remote/notify.mjs +4 -1
- package/bin/lib/remote/office/index.mjs +12 -6
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/processes.mjs +5 -2
- package/bin/lib/remote/sandbox.mjs +26 -0
- package/bin/lib/remote/secretPaths.mjs +21 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tokenRotation.mjs +28 -0
- package/bin/lib/remote/toolHandlers.mjs +852 -741
- package/bin/lib/remote/watchBatcher.mjs +56 -0
- package/bin/lib/remoteControl.mjs +26 -26
- package/bin/lib/selfUpdate.mjs +12 -2
- package/bin/lib/update/binarySwap.mjs +15 -1
- package/bin/lib/update/state.mjs +10 -0
- package/docs/AIVIN_MASCOT.md +14 -0
- package/docs/CLI.md +1545 -1484
- package/docs/media/aivin-ecosystem.jpg +0 -0
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +75 -71
- package/docs/media/aivin-mascot-states.mp4 +0 -0
|
@@ -1,493 +1,663 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import path from 'path';
|
|
3
|
-
import readline from 'readline';
|
|
4
|
-
import { createHash } from 'crypto';
|
|
5
|
-
import { spawn } from 'child_process';
|
|
6
|
-
import { NotifyKind, REMOTE_CONFIG_DIR, ToolGroup } from '../constants.mjs';
|
|
7
|
-
import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
|
|
8
|
-
import { MASCOT_LAYERS } from './assets.mjs';
|
|
9
|
-
import { MASCOT_GLYPHS, MASCOT_PALETTE, MASCOT_PS1, MASCOT_XAML } from './hostSource.mjs';
|
|
10
|
-
import { ASK_PS1 } from './askHostSource.mjs';
|
|
11
|
-
import { AskCommand, MAX_ATTACH, QUESTION_ROW } from './ask.mjs';
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
import {
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
*
|
|
24
|
-
* thái
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
export const
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
export const
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
const
|
|
41
|
-
|
|
42
|
-
/**
|
|
43
|
-
export
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
});
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
const
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
const
|
|
90
|
-
const
|
|
91
|
-
|
|
92
|
-
const
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
}
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
*/
|
|
126
|
-
export function
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
const
|
|
134
|
-
const
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
if (
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
return;
|
|
266
|
-
}
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
if (
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
if (
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
if (!
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
}
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
return
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
const
|
|
424
|
-
|
|
425
|
-
timers.
|
|
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
|
-
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import readline from 'readline';
|
|
4
|
+
import { createHash } from 'crypto';
|
|
5
|
+
import { spawn } from 'child_process';
|
|
6
|
+
import { NotifyKind, REMOTE_CONFIG_DIR, ToolGroup } from '../constants.mjs';
|
|
7
|
+
import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
|
|
8
|
+
import { MASCOT_LAYERS } from './assets.mjs';
|
|
9
|
+
import { MASCOT_GLYPHS, MASCOT_PALETTE, MASCOT_PS1, MASCOT_XAML } from './hostSource.mjs';
|
|
10
|
+
import { ASK_PS1 } from './askHostSource.mjs';
|
|
11
|
+
import { AskCommand, MAX_ATTACH, QUESTION_ROW, safeWebUrl, VoiceCommand } from './ask.mjs';
|
|
12
|
+
import { hostHotkeys } from './hotkey.mjs';
|
|
13
|
+
|
|
14
|
+
const ASK_HOOK = '# @ASK_HOOK';
|
|
15
|
+
import { describeStep } from './labels.mjs';
|
|
16
|
+
import { MOOD_GESTURE, moodOf, SUBDUED_MOODS } from './mood.mjs';
|
|
17
|
+
import { MascotText, mascotLang, mascotText, windowStrings } from './strings.mjs';
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* Linh vật Aivin trên màn hình máy người dùng (29/10/2026): một nhân vật nhỏ dựng từ logo, nổi trên mọi cửa sổ khi `aivin remote start`
|
|
21
|
+
* chạy, bong bóng trên đầu hiện việc chính đang làm (mục đích bước / "Đọc baocao.xlsx"), kéo đi đâu cũng được, bấm vào ra bảng nhật ký chi
|
|
22
|
+
* tiết + nút tạm dừng AI. Đợt đầu Windows (WPF, hostSource.mjs); hệ điều hành khác / máy tính tổ chức → không có gì (mọi hàm là no-op).
|
|
23
|
+
*
|
|
24
|
+
* Trạng thái: working (có bước đang chạy) → thinking (vừa xong lô, BE đang lập bước kế — chưa coi là xong) → done / error (yên THINK_MS
|
|
25
|
+
* mà không có lô mới) → idle. waiting (chờ người bấm xác nhận trên máy), paused (công tắc ngắt), offline (mất kết nối) đè lên các trạng
|
|
26
|
+
* thái kia. Bong bóng đổi tối đa mỗi MAIN_THROTTLE_MS (lô nhiều bước chỉ hiện bước mới nhất, không nhấp nháy).
|
|
27
|
+
*/
|
|
28
|
+
|
|
29
|
+
export const MASCOT_DIR = path.join(REMOTE_CONFIG_DIR, 'mascot');
|
|
30
|
+
export const MASCOT_SETTINGS_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot.json');
|
|
31
|
+
|
|
32
|
+
export const MascotState = Object.freeze({
|
|
33
|
+
IDLE: 'idle', WORKING: 'working', THINKING: 'thinking', WAITING: 'waiting', PAUSED: 'paused', OFFLINE: 'offline', DONE: 'done', ERROR: 'error',
|
|
34
|
+
});
|
|
35
|
+
export const LogStatus = Object.freeze({ RUN: 'run', OK: 'ok', FAIL: 'fail', INFO: 'info', WARN: 'warn' });
|
|
36
|
+
/** Lệnh gửi cửa sổ / sự kiện cửa sổ gửi về (một dòng JSON mỗi lệnh). */
|
|
37
|
+
export const HostCommand = Object.freeze({ STATE: 'state', MAIN: 'main', LOG: 'log', GUI: 'gui', SHOW: 'show', QUIT: 'quit', OPEN_ASK: 'open_ask', VOICE_TOGGLE: 'voice_toggle', GESTURE: 'gesture', NOTIFY_FREQ: 'notify_freq' });
|
|
38
|
+
|
|
39
|
+
/** `aivin ui` (terminal khác) chạm tệp này → daemon đang chạy hiện linh vật + mở ô hỏi (mascot/ui.mjs). */
|
|
40
|
+
export const MASCOT_SHOW_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot-show');
|
|
41
|
+
export const MASCOT_HIDE_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot-hide');
|
|
42
|
+
/** Mục "Quick voice" của khay chạm tệp này → daemon hiện linh vật + bấm mic. Xử lý xong xoá luôn: daemon khởi động lại không được tự mở mic. */
|
|
43
|
+
export const MASCOT_VOICE_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot-voice');
|
|
44
|
+
/** Phím tắt cửa sổ linh vật đang giữ thật (`{ chat, voice }`, tổ hợp đầu tiên còn trống) — khay đọc để hiện cạnh mục menu; cửa sổ đóng thì xoá. */
|
|
45
|
+
export const MASCOT_HOTKEYS_FILE = path.join(REMOTE_CONFIG_DIR, 'mascot-hotkeys.json');
|
|
46
|
+
const SHOW_POLL_MS = 250;
|
|
47
|
+
const SHOW_REQUEST_GRACE_MS = 30_000;
|
|
48
|
+
|
|
49
|
+
/** Ghi yêu cầu hiện linh vật cho daemon đang chạy (hoặc sắp chạy). */
|
|
50
|
+
export function requestMascotShow(file = MASCOT_SHOW_FILE) {
|
|
51
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
52
|
+
fs.writeFileSync(file, String(Date.now()));
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/** Ghi yêu cầu ẩn linh vật cho daemon đang chạy. */
|
|
56
|
+
export function requestMascotHide(file = MASCOT_HIDE_FILE) {
|
|
57
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
58
|
+
fs.writeFileSync(file, String(Date.now()));
|
|
59
|
+
}
|
|
60
|
+
export const HostEvent = Object.freeze({
|
|
61
|
+
READY: 'ready', POS: 'pos', PAUSE: 'pause', RESUME: 'resume', HIDE: 'hide', OFF: 'off', ASK: 'ask', CHOOSE: 'choose', CANCEL: 'cancel', NEW_CHAT: 'new_chat', OPEN_WEBVIEW: 'open_webview',
|
|
62
|
+
DROP: 'drop', DETACH: 'detach', AWAY: 'away', BACK: 'back', NOTIFY_FREQ: 'notify_freq', HOTKEYS: 'hotkeys',
|
|
63
|
+
VOICE_START: 'voice_start', VOICE_AUDIO: 'voice_audio', VOICE_INTERRUPT: 'voice_interrupt', VOICE_STOP: 'voice_stop', VOICE_MIC_LOST: 'voice_mic_lost',
|
|
64
|
+
});
|
|
65
|
+
const VOICE_EVENTS = new Set([HostEvent.VOICE_START, HostEvent.VOICE_AUDIO, HostEvent.VOICE_INTERRUPT, HostEvent.VOICE_STOP, HostEvent.VOICE_MIC_LOST]);
|
|
66
|
+
|
|
67
|
+
const THINK_MS = 8000;
|
|
68
|
+
const RESULT_MS = 6000;
|
|
69
|
+
const MAIN_THROTTLE_MS = 600;
|
|
70
|
+
const RESTART_DELAYS_MS = [5000, 30_000, 120_000];
|
|
71
|
+
const QUEUE_LOGS = 40;
|
|
72
|
+
/** Vắng lâu chừng này mà không có việc gì xảy ra → quay lại vẫn được vẫy chào (không bong bóng). */
|
|
73
|
+
const AWAY_WAVE_MS = 30 * 60_000;
|
|
74
|
+
|
|
75
|
+
/** mascot.json có nhưng không đọc được thành object JSON (đang ghi dở, hỏng tay…) → lượt lưu không ghi đè (02/11/2026). */
|
|
76
|
+
export class MascotSettingsUnreadable extends Error {}
|
|
77
|
+
|
|
78
|
+
function readMascotFile(file) {
|
|
79
|
+
let raw;
|
|
80
|
+
const unreadable = (why) => new MascotSettingsUnreadable(`${file} could not be read (${why}) — fix or delete it`);
|
|
81
|
+
try { raw = fs.readFileSync(file, 'utf8'); } catch (e) { if (e?.code === 'ENOENT') return null; throw unreadable(e?.code || e?.message); }
|
|
82
|
+
let data;
|
|
83
|
+
try { data = JSON.parse(raw.replace(/^\uFEFF/, '')); } catch (e) { throw unreadable(e?.message); }
|
|
84
|
+
if (!data || typeof data !== 'object' || Array.isArray(data)) throw unreadable('not a JSON object');
|
|
85
|
+
return data;
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
function normalizeMascotSettings(data) {
|
|
89
|
+
const pos = Number.isFinite(data.x) && Number.isFinite(data.y) ? { x: data.x, y: data.y } : {};
|
|
90
|
+
const freq = Number.isInteger(data.notify_freq) && data.notify_freq >= 0 && data.notify_freq <= 2 ? { notify_freq: data.notify_freq } : {};
|
|
91
|
+
// `aivin remote mascot hotkey …` (cli.mjs): tổ hợp chủ máy đặt / 'off'; trước đây bị bỏ khi đọc → lượt lưu vị trí kế tiếp xoá mất.
|
|
92
|
+
const hotkey = typeof data.hotkey === 'string' && data.hotkey ? { hotkey: data.hotkey } : {};
|
|
93
|
+
const chatHotkey = typeof data.chat_hotkey === 'string' && data.chat_hotkey ? { chat_hotkey: data.chat_hotkey } : {};
|
|
94
|
+
return { enabled: data.enabled !== false, ...freq, ...hotkey, ...chatHotkey, ...pos };
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
export function loadMascotSettings(file = MASCOT_SETTINGS_FILE) {
|
|
98
|
+
try {
|
|
99
|
+
return normalizeMascotSettings(readMascotFile(file) || {});
|
|
100
|
+
} catch {
|
|
101
|
+
return { enabled: true };
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/**
|
|
106
|
+
* Đọc–sửa–ghi mascot.json, ghi nguyên tử (tệp tạm + rename: daemon, lệnh CLI, khay Aivin.exe cùng ghi tệp này). Tệp có mà hỏng → ném
|
|
107
|
+
* MascotSettingsUnreadable, KHÔNG ghi đè (trước đây đọc hỏng = `{ enabled: true }` rồi ghi đè mất vị trí / phím tắt / mức báo); nơi gọi bỏ
|
|
108
|
+
* qua, lượt lưu sau thử lại.
|
|
109
|
+
*/
|
|
110
|
+
export function saveMascotSettings(patch, file = MASCOT_SETTINGS_FILE) {
|
|
111
|
+
const next = { ...normalizeMascotSettings(readMascotFile(file) || {}), ...patch };
|
|
112
|
+
for (const [k, v] of Object.entries(next)) if (v === null || v === undefined) delete next[k];
|
|
113
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
114
|
+
const tmp = `${file}.${process.pid}.${Date.now()}.tmp`;
|
|
115
|
+
try {
|
|
116
|
+
fs.writeFileSync(tmp, JSON.stringify(next, null, 2) + '\n');
|
|
117
|
+
fs.renameSync(tmp, file);
|
|
118
|
+
} catch (e) {
|
|
119
|
+
try { fs.rmSync(tmp, { force: true }); } catch { /* đã dọn */ }
|
|
120
|
+
throw e;
|
|
121
|
+
}
|
|
122
|
+
return next;
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
/** host.ps1 = mã cửa sổ + ô hỏi (askHostSource.mjs) chèn tại dấu `# @ASK_HOOK`; thiếu dấu thì ô hỏi không có, cửa sổ vẫn chạy. */
|
|
126
|
+
export function hostScript() {
|
|
127
|
+
return MASCOT_PS1.includes(ASK_HOOK) ? MASCOT_PS1.replace(ASK_HOOK, ASK_PS1) : MASCOT_PS1;
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/** Tệp của cửa sổ: mã + ảnh theo dấu vân tay (đổi bản CLI → bộ mới, dọn bộ cũ); config.json (vị trí, chữ, màu) ghi mỗi lần mở. */
|
|
131
|
+
export function writeHostFiles({ dir, lang, settings }) {
|
|
132
|
+
const hostPs1 = hostScript();
|
|
133
|
+
const sha = createHash('sha256').update(hostPs1).update(MASCOT_XAML);
|
|
134
|
+
for (const body of Object.values(MASCOT_LAYERS)) sha.update(body);
|
|
135
|
+
const hash = sha.digest('hex').slice(0, 12);
|
|
136
|
+
const home = path.join(dir, hash);
|
|
137
|
+
fs.mkdirSync(home, { recursive: true });
|
|
138
|
+
const files = { 'host.ps1': hostPs1, 'mascot.xaml': MASCOT_XAML };
|
|
139
|
+
for (const [name, body] of Object.entries(files)) if (!fs.existsSync(path.join(home, name))) fs.writeFileSync(path.join(home, name), body);
|
|
140
|
+
for (const [name, body] of Object.entries(MASCOT_LAYERS)) if (!fs.existsSync(path.join(home, name))) fs.writeFileSync(path.join(home, name), Buffer.from(body, 'base64'));
|
|
141
|
+
if (!fs.existsSync(path.join(home, 'logo.png'))) fs.writeFileSync(path.join(home, 'logo.png'), Buffer.from(AIVIN_LOGO_PNG_BASE64, 'base64'));
|
|
142
|
+
fs.writeFileSync(path.join(home, 'config.json'), JSON.stringify({
|
|
143
|
+
strings: windowStrings(lang), palette: MASCOT_PALETTE, glyphs: MASCOT_GLYPHS, x: settings.x ?? null, y: settings.y ?? null, max_files: MAX_ATTACH,
|
|
144
|
+
notify_freq: settings.notify_freq ?? 1, hotkeys: hostHotkeys(settings.hotkey, settings.chat_hotkey),
|
|
145
|
+
}));
|
|
146
|
+
for (const name of fs.readdirSync(dir)) {
|
|
147
|
+
if (name !== hash && /^[0-9a-f]{12}$/.test(name)) fs.rmSync(path.join(dir, name), { recursive: true, force: true });
|
|
148
|
+
}
|
|
149
|
+
return home;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
const NOOP = Object.freeze({
|
|
153
|
+
connected() {}, disconnected() {}, paused() {}, remoteView() {}, callStarted() {}, callFinished() {}, waitingConfirm() {}, confirmDone() {}, chat() {}, close() {},
|
|
154
|
+
alert() {}, needsYou() {}, openAsk() {}, setNotifyFreq() {}, setLang() {}, get lang() { return 'en'; }, pid: () => null, enabled: false,
|
|
155
|
+
});
|
|
156
|
+
|
|
157
|
+
const hhmmss = (t) => new Date(t).toTimeString().slice(0, 8);
|
|
158
|
+
|
|
159
|
+
/** Cửa sổ chủ máy đang dùng khi hỏi bot (cửa sổ linh vật gửi kèm `ask` / `voice_start`): `{ window: '0x..', title, process }` hoặc null. */
|
|
160
|
+
export function userWindow(w) {
|
|
161
|
+
if (!w || typeof w !== 'object' || typeof w.window !== 'string' || !/^0x[0-9a-f]{1,16}$/.test(w.window)) return null;
|
|
162
|
+
const text = (v, max) => (typeof v === 'string' ? v.slice(0, max) : '');
|
|
163
|
+
return { window: w.window, title: text(w.title, 200), process: text(w.process, 64) };
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* `onPause` / `onResume`: nút trên bảng nhật ký bật / tắt công tắc ngắt (như `aivin remote pause|resume`). `onVoice(msg)`: sự kiện nói
|
|
168
|
+
* chuyện của cửa sổ (`voice_*`, xem ask.mjs); cửa sổ chết giữa chừng → `voice_stop`. `onChoose(id | ids)`: bấm nút trả lời câu Aivin hỏi (câu chọn nhiều: mảng id đã tích).
|
|
169
|
+
* `onCancel()`: bấm nút dừng lượt chat đang chạy. `onNewChat()`: nút "Phiên chat mới" trên bảng nhật ký. `onOpenTool(msg)`: bấm mở công cụ tương tác trong câu trả lời.
|
|
170
|
+
* `onAsk(text, window)`: câu gõ trong ô hỏi + cửa sổ chủ máy đang dùng (`userWindow`). `pid()`: tiến trình của cửa sổ linh vật (null khi
|
|
171
|
+
* chưa chạy). `spawnImpl`, `timers`, `now`, `dir`, `settingsFile`, các mốc `*Ms`: cho test.
|
|
172
|
+
*/
|
|
173
|
+
export function createMascot({
|
|
174
|
+
enabled = true, platform = process.platform, env = process.env, lang: preferredLang, onPause = () => {}, onResume = () => {}, say = () => {},
|
|
175
|
+
onAsk = () => {}, onVoice = () => {}, onChoose = () => {}, onCancel = () => {}, onNewChat = () => {}, onOpenTool = () => {}, onDrop = () => {}, onDetach = () => {}, onNotifyFreq = () => {},
|
|
176
|
+
spawnImpl = spawn, dir = MASCOT_DIR, settingsFile = MASCOT_SETTINGS_FILE, showFile = MASCOT_SHOW_FILE, hideFile = MASCOT_HIDE_FILE, voiceFile = MASCOT_VOICE_FILE, hotkeysFile = MASCOT_HOTKEYS_FILE, now = Date.now, timers = { setTimeout, clearTimeout },
|
|
177
|
+
thinkMs = THINK_MS, resultMs = RESULT_MS, mainThrottleMs = MAIN_THROTTLE_MS, restartDelaysMs = RESTART_DELAYS_MS, awayWaveMs = AWAY_WAVE_MS,
|
|
178
|
+
} = {}) {
|
|
179
|
+
if (!enabled || platform !== 'win32') return NOOP;
|
|
180
|
+
let currentLang = preferredLang ? mascotLang(env, platform, preferredLang) : mascotLang(env, platform);
|
|
181
|
+
const t = (key, vars) => mascotText(currentLang, key, vars);
|
|
182
|
+
|
|
183
|
+
let child = null;
|
|
184
|
+
let ready = false;
|
|
185
|
+
let closed = false;
|
|
186
|
+
// Linh vật đang tắt (`aivin remote mascot off` / nút "Tắt linh vật"): không mở cửa sổ, chỉ chờ `aivin ui` đánh thức.
|
|
187
|
+
let dormant = !loadMascotSettings(settingsFile).enabled;
|
|
188
|
+
// Lệnh chờ cửa sổ sẵn sàng sau khi được đánh thức: mở ô hỏi / bấm mic.
|
|
189
|
+
let commandOnReady = null;
|
|
190
|
+
let restarts = 0;
|
|
191
|
+
let restartTimer = null;
|
|
192
|
+
const pending = [];
|
|
193
|
+
let lastState = null;
|
|
194
|
+
let lastMain = null;
|
|
195
|
+
|
|
196
|
+
const write = (msg) => {
|
|
197
|
+
try { child?.stdin?.write(`${JSON.stringify(msg)}\n`); } catch { /* cửa sổ vừa chết — lần dựng lại gửi trạng thái mới nhất */ }
|
|
198
|
+
};
|
|
199
|
+
// Câu hỏi đang chờ (dòng câu hỏi + nút + ghim ô hỏi): cửa sổ dựng lại / chưa sẵn sàng vẫn hiện lại đúng câu hỏi để trả lời.
|
|
200
|
+
let lastQuestion = null;
|
|
201
|
+
let lastChoices = null;
|
|
202
|
+
let lastPin = null;
|
|
203
|
+
// Tệp thả vào bot đang chờ: cửa sổ dựng lại vẫn ôm thùng có số tệp.
|
|
204
|
+
let lastFiles = null;
|
|
205
|
+
// Đang nói chuyện bằng giọng (cửa sổ báo voice_start … voice_stop / daemon gửi voice_end): đổi ngôn ngữ chờ tới khi xong mới dựng lại.
|
|
206
|
+
let voiceOn = false;
|
|
207
|
+
let langRebuild = false;
|
|
208
|
+
// Đang dựng lại cửa sổ có chủ đích (đổi ngôn ngữ): cửa sổ cũ đóng thì mở ngay, không tính là lần chết / không giãn thời gian thử lại.
|
|
209
|
+
let rebuilding = false;
|
|
210
|
+
const send = (msg) => {
|
|
211
|
+
if (msg.t === HostCommand.STATE) lastState = msg;
|
|
212
|
+
if (msg.t === HostCommand.MAIN) lastMain = msg;
|
|
213
|
+
if (msg.t === AskCommand.CHAT && String(msg.id || '').startsWith(QUESTION_ROW)) lastQuestion = msg;
|
|
214
|
+
if (msg.t === AskCommand.CHOICES) lastChoices = msg;
|
|
215
|
+
if (msg.t === AskCommand.PIN) lastPin = msg;
|
|
216
|
+
if (msg.t === AskCommand.FILES) lastFiles = msg;
|
|
217
|
+
if (msg.t === VoiceCommand.END) { voiceOn = false; if (langRebuild) timers.setTimeout(rebuildForLang, 0); }
|
|
218
|
+
if (ready) return write(msg);
|
|
219
|
+
if (msg.t === HostCommand.LOG) {
|
|
220
|
+
pending.push(msg);
|
|
221
|
+
if (pending.length > QUEUE_LOGS) pending.shift();
|
|
222
|
+
}
|
|
223
|
+
queueChat(msg);
|
|
224
|
+
};
|
|
225
|
+
// Ô hỏi lúc cửa sổ chưa sẵn sàng (đang mở / dựng lại): giữ dòng chat (theo id — dòng chữ chạy cập nhật tại chỗ), trạng thái bận, dòng
|
|
226
|
+
// trạng thái mới nhất; trước 02/11/2026 bị bỏ hết → câu trả lời tới đúng lúc cửa sổ dựng lại thì mất.
|
|
227
|
+
const pendingChat = new Map();
|
|
228
|
+
let pendingBusy = null;
|
|
229
|
+
let pendingStatus = null;
|
|
230
|
+
let rowSeq = 0;
|
|
231
|
+
function queueChat(msg) {
|
|
232
|
+
if (msg.t === AskCommand.CLEAR) { pendingChat.clear(); pendingChat.set('\0clear', msg); return; }
|
|
233
|
+
if (msg.t === AskCommand.BUSY) { pendingBusy = msg; return; }
|
|
234
|
+
if (msg.t === AskCommand.STATUS) { pendingStatus = msg; return; }
|
|
235
|
+
if (msg.t !== AskCommand.CHAT) return;
|
|
236
|
+
const id = String(msg.id || '');
|
|
237
|
+
if (msg.remove) { if (pendingChat.has(id)) { pendingChat.delete(id); return; } }
|
|
238
|
+
pendingChat.set(id || `\0row${rowSeq++}`, msg);
|
|
239
|
+
while (pendingChat.size > QUEUE_LOGS) pendingChat.delete(pendingChat.keys().next().value);
|
|
240
|
+
}
|
|
241
|
+
const flush = () => {
|
|
242
|
+
for (const msg of pending.splice(0)) write(msg);
|
|
243
|
+
for (const msg of pendingChat.values()) write(msg);
|
|
244
|
+
pendingChat.clear();
|
|
245
|
+
if (pendingBusy) write(pendingBusy);
|
|
246
|
+
if (pendingStatus) write(pendingStatus);
|
|
247
|
+
pendingBusy = null;
|
|
248
|
+
pendingStatus = null;
|
|
249
|
+
if (lastState) write(lastState);
|
|
250
|
+
if (lastMain) write({ ...lastMain, quiet: true });
|
|
251
|
+
if (guiActive > 0) write({ t: HostCommand.GUI, active: true });
|
|
252
|
+
if (lastPin?.on) {
|
|
253
|
+
if (lastQuestion) write(lastQuestion);
|
|
254
|
+
if (lastChoices) write(lastChoices);
|
|
255
|
+
write(lastPin);
|
|
256
|
+
}
|
|
257
|
+
if (lastFiles?.n) write(lastFiles);
|
|
258
|
+
if (commandOnReady) { write({ t: commandOnReady }); commandOnReady = null; }
|
|
259
|
+
};
|
|
260
|
+
|
|
261
|
+
const onEvent = (msg) => {
|
|
262
|
+
if (msg.t === HostEvent.READY) { ready = true; restarts = 0; flush(); return; }
|
|
263
|
+
if (msg.t === HostEvent.POS && Number.isFinite(msg.x) && Number.isFinite(msg.y)) {
|
|
264
|
+
try { saveMascotSettings({ x: msg.x, y: msg.y }, settingsFile); } catch { /* không lưu được vị trí — lần sau về chỗ cũ */ }
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
if (msg.t === HostEvent.PAUSE) return onPause();
|
|
268
|
+
if (msg.t === HostEvent.RESUME) return onResume();
|
|
269
|
+
if (msg.t === HostEvent.HOTKEYS) return writeHotkeys(msg);
|
|
270
|
+
if (msg.t === HostEvent.HIDE) { hiddenUntilWork = true; return; }
|
|
271
|
+
// Ô hỏi: chủ máy gõ / nói với bot → daemon gửi lên Aivin (ask.mjs).
|
|
272
|
+
if (msg.t === HostEvent.ASK && typeof msg.text === 'string') return onAsk(msg.text, userWindow(msg.window));
|
|
273
|
+
if (msg.t === HostEvent.CHOOSE) {
|
|
274
|
+
// Câu chọn nhiều: `ids` = các mục đã tích; chọn một: `id`.
|
|
275
|
+
if (Array.isArray(msg.ids) && msg.ids.length && msg.ids.every((x) => typeof x === 'string')) return onChoose(msg.ids);
|
|
276
|
+
if (typeof msg.id === 'string') return onChoose(msg.id);
|
|
277
|
+
}
|
|
278
|
+
// Nút dừng (nút mic khi đang chờ lượt chat): dừng lượt đang chạy.
|
|
279
|
+
if (msg.t === HostEvent.CANCEL) return onCancel();
|
|
280
|
+
// Nút "Chat mới" trên bảng: phiên chat mới cho linh vật.
|
|
281
|
+
if (msg.t === HostEvent.NEW_CHAT) return onNewChat();
|
|
282
|
+
if (msg.t === HostEvent.OPEN_WEBVIEW) return onOpenTool(msg);
|
|
283
|
+
if (msg.t === HostEvent.NOTIFY_FREQ && Number.isFinite(msg.value)) {
|
|
284
|
+
const val = Number(msg.value);
|
|
285
|
+
if (val >= 0 && val <= 2) {
|
|
286
|
+
try { saveMascotSettings({ notify_freq: val }, settingsFile); } catch {}
|
|
287
|
+
onNotifyFreq(val);
|
|
288
|
+
}
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
if (msg.t === HostEvent.DROP && Array.isArray(msg.files)) return onDrop(msg.files.filter((f) => typeof f === 'string' && f));
|
|
292
|
+
if (msg.t === HostEvent.DETACH && typeof msg.path === 'string' && msg.path) return onDetach(msg.path);
|
|
293
|
+
if (msg.t === HostEvent.AWAY) { away = { since: now(), done: 0, failed: 0, needs: 0 }; return; }
|
|
294
|
+
if (msg.t === HostEvent.BACK) return welcomeBack();
|
|
295
|
+
if (msg.t === HostEvent.VOICE_START) { voiceOn = true; return onVoice({ t: msg.t, window: userWindow(msg.window) }); }
|
|
296
|
+
if (msg.t === HostEvent.VOICE_STOP || msg.t === HostEvent.VOICE_MIC_LOST) {
|
|
297
|
+
voiceOn = false;
|
|
298
|
+
onVoice(msg);
|
|
299
|
+
return rebuildForLang();
|
|
300
|
+
}
|
|
301
|
+
if (VOICE_EVENTS.has(msg.t)) return onVoice(msg);
|
|
302
|
+
if (msg.t === HostEvent.OFF) {
|
|
303
|
+
try { saveMascotSettings({ enabled: false }, settingsFile); } catch { /* tắt trong phiên này vẫn được */ }
|
|
304
|
+
say(t(MascotText.TURNED_OFF));
|
|
305
|
+
sleep();
|
|
306
|
+
}
|
|
307
|
+
};
|
|
308
|
+
|
|
309
|
+
/** Tắt cửa sổ nhưng daemon vẫn giữ trạng thái — `aivin ui` đánh thức lại được. */
|
|
310
|
+
function sleep() {
|
|
311
|
+
dormant = true;
|
|
312
|
+
timers.clearTimeout(restartTimer);
|
|
313
|
+
quitHost();
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/** Dựng lại cửa sổ theo ngôn ngữ mới khi rảnh (không nói chuyện); chưa có cửa sổ / đang tắt → lần mở kế tiếp tự dùng chữ mới. */
|
|
317
|
+
function rebuildForLang() {
|
|
318
|
+
if (!langRebuild || voiceOn || closed) return;
|
|
319
|
+
langRebuild = false;
|
|
320
|
+
if (!child || dormant) return;
|
|
321
|
+
rebuilding = true;
|
|
322
|
+
quitHost(300);
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
function quitHost(killAfterMs = 1500) {
|
|
326
|
+
const c = child;
|
|
327
|
+
if (!c) return;
|
|
328
|
+
write({ t: HostCommand.QUIT });
|
|
329
|
+
try { c.stdin?.end(); } catch { /* đã đóng */ }
|
|
330
|
+
const kill = timers.setTimeout(() => { try { c.kill(); } catch { /* đã thoát */ } }, killAfterMs);
|
|
331
|
+
kill?.unref?.();
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
function writeHotkeys({ chat, voice }) {
|
|
335
|
+
const labels = { ...(typeof chat === 'string' && chat ? { chat } : {}), ...(typeof voice === 'string' && voice ? { voice } : {}) };
|
|
336
|
+
try { fs.writeFileSync(hotkeysFile, JSON.stringify(labels)); } catch { /* khay chỉ không hiện phím tắt */ }
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
/**
|
|
340
|
+
* `aivin ui` / khay: bật lại nếu đang tắt, hiện linh vật (kể cả đang "ẩn tới khi có việc"), rồi `command`: mở ô hỏi để gõ ngay (mặc định)
|
|
341
|
+
* hoặc bấm mic (Quick voice).
|
|
342
|
+
*/
|
|
343
|
+
function wake(command = HostCommand.OPEN_ASK) {
|
|
344
|
+
if (closed) return;
|
|
345
|
+
hiddenUntilWork = false;
|
|
346
|
+
try { saveMascotSettings({ enabled: true }, settingsFile); } catch {}
|
|
347
|
+
if (dormant || !child) {
|
|
348
|
+
dormant = false;
|
|
349
|
+
restarts = 0;
|
|
350
|
+
commandOnReady = command;
|
|
351
|
+
return start();
|
|
352
|
+
}
|
|
353
|
+
if (!ready) { commandOnReady = command; return; }
|
|
354
|
+
write({ t: HostCommand.SHOW });
|
|
355
|
+
write({ t: command });
|
|
356
|
+
}
|
|
357
|
+
|
|
358
|
+
// Yêu cầu hiện/ẩn linh vật từ khay hệ thống hoặc lệnh `aivin ui`: tệp đánh dấu đổi giờ sửa.
|
|
359
|
+
// Tệp đánh dấu còn lại từ lần bật trước (không bao giờ bị xoá) không được bật lại linh vật mỗi lần daemon khởi động dù chủ máy đã tắt —
|
|
360
|
+
// chỉ yêu cầu mới trong khoảng ân hạn (vd `aivin ui` vừa chạy, daemon đang lên) mới tính, như tệp ẩn (02/11/2026).
|
|
361
|
+
let showSeenAt = now() - SHOW_REQUEST_GRACE_MS;
|
|
362
|
+
let hideSeenAt = now() - SHOW_REQUEST_GRACE_MS;
|
|
363
|
+
const voiceSeenAt = now() - SHOW_REQUEST_GRACE_MS;
|
|
364
|
+
const showWatch = setInterval(() => {
|
|
365
|
+
try {
|
|
366
|
+
const showAt = fs.statSync(showFile).mtimeMs;
|
|
367
|
+
if (showAt > showSeenAt) {
|
|
368
|
+
showSeenAt = showAt;
|
|
369
|
+
wake();
|
|
370
|
+
}
|
|
371
|
+
} catch {}
|
|
372
|
+
try {
|
|
373
|
+
const hideAt = fs.statSync(hideFile).mtimeMs;
|
|
374
|
+
if (hideAt > hideSeenAt) {
|
|
375
|
+
hideSeenAt = hideAt;
|
|
376
|
+
try { saveMascotSettings({ enabled: false }, settingsFile); } catch {}
|
|
377
|
+
sleep();
|
|
378
|
+
}
|
|
379
|
+
} catch {}
|
|
380
|
+
try {
|
|
381
|
+
const voiceAt = fs.statSync(voiceFile).mtimeMs;
|
|
382
|
+
fs.rmSync(voiceFile, { force: true });
|
|
383
|
+
if (voiceAt > voiceSeenAt) wake(HostCommand.VOICE_TOGGLE);
|
|
384
|
+
} catch {}
|
|
385
|
+
}, SHOW_POLL_MS);
|
|
386
|
+
showWatch.unref?.();
|
|
387
|
+
|
|
388
|
+
function start() {
|
|
389
|
+
if (closed || dormant || child) return;
|
|
390
|
+
let home;
|
|
391
|
+
try {
|
|
392
|
+
home = writeHostFiles({ dir, lang: currentLang, settings: loadMascotSettings(settingsFile) });
|
|
393
|
+
} catch {
|
|
394
|
+
return;
|
|
395
|
+
}
|
|
396
|
+
let c;
|
|
397
|
+
try {
|
|
398
|
+
c = spawnImpl('powershell.exe', ['-NoProfile', '-NonInteractive', '-STA', '-WindowStyle', 'Hidden', '-ExecutionPolicy', 'Bypass', '-File', path.join(home, 'host.ps1')], {
|
|
399
|
+
env: { ...env, AIVIN_MASCOT_DIR: home }, stdio: ['pipe', 'pipe', 'pipe'], windowsHide: true,
|
|
400
|
+
});
|
|
401
|
+
} catch {
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
child = c;
|
|
405
|
+
ready = false;
|
|
406
|
+
let stderr = '';
|
|
407
|
+
// Chuỗi (không phải Buffer) theo UTF-8: ký tự nhiều byte bị cắt giữa hai mẩu không vỡ thành "�".
|
|
408
|
+
c.stderr?.setEncoding?.('utf8');
|
|
409
|
+
c.stderr?.on('data', (d) => { stderr = (stderr + d).slice(-2000); });
|
|
410
|
+
c.stdin?.on('error', () => { /* cửa sổ đã đóng */ });
|
|
411
|
+
readline.createInterface({ input: c.stdout }).on('line', (line) => {
|
|
412
|
+
try { onEvent(JSON.parse(line)); } catch { /* dòng lạ */ }
|
|
413
|
+
});
|
|
414
|
+
c.on('error', () => { /* xử lý ở close */ });
|
|
415
|
+
c.on('close', () => {
|
|
416
|
+
if (child === c) { child = null; ready = false; }
|
|
417
|
+
try { fs.rmSync(hotkeysFile, { force: true }); } catch { /* khay vẫn kiểm tra daemon + linh vật đang bật */ }
|
|
418
|
+
voiceOn = false;
|
|
419
|
+
onVoice({ t: HostEvent.VOICE_STOP });
|
|
420
|
+
if (closed || dormant) return;
|
|
421
|
+
if (rebuilding) { rebuilding = false; return start(); }
|
|
422
|
+
// Không có màn hình (phiên dịch vụ), WPF hỏng… → thử lại giãn dần, quá số lần thì thôi (daemon vẫn chạy bình thường).
|
|
423
|
+
const delay = restartDelaysMs[restarts++];
|
|
424
|
+
if (delay === undefined) { say(`(mascot: ${stderr.trim().split(/\r?\n/).pop() || 'window could not start'})`); return; }
|
|
425
|
+
restartTimer = timers.setTimeout(start, delay);
|
|
426
|
+
});
|
|
427
|
+
}
|
|
428
|
+
|
|
429
|
+
function close() {
|
|
430
|
+
if (closed) return;
|
|
431
|
+
closed = true;
|
|
432
|
+
clearInterval(showWatch);
|
|
433
|
+
timers.clearTimeout(restartTimer);
|
|
434
|
+
timers.clearTimeout(thinkTimer);
|
|
435
|
+
timers.clearTimeout(resultTimer);
|
|
436
|
+
timers.clearTimeout(mainTimer);
|
|
437
|
+
quitHost();
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
// --- Trạng thái ---------------------------------------------------------------------------------------------------------------------
|
|
441
|
+
const active = new Map();
|
|
442
|
+
const waiting = new Set();
|
|
443
|
+
let guiActive = 0;
|
|
444
|
+
let paused = false;
|
|
445
|
+
let offline = false;
|
|
446
|
+
let phase = MascotState.IDLE;
|
|
447
|
+
let batchOk = 0;
|
|
448
|
+
let batchFailed = null;
|
|
449
|
+
let thinkTimer = null;
|
|
450
|
+
let resultTimer = null;
|
|
451
|
+
let hiddenUntilWork = false;
|
|
452
|
+
/** Aivin đang hỏi chủ máy (câu hỏi chờ trả lời trong ô hỏi) — như chờ xác nhận: "!" tới khi trả lời. */
|
|
453
|
+
let askingYou = false;
|
|
454
|
+
/** Chủ máy đi vắng (cửa sổ báo không chạm chuột / phím một lúc): mốc + đếm việc xảy ra trong lúc đó, hoặc null. */
|
|
455
|
+
let away = null;
|
|
456
|
+
|
|
457
|
+
/** Quay lại sau khi vắng: có việc xảy ra → vẫy chào + bong bóng tóm tắt; vắng lâu mà không có gì → chỉ vẫy chào. */
|
|
458
|
+
function welcomeBack() {
|
|
459
|
+
const was = away;
|
|
460
|
+
away = null;
|
|
461
|
+
if (!was) return;
|
|
462
|
+
const parts = [
|
|
463
|
+
was.done && t(MascotText.AWAY_DONE, { n: was.done }),
|
|
464
|
+
was.failed && t(MascotText.AWAY_FAILED, { n: was.failed }),
|
|
465
|
+
was.needs && t(MascotText.AWAY_NEEDS, { n: was.needs }),
|
|
466
|
+
].filter(Boolean);
|
|
467
|
+
if (!parts.length && now() - was.since < awayWaveMs) return;
|
|
468
|
+
if (hiddenUntilWork) { hiddenUntilWork = false; send({ t: HostCommand.SHOW }); }
|
|
469
|
+
send({ t: HostCommand.GESTURE, g: 'wave' });
|
|
470
|
+
if (parts.length) main(t(MascotText.AWAY_SUMMARY, { parts: parts.join(', ') }));
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
const current = () => {
|
|
474
|
+
if (paused) return MascotState.PAUSED;
|
|
475
|
+
if (offline) return MascotState.OFFLINE;
|
|
476
|
+
if (waiting.size || askingYou) return MascotState.WAITING;
|
|
477
|
+
if (active.size) return MascotState.WORKING;
|
|
478
|
+
return phase;
|
|
479
|
+
};
|
|
480
|
+
let shownState = null;
|
|
481
|
+
const syncState = () => {
|
|
482
|
+
const s = current();
|
|
483
|
+
if (s === shownState) return;
|
|
484
|
+
shownState = s;
|
|
485
|
+
send({ t: HostCommand.STATE, state: s });
|
|
486
|
+
};
|
|
487
|
+
|
|
488
|
+
let mainTimer = null;
|
|
489
|
+
let mainNext = null;
|
|
490
|
+
let mainAt = 0;
|
|
491
|
+
const main = (text, url = null) => {
|
|
492
|
+
mainNext = { text, url };
|
|
493
|
+
const wait = mainThrottleMs - (now() - mainAt);
|
|
494
|
+
if (wait > 0) {
|
|
495
|
+
if (!mainTimer) mainTimer = timers.setTimeout(() => { mainTimer = null; main(mainNext.text, mainNext.url); }, wait);
|
|
496
|
+
return;
|
|
497
|
+
}
|
|
498
|
+
mainAt = now();
|
|
499
|
+
send({ t: HostCommand.MAIN, text, ...(url ? { url } : {}) });
|
|
500
|
+
};
|
|
501
|
+
const log = (entry) => send({ t: HostCommand.LOG, time: hhmmss(now()), ...entry });
|
|
502
|
+
|
|
503
|
+
const settle = () => {
|
|
504
|
+
timers.clearTimeout(thinkTimer);
|
|
505
|
+
timers.clearTimeout(resultTimer);
|
|
506
|
+
if (active.size || waiting.size) return;
|
|
507
|
+
// Hết lô bước: BE thường gửi lô kế trong vài giây (lượt Planner) — "đang nghĩ", chưa báo xong.
|
|
508
|
+
phase = MascotState.THINKING;
|
|
509
|
+
syncState();
|
|
510
|
+
main(t(MascotText.THINKING));
|
|
511
|
+
thinkTimer = timers.setTimeout(() => {
|
|
512
|
+
phase = batchFailed ? MascotState.ERROR : MascotState.DONE;
|
|
513
|
+
main(batchFailed ? t(MascotText.FAILED, { title: batchFailed }) : batchOk > 1 ? t(MascotText.DONE_MANY, { count: batchOk }) : t(MascotText.DONE_ONE));
|
|
514
|
+
batchOk = 0;
|
|
515
|
+
batchFailed = null;
|
|
516
|
+
syncState();
|
|
517
|
+
// Về chờ việc: mục "đang làm" của bảng nhật ký không giữ kết quả cũ (kết quả vẫn còn trong nhật ký); không bật bong bóng.
|
|
518
|
+
resultTimer = timers.setTimeout(() => {
|
|
519
|
+
phase = MascotState.IDLE;
|
|
520
|
+
syncState();
|
|
521
|
+
send({ t: HostCommand.MAIN, text: t(MascotText.READY), quiet: true });
|
|
522
|
+
}, resultMs);
|
|
523
|
+
}, thinkMs);
|
|
524
|
+
};
|
|
525
|
+
|
|
526
|
+
start();
|
|
527
|
+
|
|
528
|
+
return {
|
|
529
|
+
enabled: true,
|
|
530
|
+
get lang() { return currentLang; },
|
|
531
|
+
/** Lệnh của ô hỏi (ask.mjs: chat / chat_busy / ask_status) → cửa sổ. */
|
|
532
|
+
chat(cmd) { send(cmd); },
|
|
533
|
+
connected() {
|
|
534
|
+
offline = false;
|
|
535
|
+
syncState();
|
|
536
|
+
log({ status: LogStatus.INFO, title: t(MascotText.CONNECTED) });
|
|
537
|
+
// Không bật bong bóng khi vừa nối (người dùng thấy thừa) — chỉ đặt lại mục "Đang làm" của bảng nhật ký.
|
|
538
|
+
send({ t: HostCommand.MAIN, text: t(MascotText.READY), quiet: true });
|
|
539
|
+
},
|
|
540
|
+
disconnected() {
|
|
541
|
+
if (offline) return;
|
|
542
|
+
offline = true;
|
|
543
|
+
syncState();
|
|
544
|
+
log({ status: LogStatus.WARN, title: t(MascotText.DISCONNECTED) });
|
|
545
|
+
main(t(MascotText.DISCONNECTED));
|
|
546
|
+
},
|
|
547
|
+
paused(on) {
|
|
548
|
+
if (paused === on) return;
|
|
549
|
+
paused = on;
|
|
550
|
+
syncState();
|
|
551
|
+
const text = t(on ? MascotText.PAUSED : MascotText.RESUMED);
|
|
552
|
+
log({ status: on ? LogStatus.WARN : LogStatus.INFO, title: text });
|
|
553
|
+
main(text);
|
|
554
|
+
},
|
|
555
|
+
/** Có người đang xem + điều khiển màn hình máy này từ web (Desktop Scenecast) — chủ máy luôn biết. */
|
|
556
|
+
remoteView(on) {
|
|
557
|
+
const text = t(on ? MascotText.CAST_VIEWING : MascotText.CAST_ENDED);
|
|
558
|
+
log({ status: on ? LogStatus.WARN : LogStatus.INFO, title: text });
|
|
559
|
+
main(text);
|
|
560
|
+
},
|
|
561
|
+
callStarted(call, tool) {
|
|
562
|
+
if (!call?.call_id || tool?.internal) return;
|
|
563
|
+
const { title, detail } = describeStep({ call, tool, lang: currentLang });
|
|
564
|
+
active.set(call.call_id, { title, detail, gui: tool?.group === ToolGroup.GUI, at: now() });
|
|
565
|
+
timers.clearTimeout(thinkTimer);
|
|
566
|
+
timers.clearTimeout(resultTimer);
|
|
567
|
+
phase = MascotState.WORKING;
|
|
568
|
+
// AI sắp bấm / chụp cửa sổ: linh vật tránh đường (không che, không hứng cú bấm).
|
|
569
|
+
if (tool?.group === ToolGroup.GUI && guiActive++ === 0) send({ t: HostCommand.GUI, active: true });
|
|
570
|
+
if (hiddenUntilWork) { hiddenUntilWork = false; send({ t: HostCommand.SHOW }); }
|
|
571
|
+
syncState();
|
|
572
|
+
main(title);
|
|
573
|
+
log({ id: call.call_id, status: LogStatus.RUN, title, sub: detail });
|
|
574
|
+
},
|
|
575
|
+
callFinished(call, tool, outcome) {
|
|
576
|
+
const entry = active.get(call?.call_id);
|
|
577
|
+
if (!entry) return;
|
|
578
|
+
active.delete(call.call_id);
|
|
579
|
+
if (entry.gui && --guiActive === 0) send({ t: HostCommand.GUI, active: false });
|
|
580
|
+
const ms = Number(outcome?.duration_ms) || now() - entry.at;
|
|
581
|
+
const took = ms >= 10_000 ? t(MascotText.SECONDS, { n: Math.round(ms / 1000) }) : t(MascotText.MS, { n: ms });
|
|
582
|
+
if (outcome?.ok) batchOk++;
|
|
583
|
+
else batchFailed = entry.title;
|
|
584
|
+
log({ id: call.call_id, status: outcome?.ok ? LogStatus.OK : LogStatus.FAIL, sub: outcome?.ok ? `${entry.detail} · ${took}` : String(outcome?.error || '').slice(0, 300) });
|
|
585
|
+
settle();
|
|
586
|
+
},
|
|
587
|
+
waitingConfirm(call, tool) {
|
|
588
|
+
if (!call?.call_id) return;
|
|
589
|
+
const { title } = describeStep({ call, tool, lang: currentLang });
|
|
590
|
+
waiting.add(call.call_id);
|
|
591
|
+
syncState();
|
|
592
|
+
main(t(MascotText.WAITING_CONFIRM, { title }));
|
|
593
|
+
},
|
|
594
|
+
confirmDone(call, allowed) {
|
|
595
|
+
if (!waiting.delete(call?.call_id)) return;
|
|
596
|
+
log({ status: allowed ? LogStatus.INFO : LogStatus.WARN, title: t(allowed ? MascotText.CONFIRM_ALLOWED : MascotText.CONFIRM_REJECTED) });
|
|
597
|
+
syncState();
|
|
598
|
+
if (!allowed) settle();
|
|
599
|
+
},
|
|
600
|
+
/**
|
|
601
|
+
* Báo chủ động / câu trả lời của ô hỏi (ask.mjs `onAlert`): bong bóng ngắn + nét mặt — xong (nhảy, lấp lánh) / lỗi (lắc đầu) rồi về
|
|
602
|
+
* chờ việc; cần bạn thì trạng thái do `needsYou` giữ. Đang có bước chạy trên máy thì chỉ hiện bong bóng, không đổi trạng thái.
|
|
603
|
+
* Emoji cảm xúc trong câu (mood.mjs) → thêm cử chỉ + nét mặt; buồn / ngượng thì không nhảy mừng "xong", về thẳng chờ việc. Báo lỗi
|
|
604
|
+
* đã có nét mặt riêng (lắc đầu) nên không xét emoji.
|
|
605
|
+
*/
|
|
606
|
+
alert({ kind, text, url: rawUrl } = {}) {
|
|
607
|
+
if (!text) return;
|
|
608
|
+
// Cửa sổ mở link bằng Process.Start khi bấm bong bóng / dòng nhật ký: chỉ http(s).
|
|
609
|
+
const url = safeWebUrl(rawUrl);
|
|
610
|
+
if (hiddenUntilWork) { hiddenUntilWork = false; send({ t: HostCommand.SHOW }); }
|
|
611
|
+
// Khách cần nhân viên không phải việc AI làm trên máy: chỉ hiện chữ, không báo "xong", không nét mặt theo emoji trong lời khách.
|
|
612
|
+
if (kind === NotifyKind.CUSTOMER) {
|
|
613
|
+
log({ status: LogStatus.WARN, title: text, ...(url ? { url } : {}) });
|
|
614
|
+
return main(text, url);
|
|
615
|
+
}
|
|
616
|
+
const failed = kind === NotifyKind.FAILED;
|
|
617
|
+
const mood = failed ? null : moodOf(text);
|
|
618
|
+
const react = () => { if (mood) send({ t: HostCommand.GESTURE, ...MOOD_GESTURE[mood] }); };
|
|
619
|
+
if (away) away[failed ? 'failed' : kind === NotifyKind.NEEDS_YOU ? 'needs' : 'done']++;
|
|
620
|
+
log({ status: failed ? LogStatus.FAIL : kind === NotifyKind.NEEDS_YOU ? LogStatus.WARN : LogStatus.OK, title: text, ...(url ? { url } : {}) });
|
|
621
|
+
main(text, url);
|
|
622
|
+
if (kind === NotifyKind.NEEDS_YOU || active.size || waiting.size) return react();
|
|
623
|
+
timers.clearTimeout(thinkTimer);
|
|
624
|
+
timers.clearTimeout(resultTimer);
|
|
625
|
+
if (SUBDUED_MOODS.has(mood)) {
|
|
626
|
+
phase = MascotState.IDLE;
|
|
627
|
+
syncState();
|
|
628
|
+
return react();
|
|
629
|
+
}
|
|
630
|
+
phase = failed ? MascotState.ERROR : MascotState.DONE;
|
|
631
|
+
syncState();
|
|
632
|
+
react();
|
|
633
|
+
resultTimer = timers.setTimeout(() => {
|
|
634
|
+
phase = MascotState.IDLE;
|
|
635
|
+
syncState();
|
|
636
|
+
send({ t: HostCommand.MAIN, text: t(MascotText.READY), quiet: true });
|
|
637
|
+
}, resultMs);
|
|
638
|
+
},
|
|
639
|
+
/** Có / hết câu hỏi Aivin đang chờ chủ máy trả lời (ask.mjs `onPending`). */
|
|
640
|
+
needsYou(on) {
|
|
641
|
+
if (askingYou === !!on) return;
|
|
642
|
+
askingYou = !!on;
|
|
643
|
+
syncState();
|
|
644
|
+
},
|
|
645
|
+
/** Hiện linh vật + mở ô hỏi để gõ ngay (như `aivin ui`) — cho phím tắt / khay hệ thống; câu hỏi đang chờ (nếu có) đã nằm sẵn trong ô. */
|
|
646
|
+
openAsk: () => wake(),
|
|
647
|
+
setNotifyFreq: (val) => send({ t: HostCommand.NOTIFY_FREQ, value: Number(val) }),
|
|
648
|
+
/**
|
|
649
|
+
* Ngôn ngữ người dùng trên Aivin (HELLO) khác ngôn ngữ đang hiện: chữ trên cửa sổ nằm trong config.json → phải dựng lại cửa sổ. Cùng
|
|
650
|
+
* ngôn ngữ → không làm gì; đang nói chuyện bằng giọng → chờ tới khi xong (02/11/2026: trước đây kill cửa sổ ngay mỗi lần nối lại).
|
|
651
|
+
*/
|
|
652
|
+
setLang(nextLang) {
|
|
653
|
+
if (!nextLang) return;
|
|
654
|
+
const resolved = mascotLang(env, platform, nextLang);
|
|
655
|
+
if (resolved === currentLang) return;
|
|
656
|
+
currentLang = resolved;
|
|
657
|
+
langRebuild = true;
|
|
658
|
+
rebuildForLang();
|
|
659
|
+
},
|
|
660
|
+
pid: () => child?.pid ?? null,
|
|
661
|
+
close,
|
|
662
|
+
};
|
|
663
|
+
}
|