@aivin-labs/cli 1.0.13 → 1.0.24

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.
Files changed (73) hide show
  1. package/README.md +325 -304
  2. package/bin/cli.mjs +97 -18
  3. package/bin/lib/localPreview.mjs +437 -0
  4. package/bin/lib/openFile.mjs +235 -0
  5. package/bin/lib/previewCache.mjs +71 -0
  6. package/bin/lib/remote/atomicFile.mjs +32 -0
  7. package/bin/lib/remote/autoStart.mjs +2 -1
  8. package/bin/lib/remote/autoUpdate.mjs +153 -129
  9. package/bin/lib/remote/callLedger.mjs +21 -0
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -2
  11. package/bin/lib/remote/client.mjs +1025 -889
  12. package/bin/lib/remote/codingAgents.mjs +2 -2
  13. package/bin/lib/remote/constants.mjs +263 -251
  14. package/bin/lib/remote/credentials.mjs +81 -4
  15. package/bin/lib/remote/daemonLock.mjs +57 -17
  16. package/bin/lib/remote/desktop/castInput.mjs +98 -0
  17. package/bin/lib/remote/desktop/desktopCast.mjs +337 -198
  18. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
  19. package/bin/lib/remote/desktop/desktopCastSource.mjs +880 -514
  20. package/bin/lib/remote/desktop/desktopWebRtc.mjs +251 -95
  21. package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
  22. package/bin/lib/remote/desktop/index.mjs +21 -7
  23. package/bin/lib/remote/desktop/linuxTraySource.mjs +1 -8
  24. package/bin/lib/remote/desktop/macTraySource.mjs +0 -2
  25. package/bin/lib/remote/desktop/strings.mjs +28 -2
  26. package/bin/lib/remote/desktop/traySource.mjs +380 -16
  27. package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
  28. package/bin/lib/remote/desktop/webrtcWorker.mjs +183 -0
  29. package/bin/lib/remote/deviceProfile.mjs +2 -4
  30. package/bin/lib/remote/fileIndexer.mjs +30 -14
  31. package/bin/lib/remote/folderRules.mjs +3 -0
  32. package/bin/lib/remote/gitSafe.mjs +31 -0
  33. package/bin/lib/remote/gui/index.mjs +66 -24
  34. package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
  35. package/bin/lib/remote/gui/windowsHost.mjs +3 -1
  36. package/bin/lib/remote/gui/windowsHostSource.mjs +291 -60
  37. package/bin/lib/remote/httpTransfer.mjs +64 -3
  38. package/bin/lib/remote/localPolicy.mjs +73 -7
  39. package/bin/lib/remote/mascot/ask.mjs +956 -768
  40. package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
  41. package/bin/lib/remote/mascot/askHostSource.mjs +658 -530
  42. package/bin/lib/remote/mascot/blocks.mjs +201 -0
  43. package/bin/lib/remote/mascot/bot.mjs +26 -2
  44. package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
  45. package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
  46. package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
  47. package/bin/lib/remote/mascot/fileChips.mjs +62 -0
  48. package/bin/lib/remote/mascot/hostSource.mjs +328 -49
  49. package/bin/lib/remote/mascot/hotkey.mjs +31 -7
  50. package/bin/lib/remote/mascot/images.mjs +111 -0
  51. package/bin/lib/remote/mascot/index.mjs +663 -493
  52. package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
  53. package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
  54. package/bin/lib/remote/mascot/mood.mjs +57 -0
  55. package/bin/lib/remote/mascot/rigSource.mjs +643 -609
  56. package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
  57. package/bin/lib/remote/mascot/strings.mjs +459 -375
  58. package/bin/lib/remote/mascot/ui.mjs +27 -7
  59. package/bin/lib/remote/multiUser.mjs +7 -2
  60. package/bin/lib/remote/notify.mjs +4 -1
  61. package/bin/lib/remote/office/index.mjs +12 -6
  62. package/bin/lib/remote/processes.mjs +5 -2
  63. package/bin/lib/remote/sandbox.mjs +26 -0
  64. package/bin/lib/remote/secretPaths.mjs +21 -0
  65. package/bin/lib/remote/tokenRotation.mjs +28 -0
  66. package/bin/lib/remote/toolHandlers.mjs +79 -15
  67. package/bin/lib/remote/watchBatcher.mjs +56 -0
  68. package/bin/lib/selfUpdate.mjs +12 -2
  69. package/bin/lib/update/binarySwap.mjs +15 -1
  70. package/bin/lib/update/state.mjs +10 -0
  71. package/docs/CLI.md +1545 -1504
  72. package/docs/media/aivin-ecosystem.jpg +0 -0
  73. package/package.json +75 -71
