@aivin-labs/cli 1.0.11 → 1.0.13
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 +16 -0
- package/bin/cli.mjs +67 -0
- package/bin/lib/remote/browserTunnel.mjs +47 -8
- package/bin/lib/remote/callLedger.mjs +73 -14
- package/bin/lib/remote/client.mjs +89 -8
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/constants.mjs +17 -0
- package/bin/lib/remote/dailyBrowser.mjs +8 -2
- package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
- package/bin/lib/remote/desktop/index.mjs +44 -7
- package/bin/lib/remote/desktop/linux.mjs +1 -1
- package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -427
- package/bin/lib/remote/desktop/mac.mjs +2 -2
- package/bin/lib/remote/desktop/macTraySource.mjs +295 -292
- package/bin/lib/remote/desktop/traySource.mjs +541 -527
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +85 -0
- package/bin/lib/remote/fileIndexer.mjs +757 -399
- package/bin/lib/remote/folderRules.mjs +140 -0
- package/bin/lib/remote/gui/index.mjs +126 -17
- package/bin/lib/remote/gui/windowsHost.mjs +9 -2
- package/bin/lib/remote/gui/windowsHostSource.mjs +194 -51
- package/bin/lib/remote/idempotency.mjs +49 -20
- package/bin/lib/remote/localPolicy.mjs +8 -2
- package/bin/lib/remote/mascot/askHostSource.mjs +18 -0
- package/bin/lib/remote/mascot/bot.mjs +29 -4
- package/bin/lib/remote/mascot/hostSource.mjs +4 -4
- package/bin/lib/remote/mascot/rigSource.mjs +12 -7
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/toolHandlers.mjs +788 -741
- package/bin/lib/remoteControl.mjs +26 -26
- package/docs/AIVIN_MASCOT.md +14 -0
- package/docs/CLI.md +1504 -1484
- 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 +71 -71
- package/docs/media/aivin-mascot-states.mp4 +0 -0
|
@@ -1,741 +1,788 @@
|
|
|
1
|
-
import fs from 'fs';
|
|
2
|
-
import os from 'os';
|
|
3
|
-
import path from 'path';
|
|
4
|
-
import readline from 'readline';
|
|
5
|
-
import { spawn } from 'child_process';
|
|
6
|
-
import { DeviceErrorCode, IGNORED_DIRS, MemoryKind, ToolGroup } from './constants.mjs';
|
|
7
|
-
import {
|
|
8
|
-
DeviceToolError, assertCommandAllowed, containsProtectedPath, displayPath, isProtectedPath, isRootPath, protectedDirNamesUnder,
|
|
9
|
-
resolveEntryInRoots, resolveInRoots, scrubEnv,
|
|
10
|
-
} from './sandbox.mjs';
|
|
11
|
-
import { deleteMemoryItems, getMemoryItem, listMemoryItems, putMemoryItems, searchMemory } from './deviceMemory.mjs';
|
|
12
|
-
import { extractDocText, isDocFile } from './docText.mjs';
|
|
13
|
-
import {
|
|
14
|
-
import {
|
|
15
|
-
import {
|
|
16
|
-
import {
|
|
17
|
-
import {
|
|
18
|
-
import {
|
|
19
|
-
import {
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
import {
|
|
26
|
-
import {
|
|
27
|
-
import {
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
*
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
*
|
|
36
|
-
*
|
|
37
|
-
*
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
const
|
|
44
|
-
|
|
45
|
-
const
|
|
46
|
-
const
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
const
|
|
50
|
-
|
|
51
|
-
const
|
|
52
|
-
|
|
53
|
-
const
|
|
54
|
-
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
}
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
}
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
const
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
let
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
if (
|
|
95
|
-
|
|
96
|
-
if (
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
if (
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
}
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
const
|
|
129
|
-
const
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
}
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
const
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
}
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
if (
|
|
154
|
-
|
|
155
|
-
}
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
}
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
const
|
|
172
|
-
const
|
|
173
|
-
const
|
|
174
|
-
const
|
|
175
|
-
const
|
|
176
|
-
const
|
|
177
|
-
const
|
|
178
|
-
const
|
|
179
|
-
const
|
|
180
|
-
|
|
181
|
-
const
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
const
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
if (
|
|
200
|
-
if (
|
|
201
|
-
|
|
202
|
-
if (
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
if (!
|
|
207
|
-
if (
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
item.
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
const
|
|
233
|
-
const
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
const
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
return
|
|
256
|
-
}
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
}
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
const
|
|
353
|
-
const
|
|
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
|
-
const
|
|
397
|
-
const
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
await
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
|
|
417
|
-
|
|
418
|
-
|
|
419
|
-
|
|
420
|
-
|
|
421
|
-
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
}
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
}
|
|
436
|
-
|
|
437
|
-
async function
|
|
438
|
-
const
|
|
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
|
-
return {
|
|
479
|
-
}
|
|
480
|
-
|
|
481
|
-
async function
|
|
482
|
-
const undo = undoOf(args, env, '
|
|
483
|
-
try { return await
|
|
484
|
-
}
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
}
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
}
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
} finally { undo?.commit(); }
|
|
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
|
-
const
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
const
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
const
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
description: '
|
|
662
|
-
input_schema: schema({
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
{ name: '
|
|
690
|
-
description: '
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
{
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import readline from 'readline';
|
|
5
|
+
import { spawn } from 'child_process';
|
|
6
|
+
import { DeviceErrorCode, IGNORED_DIRS, MemoryKind, ToolGroup } from './constants.mjs';
|
|
7
|
+
import {
|
|
8
|
+
DeviceToolError, assertCommandAllowed, containsProtectedPath, displayPath, isProtectedPath, isRootPath, protectedDirNamesUnder,
|
|
9
|
+
resolveEntryInRoots, resolveInRoots, scrubEnv,
|
|
10
|
+
} from './sandbox.mjs';
|
|
11
|
+
import { deleteMemoryItems, getMemoryItem, listMemoryItems, putMemoryItems, searchMemory } from './deviceMemory.mjs';
|
|
12
|
+
import { extractDocText, isDocFile } from './docText.mjs';
|
|
13
|
+
import { osFileSearch } from './osSearch.mjs';
|
|
14
|
+
import { tokenize } from './textIndex.mjs';
|
|
15
|
+
import { showOSNotification } from './notify.mjs';
|
|
16
|
+
import { accountEnv, withProcessCap } from './multiUser.mjs';
|
|
17
|
+
import { buildGuiTools } from './gui/index.mjs';
|
|
18
|
+
import { buildOfficeTools } from './office/index.mjs';
|
|
19
|
+
import { measurePath } from './undoStore.mjs';
|
|
20
|
+
import { buildProcessTools, shellCommand } from './processes.mjs';
|
|
21
|
+
import { buildAgentTools, createAgentRunner } from './codingAgents.mjs';
|
|
22
|
+
|
|
23
|
+
/** Một bộ chạy agent lập trình cho cả tiến trình (việc đang chạy sống qua các lần dựng lại danh mục công cụ). */
|
|
24
|
+
let sharedAgents = null;
|
|
25
|
+
import { buildScheduleTools } from './schedule.mjs';
|
|
26
|
+
import { buildWatchTools } from './deviceWatches.mjs';
|
|
27
|
+
import { buildTransferTools } from './httpTransfer.mjs';
|
|
28
|
+
import { buildMeetingTools } from './meeting/index.mjs';
|
|
29
|
+
import { buildClipboardTools } from './clipboard.mjs';
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Công cụ trên máy, chia gói theo năng lực phát hiện được (git chỉ có khi máy cài git, tìm nội dung dùng ripgrep nếu có…). Mỗi công cụ
|
|
33
|
+
* tự khai: schema tham số, chỉ đọc / có tác dụng phụ / không hoàn tác, nhóm song song, khoá đường dẫn khi ghi. Công cụ `internal` chỉ BE
|
|
34
|
+
* gọi trực tiếp (tra ngữ cảnh, lưu ghi nhớ) — không đưa vào danh mục của Planner.
|
|
35
|
+
*
|
|
36
|
+
* `env` = { roots, binaries, fileIndex, projects, runAs?, memory?, browserTunnels?, gui?, office?, undo?, transfer? }. `undo` (kho hoàn tác, undoStore.mjs)
|
|
37
|
+
* vắng (máy tính tổ chức — công cụ tệp chạy dưới tài khoản thành viên) thì ghi / xoá như cũ, không lấy lại được. `ctx` = { signal, onOutput, timeoutMs }. Máy tính tổ chức
|
|
38
|
+
* (`--multi-user`): mỗi lời gọi một `env` riêng của thành viên — `runAs` (tài khoản Linux chạy lệnh), `memory` (bộ nhớ của vùng), xem
|
|
39
|
+
* multiUser.mjs.
|
|
40
|
+
*/
|
|
41
|
+
|
|
42
|
+
const DEFAULT_MEMORY = { search: searchMemory, get: getMemoryItem, list: listMemoryItems, delete: deleteMemoryItems, put: putMemoryItems };
|
|
43
|
+
const memoryOf = (env) => env?.memory || DEFAULT_MEMORY;
|
|
44
|
+
|
|
45
|
+
const DEFAULT_READ_LINES = 1000;
|
|
46
|
+
const MAX_READ_LINES = 5000;
|
|
47
|
+
const MAX_READ_BYTES = 1024 * 1024;
|
|
48
|
+
const MAX_EXEC_OUTPUT = 2 * 1024 * 1024;
|
|
49
|
+
const MAX_LIST_ENTRIES = 2000;
|
|
50
|
+
/** Trần một lần thao tác hàng loạt (fs.move_many / fs.delete_many). */
|
|
51
|
+
const MAX_BATCH_ITEMS = 1000;
|
|
52
|
+
const BATCH_CONCURRENCY = 8;
|
|
53
|
+
const GREP_CONCURRENCY = 16;
|
|
54
|
+
|
|
55
|
+
const str = (description) => ({ type: 'string', description });
|
|
56
|
+
const num = (description) => ({ type: 'number', description });
|
|
57
|
+
const bool = (description) => ({ type: 'boolean', description });
|
|
58
|
+
const schema = (properties, required = []) => ({ type: 'object', properties, required });
|
|
59
|
+
|
|
60
|
+
function requireArg(value, name) {
|
|
61
|
+
if (value === undefined || value === null || value === '') throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Missing argument: ${name}`);
|
|
62
|
+
return value;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function throwIfAborted(signal) {
|
|
66
|
+
if (signal?.aborted) throw signal.reason || new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled');
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// ── fs ──────────────────────────────────────────────────────────────────────────────────────────
|
|
70
|
+
|
|
71
|
+
async function looksBinary(abs) {
|
|
72
|
+
const handle = await fs.promises.open(abs, 'r');
|
|
73
|
+
try {
|
|
74
|
+
const buf = Buffer.alloc(8192);
|
|
75
|
+
const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
|
|
76
|
+
return buf.subarray(0, bytesRead).includes(0);
|
|
77
|
+
} finally {
|
|
78
|
+
await handle.close();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Đọc theo khoảng dòng bằng luồng — tệp lớn không phải nạp cả vào RAM. */
|
|
83
|
+
async function readLines(abs, startLine, endLine, signal) {
|
|
84
|
+
const stream = fs.createReadStream(abs, { encoding: 'utf8' });
|
|
85
|
+
const rl = readline.createInterface({ input: stream, crlfDelay: Infinity });
|
|
86
|
+
const lines = [];
|
|
87
|
+
let n = 0;
|
|
88
|
+
let bytes = 0;
|
|
89
|
+
let truncatedByBytes = false;
|
|
90
|
+
try {
|
|
91
|
+
for await (const line of rl) {
|
|
92
|
+
n++;
|
|
93
|
+
if (n < startLine) continue;
|
|
94
|
+
if (n > endLine) break;
|
|
95
|
+
bytes += line.length + 1;
|
|
96
|
+
if (bytes > MAX_READ_BYTES) { truncatedByBytes = true; break; }
|
|
97
|
+
lines.push(line);
|
|
98
|
+
if (signal?.aborted) break;
|
|
99
|
+
}
|
|
100
|
+
} finally {
|
|
101
|
+
rl.close();
|
|
102
|
+
stream.destroy();
|
|
103
|
+
}
|
|
104
|
+
throwIfAborted(signal);
|
|
105
|
+
return { lines, lastLine: startLine + lines.length - 1, truncatedByBytes };
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
async function fsRead(args, ctx, env) {
|
|
109
|
+
const abs = resolveInRoots(env.roots, requireArg(args.path, 'path'));
|
|
110
|
+
const stat = await fs.promises.stat(abs).catch(() => null);
|
|
111
|
+
if (!stat) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `File not found: ${args.path}`);
|
|
112
|
+
if (stat.isDirectory()) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Is a directory: ${args.path} (use fs.list)`);
|
|
113
|
+
if (args.byteOffset !== undefined || args.byteLength !== undefined || args.encoding === 'base64') {
|
|
114
|
+
const offset = Math.max(0, Number(args.byteOffset) || 0);
|
|
115
|
+
const length = Math.min(Math.max(0, Number(args.byteLength) || 64 * 1024), MAX_READ_BYTES, Math.max(0, stat.size - offset));
|
|
116
|
+
const handle = await fs.promises.open(abs, 'r');
|
|
117
|
+
try {
|
|
118
|
+
const buf = Buffer.alloc(length);
|
|
119
|
+
const { bytesRead } = await handle.read(buf, 0, length, offset);
|
|
120
|
+
return { path: displayPath(env.roots, abs), size: stat.size, byteOffset: offset, byteLength: bytesRead, encoding: args.encoding === 'base64' ? 'base64' : 'utf8', content: buf.subarray(0, bytesRead).toString(args.encoding === 'base64' ? 'base64' : 'utf8'), eof: offset + bytesRead >= stat.size };
|
|
121
|
+
} finally {
|
|
122
|
+
await handle.close();
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (await looksBinary(abs)) {
|
|
126
|
+
return { path: displayPath(env.roots, abs), size: stat.size, binary: true, hint: 'Binary file — read ranges with byteOffset/byteLength and encoding "base64".' };
|
|
127
|
+
}
|
|
128
|
+
const startLine = Math.max(1, Number(args.startLine) || 1);
|
|
129
|
+
const endLine = Math.min(Number(args.endLine) || startLine + DEFAULT_READ_LINES - 1, startLine + MAX_READ_LINES - 1);
|
|
130
|
+
const { lines, lastLine, truncatedByBytes } = await readLines(abs, startLine, endLine, ctx.signal);
|
|
131
|
+
const hasMore = truncatedByBytes || lines.length === endLine - startLine + 1;
|
|
132
|
+
return {
|
|
133
|
+
path: displayPath(env.roots, abs), size: stat.size, startLine, endLine: lastLine, content: lines.join('\n'),
|
|
134
|
+
...(hasMore ? { hint: `More may follow — continue with startLine: ${lastLine + 1}` } : {}),
|
|
135
|
+
};
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
async function fsReadMany(args, ctx, env) {
|
|
139
|
+
const paths = (Array.isArray(args.paths) ? args.paths : []).slice(0, 20);
|
|
140
|
+
if (!paths.length) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Missing argument: paths');
|
|
141
|
+
const lines = Math.min(Number(args.maxLines) || 400, MAX_READ_LINES);
|
|
142
|
+
const files = await Promise.all(paths.map(async (p) => {
|
|
143
|
+
try { return { ok: true, ...(await fsRead({ path: p, startLine: 1, endLine: lines }, ctx, env)) }; } catch (e) { return { ok: false, path: p, error: e.message }; }
|
|
144
|
+
}));
|
|
145
|
+
return { files };
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
const DAY_MS = 86_400_000;
|
|
149
|
+
|
|
150
|
+
/** Mốc thời gian lọc: ngày ISO ("2026-10-01") hoặc số ngày trước ("30" = 30 ngày trước). */
|
|
151
|
+
function timeBound(value) {
|
|
152
|
+
if (value === undefined || value === null || value === '') return undefined;
|
|
153
|
+
if (/^\d+(\.\d+)?$/.test(String(value))) return Date.now() - Number(value) * DAY_MS;
|
|
154
|
+
const t = Date.parse(String(value));
|
|
155
|
+
if (Number.isNaN(t)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Bad date: ${value}`);
|
|
156
|
+
return t;
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Mẫu tên kiểu *.pdf / bao-cao* → RegExp (không phân biệt hoa thường). */
|
|
160
|
+
function nameMatcher(pattern) {
|
|
161
|
+
if (!pattern) return null;
|
|
162
|
+
const re = String(pattern).split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*');
|
|
163
|
+
return new RegExp(`^${re}$`, 'i');
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
/**
|
|
167
|
+
* Liệt kê thư mục; có lọc (đuôi, mẫu tên, ngày sửa, dung lượng, chỉ tệp) và sắp xếp (tên / ngày sửa / dung lượng) → "PDF trong Downloads cũ
|
|
168
|
+
* hơn 30 ngày, lớn nhất trước" trong MỘT lời gọi, không phải đọc hết danh sách rồi tự lọc.
|
|
169
|
+
*/
|
|
170
|
+
async function fsList(args, ctx, env) {
|
|
171
|
+
const abs = resolveInRoots(env.roots, args.path || '');
|
|
172
|
+
const maxDepth = args.recursive ? Math.min(Number(args.maxDepth) || 3, 8) : 0;
|
|
173
|
+
const limit = Math.min(Number(args.maxEntries) || 500, MAX_LIST_ENTRIES);
|
|
174
|
+
const exts = (Array.isArray(args.ext) ? args.ext : String(args.ext || '').split(',')).map((x) => String(x).trim().toLowerCase().replace(/^\.?/, '.')).filter((x) => x.length > 1);
|
|
175
|
+
const name = nameMatcher(args.name);
|
|
176
|
+
const after = timeBound(args.modifiedAfter);
|
|
177
|
+
const before = timeBound(args.modifiedBefore);
|
|
178
|
+
const minSize = Number(args.minSize) || 0;
|
|
179
|
+
const maxSize = Number(args.maxSize) || Infinity;
|
|
180
|
+
const filtered = !!(exts.length || name || after || before || minSize || maxSize !== Infinity || args.filesOnly);
|
|
181
|
+
const needStat = filtered || ['modified', 'size'].includes(args.sort);
|
|
182
|
+
// Lọc / sắp xếp cần xét nhiều hơn số trả về — quét tối đa 20 lần trần.
|
|
183
|
+
const scanLimit = filtered || args.sort ? limit * 20 : limit;
|
|
184
|
+
const out = [];
|
|
185
|
+
let scanned = 0;
|
|
186
|
+
const queue = [[abs, 0]];
|
|
187
|
+
while (queue.length && scanned < scanLimit) {
|
|
188
|
+
throwIfAborted(ctx.signal);
|
|
189
|
+
const [dir, depth] = queue.shift();
|
|
190
|
+
let entries;
|
|
191
|
+
try { entries = await fs.promises.readdir(dir, { withFileTypes: true }); } catch (e) { if (dir === abs) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, e.message); continue; }
|
|
192
|
+
for (const e of entries) {
|
|
193
|
+
if (scanned >= scanLimit) break;
|
|
194
|
+
const full = path.join(dir, e.name);
|
|
195
|
+
// Thư mục cấu hình Aivin (token) nằm dưới gốc được phép (vd `--dir ~`) → không liệt kê, không đi vào.
|
|
196
|
+
if (isProtectedPath(full)) continue;
|
|
197
|
+
scanned++;
|
|
198
|
+
const isDir = e.isDirectory();
|
|
199
|
+
if (isDir && depth < maxDepth && !IGNORED_DIRS.has(e.name) && !e.isSymbolicLink()) queue.push([full, depth + 1]);
|
|
200
|
+
if (args.filesOnly && isDir) continue;
|
|
201
|
+
if (exts.length && (isDir || !exts.includes(path.extname(e.name).toLowerCase()))) continue;
|
|
202
|
+
if (name && !name.test(e.name)) continue;
|
|
203
|
+
const item = { path: displayPath(env.roots, full), dir: isDir || undefined };
|
|
204
|
+
if (needStat) {
|
|
205
|
+
const st = await fs.promises.lstat(full).catch(() => null);
|
|
206
|
+
if (!st) continue;
|
|
207
|
+
if ((after && st.mtimeMs < after) || (before && st.mtimeMs > before)) continue;
|
|
208
|
+
if (!isDir && (st.size < minSize || st.size > maxSize)) continue;
|
|
209
|
+
if (isDir && (minSize || maxSize !== Infinity)) continue;
|
|
210
|
+
item.size = isDir ? undefined : st.size;
|
|
211
|
+
item.modified = st.mtime.toISOString().slice(0, 10);
|
|
212
|
+
item._mtime = st.mtimeMs;
|
|
213
|
+
}
|
|
214
|
+
out.push(item);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
const dirn = args.order === 'asc' ? 1 : args.order === 'desc' ? -1 : (args.sort === 'name' ? 1 : -1);
|
|
218
|
+
if (args.sort === 'modified') out.sort((a, b) => dirn * ((a._mtime || 0) - (b._mtime || 0)));
|
|
219
|
+
else if (args.sort === 'size') out.sort((a, b) => dirn * ((a.size || 0) - (b.size || 0)));
|
|
220
|
+
else if (args.sort === 'name') out.sort((a, b) => dirn * a.path.localeCompare(b.path));
|
|
221
|
+
const entries = out.slice(0, limit).map((e) => { const item = { ...e }; delete item._mtime; return item; });
|
|
222
|
+
return {
|
|
223
|
+
base: displayPath(env.roots, abs), total: entries.length, matched: out.length,
|
|
224
|
+
truncated: out.length > limit || scanned >= scanLimit || undefined, entries,
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
const withoutAbs = ({ abs: _abs, ...rest }) => rest;
|
|
229
|
+
|
|
230
|
+
async function fsFind(args, _ctx, env) {
|
|
231
|
+
if (!env.fileIndex) throw new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, 'File index not ready');
|
|
232
|
+
const query = requireArg(args.query, 'query');
|
|
233
|
+
const limit = Math.min(Number(args.limit) || 15, 100);
|
|
234
|
+
// `vector`: BE tự gắn vector bge-m3 của câu hỏi (Planner chỉ viết query) → gộp xếp hạng ngữ nghĩa.
|
|
235
|
+
const local = env.fileIndex.search(query, limit, args.vector);
|
|
236
|
+
// Chỉ mục cố ý bỏ nhiều thứ (thư mục gộp, kho code, ngoài thư mục nhà) và khớp BẤT KỲ từ nào → thiếu kết quả hoặc kết quả yếu (tốt nhất
|
|
237
|
+
// không chứa đủ các từ, hay chỉ ra thư mục gộp) thì hỏi thêm bộ tìm của hệ điều hành (khớp ĐỦ mọi từ) — "ảnh chụp màn hình 21/8/2026" ra
|
|
238
|
+
// đúng `Screenshot 2026-08-21 ….png` trong thư mục gộp thay vì 15 tệp chỉ trùng chữ "2026".
|
|
239
|
+
const weak = !coversQuery(local[0], query) || local.some((r) => r.type === 'folder');
|
|
240
|
+
if (env.osSearch === false || (local.length >= limit && !weak)) return { results: local.map(withoutAbs), stats: env.fileIndex.stats() };
|
|
241
|
+
const seen = new Set(local.map((r) => r.abs));
|
|
242
|
+
const osSearch = typeof env.osSearch === 'function' ? env.osSearch : osFileSearch;
|
|
243
|
+
const fromOs = (await osSearch(query, { roots: env.roots, limit }))
|
|
244
|
+
.filter((r) => !seen.has(r.abs))
|
|
245
|
+
.map((r) => ({ path: displayPath(env.roots, r.abs), ...(r.size !== undefined ? { size: r.size } : {}), modified: r.modified, source: 'os' }));
|
|
246
|
+
const results = weak ? [...fromOs, ...local.map(withoutAbs)] : [...local.map(withoutAbs), ...fromOs];
|
|
247
|
+
return { results: results.slice(0, limit), stats: env.fileIndex.stats() };
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
/** Kết quả chứa đủ mọi từ của câu hỏi (tên, đường dẫn, đoạn đầu — đã bỏ dấu). */
|
|
251
|
+
function coversQuery(hit, query) {
|
|
252
|
+
if (!hit) return false;
|
|
253
|
+
const have = new Set(tokenize(`${hit.abs || hit.path} ${hit.preview || ''} ${hit.note || ''}`));
|
|
254
|
+
const words = tokenize(query);
|
|
255
|
+
return words.length > 0 && words.every((w) => have.has(w) || [...have].some((h) => h.startsWith(w)));
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
/** Thư mục làm việc người dùng chỉ ra (qua chat): lập chỉ mục đầy đủ ngay (kể cả code), theo dõi thay đổi; `remove` để bỏ. */
|
|
259
|
+
async function fsIndexFolder(args, _ctx, env) {
|
|
260
|
+
if (!env.fileIndex) throw new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, 'File index not ready');
|
|
261
|
+
const abs = resolveInRoots(env.roots, requireArg(args.path, 'path'));
|
|
262
|
+
if (args.remove) {
|
|
263
|
+
const res = await env.fileIndex.removeFolder(abs);
|
|
264
|
+
return { folder: displayPath(env.roots, abs), removed: true, working_folders: res.folders.map((f) => displayPath(env.roots, f)) };
|
|
265
|
+
}
|
|
266
|
+
const stat = await fs.promises.stat(abs).catch(() => null);
|
|
267
|
+
if (!stat?.isDirectory()) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Not a folder: ${displayPath(env.roots, abs)}`);
|
|
268
|
+
const res = await env.fileIndex.addFolder(abs);
|
|
269
|
+
return {
|
|
270
|
+
folder: displayPath(env.roots, abs), indexed_items: res.indexed, done: res.done,
|
|
271
|
+
working_folders: res.folders.map((f) => displayPath(env.roots, f)),
|
|
272
|
+
...(res.done ? {} : { note: 'Still indexing in the background - fs.find already returns what is indexed so far.' }),
|
|
273
|
+
};
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
const PREVIEW_MAX_PATHS = 10;
|
|
277
|
+
const PREVIEW_CHARS = 800;
|
|
278
|
+
|
|
279
|
+
/** Xem trước nhiều tệp một lần: dung lượng, ngày sửa, đoạn chữ đầu (đọc cả docx/xlsx/pptx) — để chọn đúng tệp giữa các ứng viên. */
|
|
280
|
+
async function fsPreview(args, ctx, env) {
|
|
281
|
+
const paths = (Array.isArray(args.paths) ? args.paths : []).slice(0, PREVIEW_MAX_PATHS);
|
|
282
|
+
if (!paths.length) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Missing argument: paths');
|
|
283
|
+
const chars = Math.min(Number(args.maxChars) || PREVIEW_CHARS, 4000);
|
|
284
|
+
const files = await Promise.all(paths.map(async (p) => {
|
|
285
|
+
try {
|
|
286
|
+
const abs = resolveInRoots(env.roots, p);
|
|
287
|
+
const stat = await fs.promises.stat(abs).catch(() => null);
|
|
288
|
+
if (!stat || !stat.isFile()) return { path: p, exists: !!stat, dir: stat?.isDirectory() || undefined };
|
|
289
|
+
const base = { path: displayPath(env.roots, abs), exists: true, size: stat.size, modified: stat.mtime.toISOString().slice(0, 10) };
|
|
290
|
+
if (isDocFile(abs)) return { ...base, preview: await extractDocText(abs, stat.size, chars) };
|
|
291
|
+
if (await looksBinary(abs)) return { ...base, binary: true };
|
|
292
|
+
const { lines } = await readLines(abs, 1, 40, ctx.signal);
|
|
293
|
+
const text = lines.join('\n');
|
|
294
|
+
return { ...base, preview: text.length > chars ? `${text.slice(0, chars)}…` : text };
|
|
295
|
+
} catch (e) {
|
|
296
|
+
return { path: p, error: e.message };
|
|
297
|
+
}
|
|
298
|
+
}));
|
|
299
|
+
return { files };
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function runProcess(cmd, argv, { cwd, signal, onOutput, env, maxOutput = MAX_EXEC_OUTPUT, shell = false, runAs }) {
|
|
303
|
+
return new Promise((resolve, reject) => {
|
|
304
|
+
const startedAt = Date.now();
|
|
305
|
+
const baseEnv = env || scrubEnv();
|
|
306
|
+
const account = runAs ? { uid: runAs.uid, gid: runAs.gid } : {};
|
|
307
|
+
// Thành viên máy tính tổ chức: trần số tiến trình theo uid (prlimit) — một người không fork bomb được cả container.
|
|
308
|
+
if (runAs) [cmd, argv] = withProcessCap(cmd, argv);
|
|
309
|
+
const child = spawn(cmd, argv, { cwd, env: runAs ? accountEnv(runAs, baseEnv) : baseEnv, windowsHide: true, shell, detached: process.platform !== 'win32', ...account });
|
|
310
|
+
let stdout = '';
|
|
311
|
+
let stderr = '';
|
|
312
|
+
let killed = false;
|
|
313
|
+
const killTree = () => {
|
|
314
|
+
if (killed || child.exitCode !== null) return;
|
|
315
|
+
killed = true;
|
|
316
|
+
if (process.platform === 'win32') spawn('taskkill', ['/pid', String(child.pid), '/T', '/F'], { windowsHide: true });
|
|
317
|
+
else { try { process.kill(-child.pid, 'SIGKILL'); } catch { child.kill('SIGKILL'); } }
|
|
318
|
+
};
|
|
319
|
+
const onAbort = () => killTree();
|
|
320
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
321
|
+
child.stdout.on('data', (chunk) => { const t = chunk.toString(); if (stdout.length < maxOutput) stdout += t; onOutput?.('stdout', t); });
|
|
322
|
+
child.stderr.on('data', (chunk) => { const t = chunk.toString(); if (stderr.length < maxOutput) stderr += t; onOutput?.('stderr', t); });
|
|
323
|
+
child.on('error', (e) => { signal?.removeEventListener('abort', onAbort); reject(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `Cannot start process: ${e.message}`)); });
|
|
324
|
+
child.on('close', (code) => {
|
|
325
|
+
signal?.removeEventListener('abort', onAbort);
|
|
326
|
+
if (signal?.aborted) return reject(signal.reason || new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled'));
|
|
327
|
+
resolve({ exitCode: code ?? -1, stdout, stderr, durationMs: Date.now() - startedAt, ...(stdout.length >= maxOutput || stderr.length >= maxOutput ? { outputTruncated: true } : {}) });
|
|
328
|
+
});
|
|
329
|
+
});
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
async function fsGrep(args, ctx, env) {
|
|
333
|
+
const query = String(requireArg(args.query, 'query'));
|
|
334
|
+
const abs = resolveInRoots(env.roots, args.path || '');
|
|
335
|
+
const maxResults = Math.min(Number(args.maxResults) || 50, 500);
|
|
336
|
+
if (env.binaries?.includes('rg')) {
|
|
337
|
+
// Loại thư mục cấu hình Aivin kể cả khi bật tìm tệp ẩn; lọc lại kết quả phía dưới phòng khi glob của người gọi lách được.
|
|
338
|
+
const exclude = protectedDirNamesUnder(abs).flatMap((name) => ['-g', `!${name}`]);
|
|
339
|
+
// Chuỗi tìm do AI gửi luôn đi sau `-e` (không bao giờ thành cờ của ripgrep — `--pre=<chương trình>` từng chạy được chương trình ngoài
|
|
340
|
+
// từ một công cụ chỉ đọc, rà 28/10/2026), đường dẫn sau `--`.
|
|
341
|
+
const argv = ['--line-number', '--no-heading', '--color', 'never', '--max-count', '5', '--max-filesize', '2M', ...(args.regex ? [] : ['-F']), '-e', query, ...(args.glob ? ['-g', String(args.glob)] : []), ...exclude, '--', abs];
|
|
342
|
+
const res = await runProcess('rg', argv, { cwd: abs, signal: ctx.signal, maxOutput: 512 * 1024, runAs: env.runAs });
|
|
343
|
+
const matches = res.stdout.split(/\r?\n/).filter(Boolean).map((line) => {
|
|
344
|
+
const m = line.match(/^(.*?):(\d+):(.*)$/);
|
|
345
|
+
if (m && isProtectedPath(path.resolve(abs, m[1]))) return null;
|
|
346
|
+
return m ? { path: displayPath(env.roots, m[1]), line: Number(m[2]), text: m[3].slice(0, 300) } : { text: line.slice(0, 300) };
|
|
347
|
+
}).filter(Boolean).slice(0, maxResults);
|
|
348
|
+
return { engine: 'ripgrep', total: matches.length, matches };
|
|
349
|
+
}
|
|
350
|
+
// Không có ripgrep (đa số máy Windows): đọc SONG SONG theo từng thư mục (trước đây đọc tuần tự từng tệp — chậm trên cây lớn).
|
|
351
|
+
const re = args.regex ? new RegExp(query) : null;
|
|
352
|
+
const glob = nameMatcher(args.glob);
|
|
353
|
+
const matches = [];
|
|
354
|
+
const scanFile = async (full) => {
|
|
355
|
+
if (matches.length >= maxResults) return;
|
|
356
|
+
const stat = await fs.promises.stat(full).catch(() => null);
|
|
357
|
+
if (!stat || stat.size > 2 * 1024 * 1024) return;
|
|
358
|
+
const text = await fs.promises.readFile(full, 'utf8').catch(() => '');
|
|
359
|
+
if (text.includes('\u0000')) return;
|
|
360
|
+
text.split(/\r?\n/).some((line, i) => {
|
|
361
|
+
if (re ? re.test(line) : line.includes(query)) matches.push({ path: displayPath(env.roots, full), line: i + 1, text: line.trim().slice(0, 300) });
|
|
362
|
+
return matches.length >= maxResults;
|
|
363
|
+
});
|
|
364
|
+
};
|
|
365
|
+
const queue = [abs];
|
|
366
|
+
while (queue.length && matches.length < maxResults) {
|
|
367
|
+
throwIfAborted(ctx.signal);
|
|
368
|
+
const dir = queue.shift();
|
|
369
|
+
let entries;
|
|
370
|
+
try { entries = await fs.promises.readdir(dir, { withFileTypes: true }); } catch { continue; }
|
|
371
|
+
const files = [];
|
|
372
|
+
for (const e of entries) {
|
|
373
|
+
const full = path.join(dir, e.name);
|
|
374
|
+
if (isProtectedPath(full)) continue;
|
|
375
|
+
if (e.isDirectory()) { if (!IGNORED_DIRS.has(e.name) && !e.isSymbolicLink()) queue.push(full); continue; }
|
|
376
|
+
if (e.isFile() && (!glob || glob.test(e.name))) files.push(full);
|
|
377
|
+
}
|
|
378
|
+
for (let i = 0; i < files.length && matches.length < maxResults; i += GREP_CONCURRENCY) {
|
|
379
|
+
await Promise.all(files.slice(i, i + GREP_CONCURRENCY).map(scanFile));
|
|
380
|
+
}
|
|
381
|
+
}
|
|
382
|
+
return { engine: 'builtin', total: Math.min(matches.length, maxResults), matches: matches.slice(0, maxResults) };
|
|
383
|
+
}
|
|
384
|
+
|
|
385
|
+
async function fsInfo(args, _ctx, env) {
|
|
386
|
+
const abs = resolveInRoots(env.roots, args.path || '');
|
|
387
|
+
const stat = await fs.promises.stat(abs).catch(() => null);
|
|
388
|
+
if (!stat) return { path: displayPath(env.roots, abs), exists: false };
|
|
389
|
+
return { path: displayPath(env.roots, abs), exists: true, dir: stat.isDirectory(), size: stat.size, modifiedAt: stat.mtime.toISOString(), createdAt: stat.birthtime.toISOString() };
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
/** Ghi lại thao tác vào kho hoàn tác của lời gọi (BE gắn `undo_group` = nhiệm vụ). Không có kho → null (ghi / xoá như cũ). */
|
|
393
|
+
const undoOf = (args, env, op) => (env.undo ? env.undo.begin(args.undo_group, op) : null);
|
|
394
|
+
|
|
395
|
+
async function fsWrite(args, _ctx, env) {
|
|
396
|
+
const abs = resolveInRoots(env.roots, requireArg(args.path, 'path'));
|
|
397
|
+
const exists = fs.existsSync(abs);
|
|
398
|
+
if (exists && args.overwrite === false && !args.append) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `File exists and overwrite is false: ${args.path}`);
|
|
399
|
+
let data = args.encoding === 'base64' ? Buffer.from(String(args.content ?? ''), 'base64') : String(args.content ?? '');
|
|
400
|
+
// Nối chữ vào tệp chưa kết thúc bằng xuống dòng → chèn một xuống dòng theo kiểu của tệp (chạy thật 28/10/2026: dòng tóm tắt dính vào
|
|
401
|
+
// cuối dòng cũ của summary.log). Nội dung nhị phân giữ nguyên.
|
|
402
|
+
const lineBreak = args.append && exists && typeof data === 'string' && data && !/^\r?\n/.test(data) ? await missingLineBreak(abs) : '';
|
|
403
|
+
if (lineBreak) data = lineBreak + data;
|
|
404
|
+
// Ghi đè / nối thêm vào tệp có sẵn → lưu bản cũ trước (hoàn tác được); tệp mới → ghi lại để hoàn tác thì bỏ đi.
|
|
405
|
+
const undo = undoOf(args, env, 'write');
|
|
406
|
+
if (undo) await undo.ensureDir(path.dirname(abs));
|
|
407
|
+
else await fs.promises.mkdir(path.dirname(abs), { recursive: true });
|
|
408
|
+
const backup = exists ? await undo?.backupFile(abs) : undefined;
|
|
409
|
+
if (args.append) await fs.promises.appendFile(abs, data);
|
|
410
|
+
else await fs.promises.writeFile(abs, data);
|
|
411
|
+
if (!exists) undo?.created(abs);
|
|
412
|
+
undo?.commit();
|
|
413
|
+
return {
|
|
414
|
+
path: displayPath(env.roots, abs), bytes: Buffer.byteLength(data), created: !exists, appended: !!args.append || undefined,
|
|
415
|
+
...(lineBreak ? { line_break_added: true } : {}),
|
|
416
|
+
...(exists && undo ? { previous_version_kept: !!backup } : {}),
|
|
417
|
+
};
|
|
418
|
+
}
|
|
419
|
+
|
|
420
|
+
/** Tệp không rỗng và byte cuối không phải xuống dòng → kiểu xuống dòng của tệp (CRLF nếu tệp đã dùng CRLF), ngược lại ''. */
|
|
421
|
+
async function missingLineBreak(abs) {
|
|
422
|
+
const handle = await fs.promises.open(abs, 'r');
|
|
423
|
+
try {
|
|
424
|
+
const { size } = await handle.stat();
|
|
425
|
+
if (!size) return '';
|
|
426
|
+
const head = Buffer.alloc(Math.min(size, 4096));
|
|
427
|
+
await handle.read(head, 0, head.length, 0);
|
|
428
|
+
const last = Buffer.alloc(1);
|
|
429
|
+
await handle.read(last, 0, 1, size - 1);
|
|
430
|
+
if (last[0] === 0x0a) return '';
|
|
431
|
+
return head.includes('\r\n') ? '\r\n' : '\n';
|
|
432
|
+
} finally {
|
|
433
|
+
await handle.close();
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
|
|
437
|
+
async function fsEdit(args, _ctx, env) {
|
|
438
|
+
const abs = resolveInRoots(env.roots, requireArg(args.path, 'path'));
|
|
439
|
+
const oldText = String(requireArg(args.oldText, 'oldText'));
|
|
440
|
+
const newText = String(args.newText ?? '');
|
|
441
|
+
const content = await fs.promises.readFile(abs, 'utf8').catch(() => { throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `File not found: ${args.path}`); });
|
|
442
|
+
const count = content.split(oldText).length - 1;
|
|
443
|
+
if (!count) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'oldText not found in file');
|
|
444
|
+
if (count > 1 && !args.replaceAll) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `oldText occurs ${count} times — give more context or set replaceAll`);
|
|
445
|
+
const undo = undoOf(args, env, 'edit');
|
|
446
|
+
await undo?.backupFile(abs);
|
|
447
|
+
await fs.promises.writeFile(abs, args.replaceAll ? content.split(oldText).join(newText) : content.replace(oldText, () => newText));
|
|
448
|
+
undo?.commit();
|
|
449
|
+
return { path: displayPath(env.roots, abs), replaced: args.replaceAll ? count : 1 };
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/** Kiểm + chuyển một mục (dùng chung cho fs.move và fs.move_many). Đích có sẵn mà được phép đè → đích cũ vào thùng rác của kho trước. */
|
|
453
|
+
async function moveOne(env, undo, sourcePath, destinationPath, overwrite) {
|
|
454
|
+
// Không theo symlink ở thành phần cuối: chuyển một liên kết là chuyển chính liên kết đó.
|
|
455
|
+
const src = resolveEntryInRoots(env.roots, requireArg(sourcePath, 'sourcePath'));
|
|
456
|
+
const dst = resolveEntryInRoots(env.roots, requireArg(destinationPath, 'destinationPath'));
|
|
457
|
+
// Nguồn "" / "." là chính thư mục gốc — đổi tên gốc là mất cả vùng được phép.
|
|
458
|
+
if (isRootPath(env.roots, src) || isRootPath(env.roots, dst)) throw new DeviceToolError(DeviceErrorCode.ROOT_DENIED, 'Refusing to move or replace an allowed root folder');
|
|
459
|
+
if (containsProtectedPath(src) || containsProtectedPath(dst)) throw new DeviceToolError(DeviceErrorCode.PROTECTED_PATH, 'Folder holds Aivin credentials and cannot be moved remotely');
|
|
460
|
+
if (!fs.lstatSync(src, { throwIfNoEntry: false })) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Source not found: ${sourcePath}`);
|
|
461
|
+
const dstExists = !!fs.lstatSync(dst, { throwIfNoEntry: false });
|
|
462
|
+
if (dstExists && overwrite !== true) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Destination exists: ${destinationPath} (set overwrite to replace)`);
|
|
463
|
+
if (undo) await undo.ensureDir(path.dirname(dst));
|
|
464
|
+
else await fs.promises.mkdir(path.dirname(dst), { recursive: true });
|
|
465
|
+
if (dstExists) {
|
|
466
|
+
if (undo) await undo.trash(dst);
|
|
467
|
+
else await fs.promises.rm(dst, { recursive: true, force: true });
|
|
468
|
+
}
|
|
469
|
+
try {
|
|
470
|
+
await fs.promises.rename(src, dst);
|
|
471
|
+
} catch (e) {
|
|
472
|
+
if (e.code !== 'EXDEV') throw e;
|
|
473
|
+
// Khác ổ đĩa: chép rồi xoá bản gốc.
|
|
474
|
+
await fs.promises.cp(src, dst, { recursive: true, preserveTimestamps: true, verbatimSymlinks: true });
|
|
475
|
+
await fs.promises.rm(src, { recursive: true, force: true });
|
|
476
|
+
}
|
|
477
|
+
undo?.moved(src, dst);
|
|
478
|
+
return { from: displayPath(env.roots, src), to: displayPath(env.roots, dst), replaced: dstExists || undefined };
|
|
479
|
+
}
|
|
480
|
+
|
|
481
|
+
async function fsMove(args, _ctx, env) {
|
|
482
|
+
const undo = undoOf(args, env, 'move');
|
|
483
|
+
try { return await moveOne(env, undo, args.sourcePath, args.destinationPath, args.overwrite); } finally { undo?.commit(); }
|
|
484
|
+
}
|
|
485
|
+
|
|
486
|
+
/**
|
|
487
|
+
* Sao chép một tệp / thư mục (29/10/2026 — trước đó không có công cụ chép, Planner từng "sao chép" bằng fs.move làm mất tệp nguồn). Đích
|
|
488
|
+
* có sẵn chỉ bị thay khi `overwrite` (bản cũ vào thùng rác của kho, hoàn tác được); hoàn tác bản chép = bỏ đích vừa tạo.
|
|
489
|
+
*/
|
|
490
|
+
async function fsCopy(args, _ctx, env) {
|
|
491
|
+
const src = resolveInRoots(env.roots, requireArg(args.sourcePath, 'sourcePath'));
|
|
492
|
+
const dest = resolveInRoots(env.roots, requireArg(args.destinationPath, 'destinationPath'));
|
|
493
|
+
const stat = await fs.promises.stat(src).catch(() => null);
|
|
494
|
+
if (!stat) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Not found: ${args.sourcePath}`);
|
|
495
|
+
if (path.resolve(src) === path.resolve(dest)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Source and destination are the same');
|
|
496
|
+
const exists = fs.existsSync(dest);
|
|
497
|
+
if (exists && args.overwrite !== true) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Destination exists (set overwrite to replace it): ${args.destinationPath}`);
|
|
498
|
+
const undo = undoOf(args, env, 'copy');
|
|
499
|
+
try {
|
|
500
|
+
if (undo) await undo.ensureDir(path.dirname(dest));
|
|
501
|
+
else await fs.promises.mkdir(path.dirname(dest), { recursive: true });
|
|
502
|
+
if (exists) {
|
|
503
|
+
if (undo) await undo.trash(dest);
|
|
504
|
+
else await fs.promises.rm(dest, { recursive: true, force: true });
|
|
505
|
+
}
|
|
506
|
+
await fs.promises.cp(src, dest, { recursive: stat.isDirectory(), force: true });
|
|
507
|
+
undo?.created(dest);
|
|
508
|
+
} finally { undo?.commit(); }
|
|
509
|
+
return { sourcePath: displayPath(env.roots, src), destinationPath: displayPath(env.roots, dest), dir: stat.isDirectory() || undefined, replaced: exists || undefined };
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
/** Kiểm + xoá một mục: có kho → thùng rác của kho (hoàn tác được); không có / `permanent` → xoá hẳn. */
|
|
513
|
+
async function deleteOne(env, undo, target, permanent) {
|
|
514
|
+
// Không theo symlink ở thành phần cuối: xoá liên kết là xoá chính liên kết, không xoá thư mục nó trỏ tới.
|
|
515
|
+
const abs = resolveEntryInRoots(env.roots, requireArg(target, 'path'));
|
|
516
|
+
if (isRootPath(env.roots, abs)) throw new DeviceToolError(DeviceErrorCode.ROOT_DENIED, 'Refusing to delete an allowed root folder');
|
|
517
|
+
if (containsProtectedPath(abs)) throw new DeviceToolError(DeviceErrorCode.PROTECTED_PATH, 'Folder holds Aivin credentials and cannot be deleted remotely');
|
|
518
|
+
const stat = await fs.promises.lstat(abs).catch(() => null);
|
|
519
|
+
if (!stat) return { path: displayPath(env.roots, abs), deleted: false };
|
|
520
|
+
if (undo && !permanent) await undo.trash(abs);
|
|
521
|
+
else await fs.promises.rm(abs, { recursive: stat.isDirectory(), force: true });
|
|
522
|
+
return { path: displayPath(env.roots, abs), deleted: true, dir: stat.isDirectory() || undefined, recoverable: !!undo && !permanent };
|
|
523
|
+
}
|
|
524
|
+
|
|
525
|
+
async function fsDelete(args, _ctx, env) {
|
|
526
|
+
const undo = undoOf(args, env, 'delete');
|
|
527
|
+
try { return await deleteOne(env, undo, args.path, args.permanent === true); } finally { undo?.commit(); }
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
function batchItems(list, name) {
|
|
531
|
+
if (!Array.isArray(list) || !list.length) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Missing argument: ${name}`);
|
|
532
|
+
if (list.length > MAX_BATCH_ITEMS) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `At most ${MAX_BATCH_ITEMS} items per call — split the list`);
|
|
533
|
+
return list;
|
|
534
|
+
}
|
|
535
|
+
|
|
536
|
+
/** Chạy từng mục với giới hạn song song; mục lỗi không chặn mục khác. */
|
|
537
|
+
async function runBatch(items, ctx, fn) {
|
|
538
|
+
const done = [];
|
|
539
|
+
const failed = [];
|
|
540
|
+
for (let i = 0; i < items.length; i += BATCH_CONCURRENCY) {
|
|
541
|
+
throwIfAborted(ctx.signal);
|
|
542
|
+
const results = await Promise.all(items.slice(i, i + BATCH_CONCURRENCY).map(async (item) => {
|
|
543
|
+
try { return { ok: true, value: await fn(item) }; } catch (e) { return { ok: false, item, error: e.message, code: e.code }; }
|
|
544
|
+
}));
|
|
545
|
+
for (const r of results) (r.ok ? done : failed).push(r.ok ? r.value : { item: r.item, error: r.error, code: r.code });
|
|
546
|
+
}
|
|
547
|
+
return { done, failed };
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/**
|
|
551
|
+
* Chuyển / đổi tên nhiều mục một lần (sắp xếp thư mục): một lời gọi, một lần duyệt, hoàn tác được cả lô. `dry_run` → chỉ kiểm (nguồn có,
|
|
552
|
+
* đích trùng…) và trả kế hoạch, không đổi gì.
|
|
553
|
+
*/
|
|
554
|
+
async function fsMoveMany(args, ctx, env) {
|
|
555
|
+
const moves = batchItems(args.moves, 'moves');
|
|
556
|
+
if (args.dry_run) {
|
|
557
|
+
const { done, failed } = await runBatch(moves, ctx, async (m) => {
|
|
558
|
+
const src = resolveEntryInRoots(env.roots, requireArg(m?.from, 'from'));
|
|
559
|
+
const dst = resolveEntryInRoots(env.roots, requireArg(m?.to, 'to'));
|
|
560
|
+
if (!fs.lstatSync(src, { throwIfNoEntry: false })) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Source not found: ${m.from}`);
|
|
561
|
+
if (fs.lstatSync(dst, { throwIfNoEntry: false }) && args.overwrite !== true) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Destination exists: ${m.to}`);
|
|
562
|
+
return { from: displayPath(env.roots, src), to: displayPath(env.roots, dst) };
|
|
563
|
+
});
|
|
564
|
+
const folders = [...new Set(done.map((d) => path.dirname(d.to)))];
|
|
565
|
+
return { dry_run: true, would_move: done.length, problems: failed, target_folders: folders.slice(0, 50), sample: done.slice(0, 20) };
|
|
566
|
+
}
|
|
567
|
+
const undo = undoOf(args, env, 'move_many');
|
|
568
|
+
try {
|
|
569
|
+
const { done, failed } = await runBatch(moves, ctx, (m) => moveOne(env, undo, m?.from, m?.to, args.overwrite));
|
|
570
|
+
return { moved: done.length, failed, sample: done.slice(0, 20), recoverable: !!undo };
|
|
571
|
+
} finally { undo?.commit(); }
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
async function fsDeleteMany(args, ctx, env) {
|
|
575
|
+
const paths = batchItems(args.paths, 'paths');
|
|
576
|
+
const undo = undoOf(args, env, 'delete_many');
|
|
577
|
+
try {
|
|
578
|
+
const { done, failed } = await runBatch(paths, ctx, (p) => deleteOne(env, undo, p, args.permanent === true));
|
|
579
|
+
return { deleted: done.filter((d) => d.deleted).length, missing: done.filter((d) => !d.deleted).map((d) => d.path).slice(0, 50), failed, recoverable: !!undo && args.permanent !== true };
|
|
580
|
+
} finally { undo?.commit(); }
|
|
581
|
+
}
|
|
582
|
+
|
|
583
|
+
/** Quy mô của các đường sắp xoá (số tệp, thư mục, dung lượng, vài tên) — BE đưa lên thẻ duyệt. */
|
|
584
|
+
async function fsMeasure(args, _ctx, env) {
|
|
585
|
+
const paths = (Array.isArray(args.paths) ? args.paths : [args.path]).filter(Boolean).slice(0, MAX_BATCH_ITEMS);
|
|
586
|
+
const total = { files: 0, dirs: 0, bytes: 0, truncated: false, missing: 0 };
|
|
587
|
+
for (const p of paths) {
|
|
588
|
+
let abs;
|
|
589
|
+
try { abs = resolveEntryInRoots(env.roots, p); } catch { total.missing++; continue; }
|
|
590
|
+
if (!fs.lstatSync(abs, { throwIfNoEntry: false })) { total.missing++; continue; }
|
|
591
|
+
const m = await measurePath(abs);
|
|
592
|
+
total.files += m.files; total.dirs += m.dirs; total.bytes += m.bytes; total.truncated ||= m.truncated;
|
|
593
|
+
}
|
|
594
|
+
return { ...total, items: paths.length, samples: paths.slice(0, 5) };
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
function undoUnavailable() {
|
|
598
|
+
return new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, 'Undo history is not kept on this computer');
|
|
599
|
+
}
|
|
600
|
+
|
|
601
|
+
// ── shell / system / git ────────────────────────────────────────────────────────────────────────
|
|
602
|
+
|
|
603
|
+
async function shellExec(args, ctx, env) {
|
|
604
|
+
const command = String(requireArg(args.command, 'command'));
|
|
605
|
+
assertCommandAllowed(command);
|
|
606
|
+
const cwd = resolveInRoots(env.roots, args.cwd || '');
|
|
607
|
+
const [cmd, argv] = shellCommand(command);
|
|
608
|
+
const result = await runProcess(cmd, argv, { cwd, signal: ctx.signal, onOutput: ctx.onOutput, runAs: env.runAs });
|
|
609
|
+
return { command, cwd: displayPath(env.roots, cwd), ...result };
|
|
610
|
+
}
|
|
611
|
+
|
|
612
|
+
async function systemInfo(_args, _ctx, env) {
|
|
613
|
+
const cpus = os.cpus();
|
|
614
|
+
let disk;
|
|
615
|
+
try {
|
|
616
|
+
const s = fs.statfsSync(env.roots[0]);
|
|
617
|
+
disk = { totalGB: +(s.bsize * s.blocks / 1024 ** 3).toFixed(1), freeGB: +(s.bsize * s.bavail / 1024 ** 3).toFixed(1) };
|
|
618
|
+
} catch { /* không đọc được dung lượng */ }
|
|
619
|
+
return {
|
|
620
|
+
platform: process.platform, release: os.release(), arch: os.arch(), hostname: os.hostname(),
|
|
621
|
+
cpu: cpus[0]?.model, cores: cpus.length, loadavg: os.loadavg(),
|
|
622
|
+
memoryMB: { total: Math.round(os.totalmem() / 1024 ** 2), free: Math.round(os.freemem() / 1024 ** 2) },
|
|
623
|
+
uptimeSec: Math.round(os.uptime()), disk, node: process.version, roots: env.roots, programs: env.binaries, projects: env.projects,
|
|
624
|
+
};
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
async function git(argv, args, ctx, env) {
|
|
628
|
+
const cwd = resolveInRoots(env.roots, args.path || '');
|
|
629
|
+
const res = await runProcess('git', ['-C', cwd, ...argv], { cwd, signal: ctx.signal, maxOutput: 512 * 1024, runAs: env.runAs });
|
|
630
|
+
return { cwd: displayPath(env.roots, cwd), ...res };
|
|
631
|
+
}
|
|
632
|
+
|
|
633
|
+
// ── memory (bộ nhớ trên máy) ────────────────────────────────────────────────────────────────────
|
|
634
|
+
|
|
635
|
+
function contextRecall(args, _ctx, env) {
|
|
636
|
+
const query = String(args.query || '');
|
|
637
|
+
const limit = Math.min(Number(args.limit) || 8, 30);
|
|
638
|
+
const memoryKinds = Object.values(MemoryKind).filter((k) => k !== MemoryKind.PROCEDURE);
|
|
639
|
+
const memory = memoryOf(env);
|
|
640
|
+
return {
|
|
641
|
+
memory: memory.search({ query, vector: args.vector, kinds: memoryKinds, limit }),
|
|
642
|
+
procedures: memory.search({ query, vector: args.vector, kinds: [MemoryKind.PROCEDURE], limit: 3 }),
|
|
643
|
+
files: env.fileIndex ? env.fileIndex.search(query, 10, args.vector).map(withoutAbs) : [],
|
|
644
|
+
projects: env.projects || [],
|
|
645
|
+
};
|
|
646
|
+
}
|
|
647
|
+
|
|
648
|
+
const writeLock = (key) => (args, env) => [resolveInRoots(env.roots, args[key] || '')];
|
|
649
|
+
|
|
650
|
+
/** Toàn bộ công cụ cho máy này — gói chỉ bật khi máy đủ điều kiện (`available`). */
|
|
651
|
+
export function buildTools(env) {
|
|
652
|
+
const hasGit = env.binaries?.includes('git');
|
|
653
|
+
const tools = [
|
|
654
|
+
{ name: 'fs.read', group: ToolGroup.FS_READ, read_only: true, handler: fsRead,
|
|
655
|
+
description: 'Read a text file by line range (streamed, works on huge files) or a byte range (base64 for binary). Default: first 1000 lines.',
|
|
656
|
+
input_schema: schema({ path: str('file path, relative to the device root'), startLine: num('1-based first line'), endLine: num('last line (max 5000 lines per call)'), byteOffset: num('byte offset for range reads'), byteLength: num('bytes to read (max 1 MB)'), encoding: str('utf8 | base64') }, ['path']) },
|
|
657
|
+
{ name: 'fs.read_many', group: ToolGroup.FS_READ, read_only: true, handler: fsReadMany,
|
|
658
|
+
description: 'Read the start of up to 20 files at once (parallel).',
|
|
659
|
+
input_schema: schema({ paths: { type: 'array', items: { type: 'string' }, description: 'file paths' }, maxLines: num('lines per file, default 400') }, ['paths']) },
|
|
660
|
+
{ name: 'fs.list', group: ToolGroup.FS_READ, read_only: true, handler: fsList,
|
|
661
|
+
description: 'List a folder; recursive up to maxDepth (default 3), skipping node_modules/.git/build folders. Filter by extension, name pattern, modified date, size; sort by name / modified / size — e.g. PDFs in Downloads older than 30 days, biggest first, in one call.',
|
|
662
|
+
input_schema: schema({
|
|
663
|
+
path: str('folder, default the root'), recursive: bool('walk subfolders'), maxDepth: num('max depth when recursive'), maxEntries: num('max entries, default 500'),
|
|
664
|
+
ext: str('extensions, comma separated, e.g. "pdf,docx"'), name: str('name pattern with *, e.g. "invoice*"'), modifiedAfter: str('ISO date or number of days ago'),
|
|
665
|
+
modifiedBefore: str('ISO date or number of days ago (e.g. "30" = older than 30 days)'), minSize: num('bytes'), maxSize: num('bytes'), filesOnly: bool('skip folders'),
|
|
666
|
+
sort: str('name | modified | size'), order: str('asc | desc'),
|
|
667
|
+
}) },
|
|
668
|
+
{ name: 'fs.find', group: ToolGroup.FS_READ, read_only: true, handler: fsFind,
|
|
669
|
+
description: 'Instant search over the on-device file index: file names, path words, identifiers near the top of files and the opening text of documents (docx/xlsx/pptx/txt), ranked by words AND meaning. Describe the file in natural words ("office lease contract 2026"); results include size, modified date and a preview. Bulk folders (screenshots, logs), app folders and code projects are one result each (type: folder - open them with fs.list / fs.grep). When the index has too few results, the operating system file search adds more (source: os). Use to locate files before reading.',
|
|
670
|
+
input_schema: schema({ query: str('what the file is about, in natural words'), limit: num('max results, default 15') }, ['query']) },
|
|
671
|
+
{ name: 'fs.index_folder', group: ToolGroup.FS_READ, read_only: true, handler: fsIndexFolder,
|
|
672
|
+
description: 'Make a folder a working folder: index it fully right now (including the code inside a git project) and keep it updated, so fs.find finds everything in it instantly. Call it when the user says where they work ("my project is in D:/work/shop", "work in this folder"). remove: true stops indexing it.',
|
|
673
|
+
input_schema: schema({ path: str('folder path'), remove: bool('stop treating it as a working folder') }, ['path']) },
|
|
674
|
+
{ name: 'fs.preview', group: ToolGroup.FS_READ, read_only: true, handler: fsPreview,
|
|
675
|
+
description: 'Preview up to 10 files at once: size, modified date and their opening text (also inside docx/xlsx/pptx). Use to tell close candidates apart before choosing one.',
|
|
676
|
+
input_schema: schema({ paths: { type: 'array', items: { type: 'string' }, description: 'file paths' }, maxChars: num('preview length per file, default 800') }, ['paths']) },
|
|
677
|
+
{ name: 'fs.grep', group: ToolGroup.FS_READ, read_only: true, handler: fsGrep,
|
|
678
|
+
description: 'Search file contents for a text (or regex) under a folder; uses ripgrep when installed.',
|
|
679
|
+
input_schema: schema({ query: str('text or regex'), path: str('folder, default the root'), regex: bool('treat query as a regex'), glob: str('file glob filter, e.g. *.ts'), maxResults: num('default 50') }, ['query']) },
|
|
680
|
+
{ name: 'fs.info', group: ToolGroup.FS_READ, read_only: true, handler: fsInfo,
|
|
681
|
+
description: 'Existence, size and dates of a file or folder.',
|
|
682
|
+
input_schema: schema({ path: str('path') }, ['path']) },
|
|
683
|
+
{ name: 'fs.write', group: ToolGroup.FS_WRITE, handler: fsWrite, lockKeys: writeLock('path'),
|
|
684
|
+
description: 'Create or overwrite a file (creates folders). append adds to the end. encoding base64 for binary content. The previous version is kept (fs.undo restores it).',
|
|
685
|
+
input_schema: schema({ path: str('file path'), content: str('full content'), append: bool('append instead of replace'), overwrite: bool('false = fail if the file exists'), encoding: str('utf8 | base64') }, ['path', 'content']) },
|
|
686
|
+
{ name: 'fs.edit', group: ToolGroup.FS_WRITE, handler: fsEdit, lockKeys: writeLock('path'),
|
|
687
|
+
description: 'Replace an exact text in a file (must be unique unless replaceAll).',
|
|
688
|
+
input_schema: schema({ path: str('file path'), oldText: str('exact text to replace'), newText: str('replacement'), replaceAll: bool('replace every occurrence') }, ['path', 'oldText', 'newText']) },
|
|
689
|
+
{ name: 'fs.move', group: ToolGroup.FS_WRITE, handler: fsMove, lockKeys: (a, e) => [...writeLock('sourcePath')(a, e), ...writeLock('destinationPath')(a, e)],
|
|
690
|
+
description: 'Move or rename one file or folder (several: fs.move_many). Undoable.',
|
|
691
|
+
input_schema: schema({ sourcePath: str('from'), destinationPath: str('to'), overwrite: bool('replace an existing destination (the replaced one is kept for undo)') }, ['sourcePath', 'destinationPath']) },
|
|
692
|
+
{ name: 'fs.copy', group: ToolGroup.FS_WRITE, handler: fsCopy, lockKeys: (a, e) => [...writeLock('destinationPath')(a, e)],
|
|
693
|
+
description: 'Copy one file or folder (the source stays). Creates missing folders; an existing destination is replaced only with overwrite. Undoable.',
|
|
694
|
+
input_schema: schema({ sourcePath: str('from'), destinationPath: str('to'), overwrite: bool('replace an existing destination (the replaced one is kept for undo)') }, ['sourcePath', 'destinationPath']) },
|
|
695
|
+
{ name: 'fs.move_many', group: ToolGroup.FS_WRITE, handler: fsMoveMany,
|
|
696
|
+
lockKeys: (a, e) => (Array.isArray(a.moves) ? a.moves.slice(0, MAX_BATCH_ITEMS) : []).flatMap((m) => { try { return [resolveInRoots(e.roots, m?.from || ''), resolveInRoots(e.roots, m?.to || '')]; } catch { return []; } }),
|
|
697
|
+
description: `Move / rename up to ${MAX_BATCH_ITEMS} files or folders in one call (organizing a folder): moves [{from, to}], folders are created. dry_run first checks every item and returns the plan without changing anything. Items that fail do not stop the others. The whole batch is undoable.`,
|
|
698
|
+
input_schema: schema({ moves: { type: 'array', items: { type: 'object', properties: { from: str('source'), to: str('destination path') } }, description: '[{from, to}]' }, overwrite: bool('replace existing destinations'), dry_run: bool('only check and show the plan') }, ['moves']) },
|
|
699
|
+
{ name: 'fs.delete', group: ToolGroup.FS_WRITE, destructive: true, handler: fsDelete, lockKeys: writeLock('path'),
|
|
700
|
+
description: 'Delete a file or folder (recursive). It goes to the recycle area and fs.undo brings it back; permanent: true deletes for good (only when the user asked for that).',
|
|
701
|
+
input_schema: schema({ path: str('path to delete'), permanent: bool('delete for good, not recoverable') }, ['path']) },
|
|
702
|
+
{ name: 'fs.delete_many', group: ToolGroup.FS_WRITE, destructive: true, handler: fsDeleteMany,
|
|
703
|
+
lockKeys: (a, e) => (Array.isArray(a.paths) ? a.paths.slice(0, MAX_BATCH_ITEMS) : []).flatMap((p) => { try { return [resolveInRoots(e.roots, p || '')]; } catch { return []; } }),
|
|
704
|
+
description: `Delete up to ${MAX_BATCH_ITEMS} files or folders in one call (recoverable with fs.undo unless permanent). One approval covers the batch.`,
|
|
705
|
+
input_schema: schema({ paths: { type: 'array', items: { type: 'string' }, description: 'paths to delete' }, permanent: bool('delete for good, not recoverable') }, ['paths']) },
|
|
706
|
+
{ name: 'fs.history', group: ToolGroup.FS_READ, read_only: true,
|
|
707
|
+
handler: (a, _c, e) => { if (!e.undo) throw undoUnavailable(); return { groups: e.undo.history(Math.min(Number(a.limit) || 10, 50)) }; },
|
|
708
|
+
description: 'Recent groups of file changes the AI made on this computer (one group per task): what changed, when, whether undone.',
|
|
709
|
+
input_schema: schema({ limit: num('default 10') }) },
|
|
710
|
+
{ name: 'fs.undo', group: ToolGroup.FS_WRITE,
|
|
711
|
+
handler: (a, _c, e) => { if (!e.undo) throw undoUnavailable(); return e.undo.undo(a.group, e.roots); },
|
|
712
|
+
description: 'Undo every file change of one group (default: the most recent group not yet undone): restores deleted and overwritten files, moves files back, removes files the AI created. Nothing the user changed since is overwritten.',
|
|
713
|
+
input_schema: schema({ group: str('group id from fs.history; default the latest') }) },
|
|
714
|
+
{ name: 'fs.measure', group: ToolGroup.FS_READ, read_only: true, internal: true, handler: fsMeasure,
|
|
715
|
+
description: 'BE-only: file count and size of paths about to be deleted (shown on the approval card).', input_schema: schema({}) },
|
|
716
|
+
{ name: 'shell.exec', group: ToolGroup.EXEC, handler: shellExec,
|
|
717
|
+
description: `Run a command in ${process.platform === 'win32' ? 'PowerShell' : 'the login shell'} inside an allowed folder; returns exitCode/stdout/stderr. Secrets are removed from the environment. Set timeoutMs for long builds (default 60000).`,
|
|
718
|
+
input_schema: schema({ command: str('command line'), cwd: str('working folder, default the root'), timeoutMs: num('time limit in ms (max 600000)') }, ['command']) },
|
|
719
|
+
{ name: 'system.info', group: ToolGroup.SYSTEM, read_only: true, handler: systemInfo,
|
|
720
|
+
description: 'OS, CPU, memory, disk free space, installed programs and detected projects.',
|
|
721
|
+
input_schema: schema({}) },
|
|
722
|
+
{ name: 'memory.search', group: ToolGroup.MEMORY, read_only: true, handler: (a, _c, e) => ({ items: memoryOf(e).search({ query: a.query, kinds: a.kinds, limit: Math.min(Number(a.limit) || 10, 50) }) }),
|
|
723
|
+
description: "Search this device's long-term memory (facts, projects, rules, lessons, procedures) by words.",
|
|
724
|
+
input_schema: schema({ query: str('words'), kinds: { type: 'array', items: { type: 'string' }, description: 'fact | project | rule | lesson | procedure' }, limit: num('default 10') }, ['query']) },
|
|
725
|
+
{ name: 'memory.get', group: ToolGroup.MEMORY, read_only: true, handler: (a, _c, e) => memoryOf(e).get(a) || { found: false },
|
|
726
|
+
description: 'Get one memory item by id, or by kind + key.',
|
|
727
|
+
input_schema: schema({ id: str('item id'), kind: str('kind'), key: str('key') }) },
|
|
728
|
+
{ name: 'memory.list', group: ToolGroup.MEMORY, read_only: true, handler: (a, _c, e) => memoryOf(e).list(a),
|
|
729
|
+
description: 'Page through memory items (newest first); pass next_cursor to continue.',
|
|
730
|
+
input_schema: schema({ kind: str('optional kind filter'), cursor: num('from next_cursor'), limit: num('default 50') }) },
|
|
731
|
+
{ name: 'memory.delete', group: ToolGroup.MEMORY, handler: (a, _c, e) => memoryOf(e).delete(a),
|
|
732
|
+
description: 'Forget memory items by id (or kind + key).',
|
|
733
|
+
input_schema: schema({ ids: { type: 'array', items: { type: 'string' }, description: 'item ids' }, kind: str('kind'), key: str('key') }) },
|
|
734
|
+
{ name: 'context.recall', group: ToolGroup.MEMORY, read_only: true, internal: true, handler: contextRecall,
|
|
735
|
+
description: 'BE-only: hybrid recall of memory, procedures and files for an objective.', input_schema: schema({}) },
|
|
736
|
+
{ name: 'memory.put', group: ToolGroup.MEMORY, internal: true, handler: (a, _c, e) => memoryOf(e).put(a.items),
|
|
737
|
+
description: 'BE-only: upsert memory items with vectors.', input_schema: schema({}) },
|
|
738
|
+
{ name: 'notify.show', group: ToolGroup.SYSTEM, internal: true, handler: (a) => showOSNotification(a),
|
|
739
|
+
description: 'BE-only: OS notification when the AI needs the user (title, body, url opened on click).', input_schema: schema({}) },
|
|
740
|
+
];
|
|
741
|
+
if (hasGit) {
|
|
742
|
+
tools.push(
|
|
743
|
+
{ name: 'git.status', group: ToolGroup.GIT, read_only: true, handler: (a, c, e) => git(['status', '--porcelain=v1', '--branch'], a, c, e),
|
|
744
|
+
description: 'Branch and changed files of a git repository.', input_schema: schema({ path: str('repository folder, default the root') }) },
|
|
745
|
+
{ name: 'git.diff', group: ToolGroup.GIT, read_only: true, handler: (a, c, e) => git(['diff', ...(a.staged ? ['--staged'] : []), '--stat', '--patch', '--no-color', ...(a.file ? ['--', String(a.file)] : [])], a, c, e),
|
|
746
|
+
description: 'Uncommitted changes (patch) of a repository or one file.', input_schema: schema({ path: str('repository folder'), file: str('limit to one file'), staged: bool('show staged changes') }) },
|
|
747
|
+
{ name: 'git.log', group: ToolGroup.GIT, read_only: true, handler: (a, c, e) => git(['log', `-${Math.min(Number(a.limit) || 20, 200)}`, '--pretty=format:%h %ad %an %s', '--date=short'], a, c, e),
|
|
748
|
+
description: 'Recent commits of a repository.', input_schema: schema({ path: str('repository folder'), limit: num('default 20') }) },
|
|
749
|
+
);
|
|
750
|
+
}
|
|
751
|
+
// Trình duyệt cho AI Browser (máy có Chrome / Edge) — BE gọi thẳng, không vào danh mục của Planner.
|
|
752
|
+
if (env.browserTunnels) {
|
|
753
|
+
tools.push(
|
|
754
|
+
{ name: 'browser.open_tunnel', group: ToolGroup.BROWSER, internal: true, handler: (a, c) => env.browserTunnels.open(a, c),
|
|
755
|
+
description: "BE-only: open (or reuse) Aivin's own browser window on this device and connect a CDP tunnel for one AI Browser task.", input_schema: schema({}) },
|
|
756
|
+
{ name: 'browser.read_download', group: ToolGroup.BROWSER, read_only: true, internal: true, handler: (a, c) => env.browserTunnels.readDownload(a, c),
|
|
757
|
+
description: "BE-only: read a byte range of a file the AI downloaded in that window (only inside Aivin's downloads folder).", input_schema: schema({}) },
|
|
758
|
+
);
|
|
759
|
+
}
|
|
760
|
+
// Điều khiển giao diện (Windows, CLI ≥ 1.0.9) — chỉ khi máy có màn hình tương tác và không tắt bằng --no-gui.
|
|
761
|
+
if (env.gui) tools.push(...buildGuiTools(env.gui));
|
|
762
|
+
// Excel / Word / Outlook có trên máy → làm qua API của ứng dụng (tự phát hiện, không cấu hình).
|
|
763
|
+
if (env.office?.apps?.length) tools.push(...buildOfficeTools(env.office.host, env.office.apps));
|
|
764
|
+
// Tiến trình nền + đọc log thời gian thực (dev server, build watch, claude -p, tail log).
|
|
765
|
+
if (env.processes) tools.push(...buildProcessTools(env.processes));
|
|
766
|
+
// Giao việc cho agent lập trình trên máy (Claude Code…, chế độ không giao diện, có phiên nói tiếp) — máy cá nhân có cài ít nhất một agent.
|
|
767
|
+
if (env.processes && env.schedules && !env.runAs) {
|
|
768
|
+
sharedAgents ||= env.codingAgents || createAgentRunner();
|
|
769
|
+
if (sharedAgents.installed().length) tools.push(...buildAgentTools(sharedAgents));
|
|
770
|
+
}
|
|
771
|
+
// Lịch chạy định kỳ (Task Scheduler / crontab) — máy cá nhân; máy tính tổ chức không đặt lịch cho thành viên.
|
|
772
|
+
if (env.schedules) tools.push(...buildScheduleTools(env.schedules));
|
|
773
|
+
// Tệp lớn hơn trần socket: HTTP thẳng với vé của BE (chỉ BE gọi).
|
|
774
|
+
if (env.transfer) tools.push(...buildTransferTools(env.transfer));
|
|
775
|
+
// Theo dõi trên máy kích hoạt việc của Aivin (tệp mới, dòng log) — BE đặt danh sách.
|
|
776
|
+
if (env.watches) tools.push(...buildWatchTools(env.watches));
|
|
777
|
+
// Ghi chú cuộc họp (ghi âm máy + micro, chuyển chữ sau khi họp) + chụp màn hình — Windows, máy cá nhân.
|
|
778
|
+
if (env.meetings || env.media) tools.push(...buildMeetingTools({ meetings: env.meetings, media: env.media }));
|
|
779
|
+
// Clipboard (chữ; Windows thêm ảnh + tệp đã copy) — máy cá nhân có màn hình.
|
|
780
|
+
if (env.clipboard) tools.push(...buildClipboardTools(env.clipboard));
|
|
781
|
+
// Máy tính tổ chức không lập chỉ mục tệp (nhiều người chung một máy) — Planner tìm bằng fs.list / fs.grep trong thư mục của mình.
|
|
782
|
+
return env.fileIndex ? tools : tools.filter((t) => t.name !== 'fs.find' && t.name !== 'fs.index_folder');
|
|
783
|
+
}
|
|
784
|
+
|
|
785
|
+
/** Bảng tra theo tên cho bộ điều phối. */
|
|
786
|
+
export function toolMap(tools) {
|
|
787
|
+
return new Map(tools.map((t) => [t.name, t]));
|
|
788
|
+
}
|