@@ -0,0 +1,183 @@
1
+ import net from 'net';
2
+ import readline from 'readline';
3
+ import { spawn } from 'child_process';
4
+ import { createDesktopWebRtc } from './desktopWebRtc.mjs';
5
+ import { createRawFrameReader } from './desktopCast.mjs';
6
+ import { createWebRtcRuntimeLoader } from './webrtcRuntime.mjs';
7
+
8
+ /**
9
+ * WebRTC của Desktop Scenecast chạy trong TIẾN TRÌNH CON riêng (`aivin __desktop-webrtc-worker`): thư viện native `@roamhq/wrtc` làm
10
+ * tiến trình sập lúc thoát (Bun: mọi cách thoát; Node: thoát tự nhiên — đo 02/11/2026). Ở tiến trình con thì sập không ảnh hưởng mã
11
+ * thoát của daemon (trình giữ chạy / tự lùi bản dựa vào mã đó), và lỗi native giữa phiên chỉ làm mất WebRTC (lùi JPEG), không mất daemon.
12
+ *
13
+ * Giao thức: mỗi dòng stdin / stdout một JSON.
14
+ * daemon → con: `start {sessionId, viewerId, iceServers, videoBitrate}` ·`signal {msg}` · `push {frame}` · `pipe {name}` · `close {viewerId}` · `closeAll`
15
+ * daemon → con (con trỏ): `cursor {cursor}` · `cursorShape {shape}`
16
+ * con → daemon: `started {viewerId, ok}` · `signal {payload}` · `status {payload}` · `input {raw, viewerId}` · `peerReady {viewerId}` ·
17
+ * `state {needsFallback, needsJpeg, hasVideo, videoLive, localCursor}` · `log {text}`
18
+ * Khung thô I420 không đi qua daemon: con tự nối named pipe của tiến trình quay.
19
+ */
20
+
21
+ export const DESKTOP_WEBRTC_WORKER_ARG = '__desktop-webrtc-worker';
22
+ const VIDEO_LIVE_MS = 3000;
23
+
24
+ export async function runDesktopWebRtcWorker({ input = process.stdin, output = process.stdout } = {}) {
25
+ const send = (msg) => { try { output.write(JSON.stringify(msg) + '\n'); } catch { /* daemon đã đóng */ } };
26
+ let lastRawAt = 0;
27
+ let lastState = '';
28
+ let rtc;
29
+ const sendState = () => {
30
+ const state = {
31
+ needsFallback: rtc.needsFallback(), needsJpeg: rtc.needsJpeg(), hasVideo: rtc.hasVideo(), videoLive: Date.now() - lastRawAt < VIDEO_LIVE_MS, localCursor: rtc.localCursor(),
32
+ };
33
+ const key = JSON.stringify(state);
34
+ if (key !== lastState) { lastState = key; send({ t: 'state', ...state }); }
35
+ };
36
+ rtc = createDesktopWebRtc({
37
+ emitSignal: (payload) => send({ t: 'signal', payload }),
38
+ emitStatus: (payload) => { send({ t: 'status', payload }); sendState(); },
39
+ onInput: (raw, viewerId) => send({ t: 'input', raw, viewerId }),
40
+ onPeerReady: (viewerId) => { send({ t: 'peerReady', viewerId }); sendState(); },
41
+ onCursorMode: () => sendState(),
42
+ loadRuntime: createWebRtcRuntimeLoader({ log: (text) => send({ t: 'log', text }) }),
43
+ });
44
+
45
+ let pipeSocket = null;
46
+ let pipeName = '';
47
+ const connectPipe = (name, attempt = 0) => {
48
+ if (attempt === 0 && name === pipeName && pipeSocket) return;
49
+ pipeName = name;
50
+ pipeSocket?.destroy();
51
+ const sock = net.connect(`\\\\.\\pipe\\${name}`);
52
+ const read = createRawFrameReader((frame) => { if (rtc.pushRaw(frame)) lastRawAt = Date.now(); }, () => sock.destroy());
53
+ sock.on('data', read);
54
+ sock.on('error', () => {});
55
+ sock.on('close', () => {
56
+ if (pipeSocket !== sock) return;
57
+ pipeSocket = null;
58
+ if (attempt < 20) setTimeout(() => { if (!pipeSocket) connectPipe(name, attempt + 1); }, Math.min(2000, 100 * 2 ** attempt));
59
+ });
60
+ pipeSocket = sock;
61
+ };
62
+ const stateTimer = setInterval(sendState, 1000);
63
+
64
+ const handlers = {
65
+ start: async (m) => {
66
+ const ok = await rtc.start({ sessionId: m.sessionId, viewerId: m.viewerId, iceServers: m.iceServers || [], videoBitrate: m.videoBitrate || null }).catch(() => false);
67
+ send({ t: 'started', viewerId: m.viewerId, ok });
68
+ sendState();
69
+ },
70
+ signal: (m) => rtc.signal(m.msg).catch(() => false),
71
+ push: (m) => rtc.push(m.frame),
72
+ cursor: (m) => rtc.pushCursor(m.cursor),
73
+ cursorShape: (m) => rtc.pushCursorShape(m.shape),
74
+ inputFocus: (m) => rtc.pushInputFocus(m.focus),
75
+ pipe: (m) => { if (m.name) connectPipe(String(m.name)); },
76
+ close: (m) => { rtc.close(m.viewerId); sendState(); },
77
+ closeAll: () => { rtc.closeAll(); const sock = pipeSocket; pipeSocket = null; pipeName = ''; sock?.destroy(); sendState(); },
78
+ };
79
+ const rl = readline.createInterface({ input });
80
+ rl.on('line', (line) => {
81
+ let msg;
82
+ try { msg = JSON.parse(line); } catch { return; }
83
+ void Promise.resolve(handlers[msg?.t]?.(msg)).catch(() => undefined);
84
+ });
85
+ // Daemon thoát / đóng ống → con thoát theo (Windows không tự giết con khi cha chết).
86
+ await new Promise((resolve) => rl.on('close', resolve));
87
+ clearInterval(stateTimer);
88
+ rtc.closeAll();
89
+ process.exit(0);
90
+ }
91
+
92
+ /**
93
+ * Phía daemon: cùng API với createDesktopWebRtc (start / signal / push / needsFallback / needsJpeg / hasVideo / close / closeAll) + `attachPipe`
94
+ * và `videoLive`. Tiến trình con dựng khi phiên đầu cần, tắt khi `closeAll`; con chết giữa phiên → coi như không ai có WebRTC (lùi JPEG).
95
+ */
96
+ export function createDesktopWebRtcWorker({
97
+ command, emitSignal = () => {}, emitStatus = () => {}, onInput = () => {}, onPeerReady = () => {}, onState = () => {}, log = () => {}, spawnImpl = spawn,
98
+ } = {}) {
99
+ let child = null;
100
+ const NO_PEER_STATE = { needsFallback: true, needsJpeg: true, hasVideo: false, videoLive: false, localCursor: false };
101
+ let state = NO_PEER_STATE;
102
+ const waiting = new Map();
103
+ const peers = new Set();
104
+
105
+ const ensure = () => {
106
+ if (child) return child;
107
+ const [exe, ...args] = command;
108
+ const proc = spawnImpl(exe, [...args, DESKTOP_WEBRTC_WORKER_ARG], { stdio: ['pipe', 'pipe', 'ignore'], windowsHide: true });
109
+ child = proc;
110
+ readline.createInterface({ input: proc.stdout }).on('line', (line) => {
111
+ let m;
112
+ try { m = JSON.parse(line); } catch { return; }
113
+ if (m.t === 'signal') emitSignal(m.payload);
114
+ else if (m.t === 'status') emitStatus(m.payload);
115
+ else if (m.t === 'input') onInput(m.raw, m.viewerId);
116
+ else if (m.t === 'peerReady') onPeerReady(m.viewerId);
117
+ else if (m.t === 'state') {
118
+ state = { needsFallback: !!m.needsFallback, needsJpeg: !!m.needsJpeg, hasVideo: !!m.hasVideo, videoLive: !!m.videoLive, localCursor: !!m.localCursor };
119
+ onState();
120
+ }
121
+ else if (m.t === 'log') log(String(m.text || ''));
122
+ else if (m.t === 'started') { waiting.get(m.viewerId)?.(!!m.ok); waiting.delete(m.viewerId); }
123
+ });
124
+ const gone = () => {
125
+ if (child !== proc) return;
126
+ child = null;
127
+ state = NO_PEER_STATE;
128
+ onState();
129
+ for (const done of waiting.values()) done(false);
130
+ waiting.clear();
131
+ peers.clear();
132
+ };
133
+ proc.on('exit', gone);
134
+ proc.on('error', gone);
135
+ proc.stdin.on('error', () => {});
136
+ return proc;
137
+ };
138
+ const send = (msg) => {
139
+ if (!child?.stdin?.writable) return;
140
+ try { child.stdin.write(JSON.stringify(msg) + '\n'); } catch { /* con vừa chết */ }
141
+ };
142
+
143
+ function start({ sessionId, viewerId, iceServers = [], videoBitrate = null }) {
144
+ ensure();
145
+ peers.add(viewerId);
146
+ return new Promise((resolve) => {
147
+ const timer = setTimeout(() => { waiting.delete(viewerId); resolve(false); }, 30_000);
148
+ timer.unref?.();
149
+ waiting.set(viewerId, (ok) => { clearTimeout(timer); resolve(ok); });
150
+ send({ t: 'start', sessionId, viewerId, iceServers, videoBitrate });
151
+ });
152
+ }
153
+
154
+ function closeAll() {
155
+ peers.clear();
156
+ if (!child) return;
157
+ const proc = child;
158
+ send({ t: 'closeAll' });
159
+ try { proc.stdin.end(); } catch { /* đã đóng */ }
160
+ // Con tự thoát khi stdin đóng; kẹt thì giết.
161
+ setTimeout(() => { try { proc.kill(); } catch { /* đã thoát */ } }, 3000).unref?.();
162
+ child = null;
163
+ state = NO_PEER_STATE;
164
+ }
165
+
166
+ return {
167
+ start,
168
+ signal: async (msg) => { send({ t: 'signal', msg }); return true; },
169
+ push: (frame) => { if (child && peers.size) send({ t: 'push', frame }); },
170
+ pushCursor: (cursor) => { if (child && peers.size) send({ t: 'cursor', cursor }); },
171
+ // Hình gửi cả khi chưa có người xem: bộ quay chỉ gửi mỗi hình một lần, tiến trình con giữ lại cho người xem sau.
172
+ pushCursorShape: (shape) => { if (child) send({ t: 'cursorShape', shape }); },
173
+ pushInputFocus: (focus) => { if (child && peers.size) send({ t: 'inputFocus', focus }); },
174
+ attachPipe: (name) => { if (name) send({ t: 'pipe', name }); },
175
+ close: (viewerId) => { peers.delete(viewerId); send({ t: 'close', viewerId }); },
176
+ closeAll,
177
+ needsFallback: () => state.needsFallback,
178
+ needsJpeg: () => state.needsJpeg,
179
+ hasVideo: () => state.hasVideo,
180
+ videoLive: () => state.videoLive,
181
+ localCursor: () => state.localCursor,
182
+ };
183
+ }
@@ -2,14 +2,12 @@ import fs from 'fs';
2
2
  import os from 'os';
3
3
  import path from 'path';
4
4
  import { createHash } from 'crypto';
5
- import { createRequire } from 'module';
5
+ import { currentCliVersion } from '../update/versions.mjs';
6
6
  import { IGNORED_DIRS } from './constants.mjs';
7
7
  import { isProtectedPath } from './sandbox.mjs';
8
8
 
9
9
  export { REMOTE_CONFIG_DIR } from './constants.mjs';
10
10
 
11
- const require = createRequire(import.meta.url);
12
- const CLI_VERSION = (() => { try { return require('../../../package.json').version; } catch { return 'unknown'; } })();
13
11
 
14
12
  /** Chương trình đáng biết trên máy — có thì Planner dùng được, và gói công cụ tương ứng (git…) được bật. */
15
13
  const KNOWN_BINARIES = [
@@ -119,7 +117,7 @@ export function buildDeviceProfile(roots) {
119
117
  shell: detectShell(),
120
118
  os: detectOs(),
121
119
  node_version: process.version,
122
- cli_version: CLI_VERSION,
120
+ cli_version: currentCliVersion(),
123
121
  roots: roots.map((r) => path.resolve(r)),
124
122
  binaries: detectBinaries(),
125
123
  projects: detectProjects(roots),
@@ -7,6 +7,7 @@ import { cloudOnlyFiles, inCloudFolder } from './cloudFiles.mjs';
7
7
  import { extractDocText, isDocFile, wellFormed } from './docText.mjs';
8
8
  import { FolderKind, classifyDir, folderSummary, skipDir, skipFile } from './folderRules.mjs';
9
9
  import { isProtectedPath } from './sandbox.mjs';
10
+ import { createWatchBatcher } from './watchBatcher.mjs';
10
11
  import { openSqlite } from './sqliteDb.mjs';
11
12
  import { decodeInt8, int8Cosine, tokenize } from './textIndex.mjs';
12
13
 
@@ -39,6 +40,10 @@ const MAX_HEAD_FILE_BYTES = 2 * 1024 * 1024;
39
40
  const MAX_IDENTIFIERS = 200;
40
41
  const STAT_CONCURRENCY = 64;
41
42
  const WATCH_DEBOUNCE_MS = 800;
43
+ /** Lô theo dõi chạy chậm nhất sau chừng này kể từ sự kiện đầu (tệp bị ghi liên tục không giữ lô mãi) — 02/11/2026. */
44
+ const WATCH_MAX_WAIT_MS = 5_000;
45
+ /** Quá chừng này đường dẫn chờ → bỏ danh sách, quét lại tăng dần cả cây. */
46
+ const WATCH_MAX_PENDING = 5_000;
42
47
  /** Từ trong câu hỏi dài từ chừng này trở lên thì khớp cả tiền tố ("auth" ↔ "authentication"). */
43
48
  const PREFIX_MIN = 4;
44
49
  /** Số vector đọc mỗi lần khi tìm theo nghĩa. */
@@ -481,12 +486,20 @@ export function createFileIndex(roots) {
481
486
  * Tệp bộ theo dõi báo đổi: có lập chỉ mục không, và có nằm trong kho git không. null = bỏ (thư mục ẩn / rác, tệp tạm, trong thư mục ứng
482
487
  * dụng, tệp không phải tài liệu trong thư mục hàng loạt hay kho git).
483
488
  */
484
- function ruleFor(abs) {
489
+ /** Phần rẻ của `ruleFor` (không duyệt danh sách thư mục gộp): thư mục / tệp gốc của đường dẫn, null = bỏ ngay. */
490
+ function watchBase(abs) {
485
491
  const folder = indexFolders.filter((d) => within(d, abs)).sort((a, b) => b.length - a.length)[0];
486
492
  const base = folder || resolvedRoots.find((r) => within(r, abs));
487
493
  if (!base || isProtectedPath(abs)) return null;
488
494
  const segs = path.relative(base, abs).split(path.sep);
489
495
  if (segs.slice(0, -1).some((d) => skipDir(d, activeExcludes)) || skipFile(segs[segs.length - 1], activeExcludes)) return null;
496
+ return { base, folder };
497
+ }
498
+
499
+ function ruleFor(abs) {
500
+ const hit = watchBase(abs);
501
+ if (!hit) return null;
502
+ const { base, folder } = hit;
490
503
  let repo = false;
491
504
  for (const c of collapsed) {
492
505
  // Chỉ thư mục gộp nằm GIỮA gốc và tệp; gộp bao trùm cả gốc (thư mục làm việc nằm trong một kho git…) không tính.
@@ -499,13 +512,15 @@ export function createFileIndex(roots) {
499
512
  return { repo };
500
513
  }
501
514
 
502
- function watchDir(dir, pending, flush, fallBackToRescan) {
515
+ function watchDir(dir, fallBackToRescan) {
503
516
  if (watchers.has(dir)) return;
504
517
  try {
505
518
  const w = fs.watch(dir, { recursive: true }, (_event, name) => {
506
519
  if (!name) return;
507
- pending.add(path.join(dir, String(name)));
508
- flush();
520
+ const abs = path.join(dir, String(name));
521
+ // Lọc ngay (thư mục ẩn / rác / node_modules…, 02/11/2026): sự kiện của đường bị bỏ không giữ lô chờ, không vào tập chờ.
522
+ if (!watchBase(abs)) return;
523
+ batcher?.add(abs);
509
524
  });
510
525
  // Không có listener 'error' thì lỗi của bộ theo dõi (gốc bị xoá, rút ổ ngoài, hết inotify) ném ra ngoài và làm sập daemon.
511
526
  w.on('error', () => {
@@ -519,14 +534,11 @@ export function createFileIndex(roots) {
519
534
  }
520
535
 
521
536
  let rewatch = () => {};
537
+ let batcher = null;
522
538
 
523
539
  function watch() {
524
540
  watching = true;
525
- const pending = new Set();
526
- let timer;
527
- const run = async () => {
528
- const batch = [...pending];
529
- pending.clear();
541
+ const run = async (batch) => {
530
542
  const cloud = [];
531
543
  await mapLimit(batch, STAT_CONCURRENCY, async (abs) => {
532
544
  const rule = ruleFor(abs);
@@ -536,10 +548,12 @@ export function createFileIndex(roots) {
536
548
  await refreshCloud(cloud);
537
549
  scheduleVectorize(5_000);
538
550
  };
539
- const flush = () => {
540
- clearTimeout(timer);
541
- timer = setTimeout(() => void run(), WATCH_DEBOUNCE_MS);
542
- };
551
+ // Có trần chờ (maxWait) + trần cỡ tập chờ: quá → quét lại tăng dần cả cây thay vì giữ hàng chục nghìn đường dẫn (watchBatcher.mjs).
552
+ batcher?.close();
553
+ batcher = createWatchBatcher({
554
+ debounceMs: WATCH_DEBOUNCE_MS, maxWaitMs: WATCH_MAX_WAIT_MS, maxPending: WATCH_MAX_PENDING,
555
+ onBatch: run, onOverflow: () => build().catch(() => undefined),
556
+ });
543
557
  const fallBackToRescan = () => {
544
558
  // Bộ theo dõi hỏng: chuyển sang quét lại định kỳ (tăng dần — chỉ đọc tệp có mtime / size đổi).
545
559
  if (rescanTimer) return;
@@ -549,7 +563,7 @@ export function createFileIndex(roots) {
549
563
  rewatch = () => {
550
564
  const want = [...resolvedRoots, ...indexFolders.filter((d) => !resolvedRoots.some((r) => within(r, d)))];
551
565
  for (const [dir, w] of watchers) if (!want.includes(dir)) { try { w.close(); } catch { /* đã đóng */ } watchers.delete(dir); }
552
- for (const dir of want) watchDir(dir, pending, flush, fallBackToRescan);
566
+ for (const dir of want) watchDir(dir, fallBackToRescan);
553
567
  };
554
568
  rewatch();
555
569
  // `aivin remote index add|remove` (tiến trình khác) sửa danh sách → quét lại tăng dần.
@@ -655,6 +669,8 @@ export function createFileIndex(roots) {
655
669
  if (rescanTimer) { clearInterval(rescanTimer); rescanTimer = null; }
656
670
  for (const w of watchers.values()) { try { w.close(); } catch { /* đã đóng */ } }
657
671
  watchers.clear();
672
+ batcher?.close();
673
+ batcher = null;
658
674
  if (watching) {
659
675
  fs.unwatchFile(INDEX_FOLDERS_FILE);
660
676
  fs.unwatchFile(INDEX_EXCLUDES_FILE);
@@ -2,6 +2,7 @@ import fs from 'fs';
2
2
  import path from 'path';
3
3
  import { IGNORED_DIRS } from './constants.mjs';
4
4
  import { isDocFile } from './docText.mjs';
5
+ import { isSecretPath } from './secretPaths.mjs';
5
6
 
6
7
  /**
7
8
  * Quy tắc lập chỉ mục: bỏ gì, gộp gì (31/10/2026). Đo trên máy thật: 88% tệp trong thư mục ẩn, rồi 87% phần còn lại là ảnh chụp màn hình
@@ -60,6 +61,8 @@ export function skipFile(name, extraExcludes) {
60
61
  if (SKIP_FILE_NAMES.has(lower) || lower.startsWith('ntuser.dat')) return true;
61
62
  if (SKIP_FILE_EXT.has(path.extname(lower))) return true;
62
63
  if (lower.endsWith('.min.js') || lower.endsWith('.min.css') || lower.endsWith('.d.ts.map')) return true;
64
+ // Khoá riêng, kho mật khẩu…: chỉ mục giữ đoạn xem trước nội dung tệp.
65
+ if (isSecretPath(lower)) return true;
63
66
  if (extraExcludes && (extraExcludes.has(name) || extraExcludes.has(lower))) return true;
64
67
  return false;
65
68
  }
@@ -0,0 +1,31 @@
1
+ /**
2
+ * `git.*` CHỈ ĐỌC chạy an toàn trên kho lạ (02/11/2026). Cấu hình của kho (`.git/config` — agent ghi được bằng fs.write / shell, hoặc kho tải
3
+ * về) chạy được chương trình tuỳ ý ngay trong `git status` / `git diff` / `git log`: `core.fsmonitor`, `diff.external`, `diff.<x>.textconv`,
4
+ * hook `post-index-change` khi git làm mới chỉ mục… Công cụ chỉ đọc không được hỏi xác nhận nên đây là đường chạy mã lách sàn luật.
5
+ * - `--no-optional-locks`: status không ghi lại chỉ mục (không có hook ghi chỉ mục);
6
+ * - `-c core.fsmonitor=false`, `-c core.hooksPath=<thiết bị rỗng>`: không chạy fsmonitor, không tìm thấy hook nào (áp cả cho kho con);
7
+ * - diff / show / log thêm `--no-ext-diff --no-textconv`;
8
+ * - bỏ mọi biến môi trường `GIT_*` của tiến trình (GIT_EXTERNAL_DIFF, GIT_SSH_COMMAND, GIT_CONFIG_*, GIT_DIR…), tắt hỏi mật khẩu.
9
+ * Còn hở: `filter.<x>.clean` (kho tự khai bộ lọc qua `.gitattributes` + cấu hình) có thể chạy khi so tệp đang sửa — xem file-operations.md.
10
+ */
11
+
12
+ const NULL_DEVICE = process.platform === 'win32' ? 'NUL' : '/dev/null';
13
+ const DIFF_LIKE = new Set(['diff', 'show', 'log']);
14
+
15
+ /** argv cho `git` (đã gồm `-C <cwd>`), `sub` = lệnh con và tham số của nó. */
16
+ export function safeGitArgv(cwd, sub, { nullDevice = NULL_DEVICE } = {}) {
17
+ const [cmd, ...rest] = sub;
18
+ const hardened = DIFF_LIKE.has(cmd) ? [cmd, '--no-ext-diff', '--no-textconv', ...rest] : [cmd, ...rest];
19
+ // `log.showSignature` + `gpg.program` trong `.git/config`: `git log` chạy chương trình của kho để kiểm chữ ký commit (rà 02/11/2026).
20
+ return ['--no-optional-locks', '-c', 'core.fsmonitor=false', '-c', `core.hooksPath=${nullDevice}`, '-c', 'log.showSignature=false', '-c', `gpg.program=${nullDevice}`, '-C', cwd, ...hardened];
21
+ }
22
+
23
+ /** Môi trường cho git: bỏ mọi `GIT_*` (Windows: tên biến không phân biệt hoa thường), thêm cờ không hỏi mật khẩu / không đọc pager. */
24
+ export function safeGitEnv(base = process.env) {
25
+ const out = {};
26
+ for (const [key, value] of Object.entries(base || {})) {
27
+ if (/^git_/i.test(key)) continue;
28
+ out[key] = value;
29
+ }
30
+ return { ...out, GIT_TERMINAL_PROMPT: '0', GIT_OPTIONAL_LOCKS: '0' };
31
+ }
@@ -88,14 +88,14 @@ export function assertAppAllowed(name, { fullAccess }) {
88
88
  }
89
89
  }
90
90
 
91
- const normalizeName = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
91
+ const normalizeName = (s) => String(s || '').normalize('NFD').replace(/[̀-ͯ]/g, '').replace(/đ/gi, 'd').toLowerCase().replace(/[^a-z0-9]+/g, ' ').trim();
92
92
 
93
93
  /**
94
94
  * Rank UI nodes with richer evidence while keeping the model-facing schema small. Hard exclusions happen
95
95
  * before scoring; exact accessible names and AutomationIds beat loose word matches. The margin between the
96
96
  * first two candidates is used by gui.do to refuse ambiguous actions instead of guessing.
97
97
  */
98
- export function rankGuiNodes(nodes, query, role = '') {
98
+ export function rankGuiNodes(nodes, query, role = '', { matchValue = true } = {}) {
99
99
  const q = normalizeName(query);
100
100
  const words = q.split(' ').filter(Boolean);
101
101
  const wantedRole = String(role || '').toLowerCase();
@@ -105,7 +105,7 @@ export function rankGuiNodes(nodes, query, role = '') {
105
105
  .map((node, order) => {
106
106
  const name = normalizeName(node.name);
107
107
  const aid = normalizeName(node.automation_id);
108
- const value = normalizeName(node.value);
108
+ const value = matchValue ? normalizeName(node.value) : '';
109
109
  const help = normalizeName(node.help);
110
110
  const combined = [name, aid, value, help].filter(Boolean).join(' ');
111
111
  const hits = words.filter((word) => combined.includes(word)).length;
@@ -125,6 +125,28 @@ export function rankGuiNodes(nodes, query, role = '') {
125
125
  .sort((a, b) => b.score - a.score || b.hits - a.hits || a.order - b.order);
126
126
  }
127
127
 
128
+ /**
129
+ * Nhãn nút chốt / phá huỷ (đã bỏ dấu, viết thường). Cổng duyệt trên BE xét câu mô tả, nên khi máy tự chọn phần tử có nhãn kiểu này mà câu
130
+ * mô tả không nói tới (vd "Lưu" khớp tiền tố "Lưu và gửi") thì không bấm thẳng — trả mơ hồ để BE phân giải + xét sàn an toàn trên đúng nút.
131
+ */
132
+ const RISKY_LABEL_WORDS = new Set([
133
+ 'send', 'submit', 'post', 'publish', 'delete', 'remove', 'erase', 'pay', 'purchase', 'buy', 'order', 'confirm', 'approve', 'transfer', 'logout', 'signout',
134
+ 'gui', 'dang', 'xoa', 'go', 'huy', 'mua', 'chuyen', 'duyet',
135
+ ]);
136
+ const RISKY_LABEL_PHRASES = ['sign out', 'log out', 'thanh toan', 'xac nhan', 'dang xuat', 'dat hang', 'chuyen tien', 'go bo'];
137
+
138
+ export function riskyLabelWords(label) {
139
+ const n = normalizeName(label);
140
+ const words = n.split(' ').filter((w) => RISKY_LABEL_WORDS.has(w));
141
+ return [...words, ...RISKY_LABEL_PHRASES.filter((p) => ` ${n} `.includes(` ${p} `))];
142
+ }
143
+
144
+ /** Phần tử đã chọn mang nhãn chốt / phá huỷ mà câu mô tả không có → không bấm thẳng. */
145
+ export function needsServerCheck(query, node) {
146
+ const asked = new Set(riskyLabelWords(query));
147
+ return riskyLabelWords(node?.name || node?.automation_id).some((w) => !asked.has(w));
148
+ }
149
+
128
150
  /** Chọn ứng dụng theo tên: trùng hẳn > bắt đầu bằng > chứa. Nhiều ứng viên ngang nhau → trả danh sách để Planner chọn lại. */
129
151
  export function matchApps(apps, query) {
130
152
  const q = normalizeName(query);
@@ -160,7 +182,7 @@ function runPowerShellJson(script, signal) {
160
182
  export function createGuiController({
161
183
  fullAccess = false, host = createWindowsHost(), notify = showOSNotification, say = () => {}, background = true, defaultWindow = () => null, fetchApps = (signal) => runPowerShellJson('Get-StartApps | Select-Object Name, AppID | ConvertTo-Json -Compress', signal),
162
184
  } = {}) {
163
- let appsCache = null;
185
+ let appsCache = null;
164
186
  let appsInflight = null;
165
187
  let lastNotifyAt = 0;
166
188
  /** Cửa sổ của từng lần observe — để kiểm ứng dụng bị chặn ở thao tác theo node_id. */
@@ -185,6 +207,14 @@ export function createGuiController({
185
207
  */
186
208
  const target = (args) => (args.window ? { window: args.window } : { ...defaultWindow() });
187
209
  const windowInfoOf = (args, ctx) => host.call('window_info', target(args), ctx);
210
+ /**
211
+ * Thao tác có thay đổi mà không nêu cửa sổ (02/11/2026): không lấy cửa sổ đang focus — người dùng có thể vừa chuyển sang cửa sổ khác. Chỉ
212
+ * cho khi hỏi từ linh vật (có cửa sổ chủ máy dùng ngay trước đó); host kiểm lại đúng lúc thao tác (linh vật có đang được focus không).
213
+ */
214
+ const assertWindowNamed = (windowArg) => {
215
+ if (windowArg || defaultWindow()?.fallback) return;
216
+ throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Name the window for this action (window / within: a handle 0x… or a title/process from gui.windows) — input is never sent to whatever window happens to be focused');
217
+ };
188
218
 
189
219
  async function observe(args, ctx) {
190
220
  const res = await host.call('observe', {
@@ -213,13 +243,14 @@ export function createGuiController({
213
243
  const role = String(args.role || '').toLowerCase();
214
244
  const max = Math.max(1, Math.min(Number(args.max) || FIND_DEFAULT, FIND_MAX));
215
245
  const res = await observe({ ...args, max_nodes: 1500 }, ctx);
216
- const scored = rankGuiNodes(res.nodes, args.query, role);
246
+ // gui.do chọn phần tử để BẤM: không tính nội dung ô — chữ trên màn hình (thư, trang web) không được lái việc chọn nút (02/11/2026).
247
+ const scored = rankGuiNodes(res.nodes, args.query, role, { matchValue: args.match_value !== false });
217
248
  const all = scored.filter((x) => x.hits === words.length);
218
249
  const pool = all.length ? all : scored.filter((x) => x.hits === scored[0]?.hits);
219
250
  const picked = pool.slice(0, max);
220
- const margin = picked.length > 1 ? picked[0].score - picked[1].score : picked.length ? picked[0].score : 0;
221
- const out = { ...res, nodes: picked.map((x) => x.node), query: String(args.query), matched: all.length || scored.length, exact: all.length > 0, confidence: !picked.length ? 'none' : margin >= 15 || picked.length === 1 ? 'high' : margin >= 5 ? 'medium' : 'low', ambiguous: picked.length > 1 && margin < 5 || undefined };
222
- Object.defineProperty(out, '_raw_observation', { value: res, enumerable: false });
251
+ const margin = picked.length > 1 ? picked[0].score - picked[1].score : picked.length ? picked[0].score : 0;
252
+ const out = { ...res, nodes: picked.map((x) => x.node), query: String(args.query), matched: all.length || scored.length, exact: all.length > 0, confidence: !picked.length ? 'none' : margin >= 15 || picked.length === 1 ? 'high' : margin >= 5 ? 'medium' : 'low', ambiguous: picked.length > 1 && margin < 5 || undefined };
253
+ Object.defineProperty(out, '_raw_observation', { value: res, enumerable: false });
223
254
  return out;
224
255
  }
225
256
 
@@ -235,6 +266,7 @@ export function createGuiController({
235
266
  key: GuiAction.KEY, scroll: GuiAction.SCROLL,
236
267
  }[command];
237
268
  if (!action) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Unknown semantic action: ${args.do || ''}`);
269
+ assertWindowNamed(args.within || args.window);
238
270
 
239
271
  if ((command === 'key' || command === 'scroll') && !args.target) {
240
272
  const result = await act({
@@ -246,20 +278,27 @@ export function createGuiController({
246
278
 
247
279
  const query = String(args.target || '').trim();
248
280
  if (!query) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give target');
249
- let found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES }, ctx);
250
- if (!found.nodes.length && !found.ocr && found.tree_quality !== 'poor') {
251
- found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, ocr: true }, ctx);
281
+ let found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, match_value: false }, ctx);
282
+ if (!found.nodes.length && !found.ocr && found.tree_quality !== 'poor') {
283
+ found = await find({ query, role: args.role, window: args.within || args.window, max: SEMANTIC_CHOICES, match_value: false, ocr: true }, ctx);
252
284
  }
253
285
  if (!found.nodes.length) throw new DeviceToolError(DeviceErrorCode.GUI_TARGET_NOT_FOUND, `No enabled visible target matched "${query}"`);
254
286
  if (found.ambiguous) {
255
287
  return {
256
288
  ok: false, code: DeviceErrorCode.GUI_AMBIGUOUS_TARGET,
257
- choices: found.nodes.map((n) => ({ ref: n.id, label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — ') })),
289
+ choices: found.nodes.map((n) => ({ ref: n.id, label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — ') })),
258
290
  observation: found._raw_observation,
259
291
  };
260
292
  }
261
293
 
262
294
  const node = found.nodes[0];
295
+ if (command !== 'fill' && needsServerCheck(query, node)) {
296
+ return {
297
+ ok: false, code: DeviceErrorCode.GUI_AMBIGUOUS_TARGET,
298
+ choices: found.nodes.map((n) => ({ ref: n.id, label: [n.name || n.automation_id || n.role, n.role].filter(Boolean).join(' — ') })),
299
+ observation: found._raw_observation,
300
+ };
301
+ }
263
302
  if (command === 'fill' && node.password) {
264
303
  throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'AI may not fill password or secret fields — ask the user to enter it');
265
304
  }
@@ -282,6 +321,7 @@ export function createGuiController({
282
321
  return {
283
322
  ok: true, action: command, target: node.name || node.automation_id || node.role,
284
323
  ...(verified === undefined ? {} : { verified }),
324
+ ...(result.screen_point ? { screen_point: result.screen_point } : {}),
285
325
  effect: result.window_title_changed || result.target || result.focused_element || command,
286
326
  };
287
327
  }
@@ -306,6 +346,8 @@ export function createGuiController({
306
346
  const action = String(args.action || GuiAction.CLICK);
307
347
  if (!Object.values(GuiAction).includes(action)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `Unknown action: ${action}`);
308
348
  const snap = args.node_id ? String(args.node_id).split('.')[0] : null;
349
+ // node_id đã chỉ đúng phần tử của một lần observe (kèm cửa sổ của nó) — chỉ thao tác không node_id mới phải nêu cửa sổ.
350
+ if (!snap) assertWindowNamed(args.window);
309
351
  const windowInfo = snap ? snapshotWindows.get(snap) : await windowInfoOf(args, ctx);
310
352
  if (snap && !windowInfo) throw new DeviceToolError(DeviceErrorCode.GUI_STALE_NODE, `Node ${args.node_id} is from an old observation — observe again`);
311
353
  assertWindowAllowed(windowInfo, { fullAccess });
@@ -319,14 +361,14 @@ export function createGuiController({
319
361
  }
320
362
 
321
363
  async function listApps(signal) {
322
- if (appsCache && Date.now() - appsCache.at < APPS_CACHE_MS) return appsCache.apps;
323
- if (appsInflight && !signal) return appsInflight;
324
- const task = Promise.resolve().then(() => fetchApps(signal)).catch(() => []).then((rows) => {
325
- const apps = (rows || []).filter((r) => r?.Name && r?.AppID).map((r) => ({ name: String(r.Name), app_id: String(r.AppID) }));
326
- if (apps.length) appsCache = { at: Date.now(), apps };
327
- return apps.length ? apps : (appsCache?.apps || []);
328
- }).finally(() => { if (appsInflight === task) appsInflight = null; });
329
- if (!signal) appsInflight = task;
364
+ if (appsCache && Date.now() - appsCache.at < APPS_CACHE_MS) return appsCache.apps;
365
+ if (appsInflight && !signal) return appsInflight;
366
+ const task = Promise.resolve().then(() => fetchApps(signal)).catch(() => []).then((rows) => {
367
+ const apps = (rows || []).filter((r) => r?.Name && r?.AppID).map((r) => ({ name: String(r.Name), app_id: String(r.AppID) }));
368
+ if (apps.length) appsCache = { at: Date.now(), apps };
369
+ return apps.length ? apps : (appsCache?.apps || []);
370
+ }).finally(() => { if (appsInflight === task) appsInflight = null; });
371
+ if (!signal) appsInflight = task;
330
372
  return task;
331
373
  }
332
374
 
@@ -384,21 +426,21 @@ export function createGuiController({
384
426
  export function buildGuiTools(gui) {
385
427
  const target = {
386
428
  node_id: str('target element id from the latest gui.observe (preferred)'),
387
- window: str('window handle (0x…) or a title/process to match; default the focused window (asked from the mascot: the window the person was using)'),
429
+ window: str('window handle (0x…) or a title/process to match; reading defaults to the focused window, but an action without node_id must name it (asked from the mascot: the window the person was using)'),
388
430
  };
389
431
  return [
390
432
  { name: 'gui.do', group: ToolGroup.GUI, handler: (a, c, e) => gui.semanticDo(a, c, e),
391
433
  description: 'Fast semantic desktop action. State the intent briefly; the device finds one enabled visible target, refuses ambiguity, acts, and verifies simple value/state changes. Use precise gui.find/gui.act only after an ambiguous result.',
392
434
  input_schema: schema({
393
435
  do: str('click | fill | select | toggle | key | scroll | open'), target: str('short visible label or app name'),
394
- value: str('text, option, on/off, key chord, or scroll direction'), within: str('optional window title/process'),
436
+ value: str('text, option, on/off, key chord, or scroll direction'), within: str('window title/process to act in (required, except when asked from the mascot)'),
395
437
  role: str('optional role such as button or edit'), file: str('document path for open'),
396
438
  }, ['do']) },
397
439
  { name: 'gui.windows', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.windows(a, c),
398
440
  description: 'List open desktop windows: title, app process, handle, position, which is focused/minimized. blocked = the AI may not control it.',
399
441
  input_schema: schema({ include_dialogs: bool('also list owned dialogs') }) },
400
442
  { name: 'gui.observe', group: ToolGroup.GUI, read_only: true, handler: (a, c) => gui.observe(a, c),
401
- description: 'Read a window as an accessibility tree: each element has an id (node_id), role, name, value, state and supported actions. tree_quality "poor" = the app draws its own UI; a screenshot is then attached and the text on it is read on the device (OCR): each text run becomes a node with role "text", source "ocr" and an id like "4.t2" that gui.act can click / type at. Ids are only valid until the next observe of that window.',
443
+ description: 'Read a window as an accessibility tree: each element has an id (node_id), role, name, value, state and supported actions. tree_quality "poor" = the app draws its own UI; a screenshot is then attached and the text on it is read on the device (OCR): each text run becomes a node with role "text", source "ocr" and an id like "4.t2" that gui.act can click / type at. Ids are only valid until the next observe of that window. image_error = no screenshot this time (the app can only be captured from the screen and the window is behind/covered — gui.focus it first if a screenshot is needed).',
402
444
  input_schema: schema({
403
445
  window: target.window, include_image: bool('attach a screenshot even when the tree is good'), max_nodes: num('default 300'),
404
446
  ocr: bool('read the text on the window even when the tree is good (default: only when poor)'),
@@ -420,7 +462,7 @@ export function buildGuiTools(gui) {
420
462
  description: 'Bring a window to the front (restores it if minimized).',
421
463
  input_schema: schema({ window: target.window }, ['window']) },
422
464
  { name: 'gui.act', group: ToolGroup.GUI, handler: (a, c) => gui.act(a, c),
423
- description: 'Do one action on an element (node_id) or at a point of the last screenshot: click, double_click, right_click, set_value (replace a field\'s text), type (keystrokes into the focused element), key (shortcut like "ctrl+s", "alt+f4", "enter"), scroll, select (option of a list/combo), toggle, expand, collapse, drag. Uses accessibility actions first (works even when the window is behind), real mouse/keyboard otherwise. Returns evidence: the element\'s new value/state, window title change, focused element. OCR text nodes ("4.t2") take click / double_click / right_click, or set_value / type (clicks there, then types). Stops with GUI_USER_ACTIVE if the person is using the mouse/keyboard.',
465
+ description: 'Do one action on an element (node_id) or at a point of the last screenshot: click, double_click, right_click, set_value (replace a field\'s text), type (keystrokes into the focused element), key (shortcut like "ctrl+s", "alt+f4", "enter"), scroll, select (option of a list/combo), toggle, expand, collapse, drag. Uses accessibility actions first (works even when the window is behind), real mouse/keyboard otherwise. Returns evidence: the element\'s new value/state, window title change, focused element. OCR text nodes ("4.t2") take click / double_click / right_click, or set_value / type (clicks there, then types). Without node_id give window. Stops with GUI_USER_ACTIVE if the person is using the mouse/keyboard, and with GUI_FOCUS_LOST (nothing clicked / the rest not typed) if real mouse/keyboard input could not reach the window — it could not come to the front, or another window covers the point.',
424
466
  input_schema: schema({
425
467
  action: str(Object.values(GuiAction).join(' | ')), ...target, text: str('text for set_value / type'), keys: str('for key: e.g. "ctrl+s", several separated by spaces'),
426
468
  option: str('for select: the option name'), state: str('for toggle: on | off'), direction: str('for scroll: up | down | left | right'), amount: num('scroll steps, default 3'),