@aivin-labs/cli 1.0.5 → 1.0.11

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 (93) hide show
  1. package/README.md +288 -216
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +551 -5
  4. package/bin/lib/browserAutomation.mjs +384 -614
  5. package/bin/lib/browserTui.mjs +276 -251
  6. package/bin/lib/cancellation.mjs +61 -0
  7. package/bin/lib/localBrowser.mjs +345 -0
  8. package/bin/lib/mcpProxy.mjs +869 -837
  9. package/bin/lib/missionStream.mjs +696 -691
  10. package/bin/lib/releaseKeys.mjs +9 -0
  11. package/bin/lib/remote/activityLog.mjs +68 -0
  12. package/bin/lib/remote/autoStart.mjs +617 -0
  13. package/bin/lib/remote/autoUpdate.mjs +129 -0
  14. package/bin/lib/remote/brand.mjs +60 -0
  15. package/bin/lib/remote/browserTunnel.mjs +403 -0
  16. package/bin/lib/remote/callLedger.mjs +134 -0
  17. package/bin/lib/remote/cdpPolicy.mjs +79 -0
  18. package/bin/lib/remote/client.mjs +808 -0
  19. package/bin/lib/remote/clipboard.mjs +138 -0
  20. package/bin/lib/remote/codingAgents.mjs +293 -0
  21. package/bin/lib/remote/constants.mjs +234 -0
  22. package/bin/lib/remote/credentials.mjs +208 -0
  23. package/bin/lib/remote/daemonLock.mjs +86 -0
  24. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  25. package/bin/lib/remote/desktop/index.mjs +272 -0
  26. package/bin/lib/remote/desktop/linux.mjs +144 -0
  27. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  28. package/bin/lib/remote/desktop/mac.mjs +187 -0
  29. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  30. package/bin/lib/remote/desktop/strings.mjs +74 -0
  31. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  32. package/bin/lib/remote/deviceMemory.mjs +246 -0
  33. package/bin/lib/remote/deviceProfile.mjs +142 -0
  34. package/bin/lib/remote/deviceWatches.mjs +138 -0
  35. package/bin/lib/remote/docText.mjs +117 -0
  36. package/bin/lib/remote/fileIndexer.mjs +399 -0
  37. package/bin/lib/remote/gui/index.mjs +326 -0
  38. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  39. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  40. package/bin/lib/remote/gui/windowsHostSource.mjs +1156 -0
  41. package/bin/lib/remote/httpTransfer.mjs +89 -0
  42. package/bin/lib/remote/idempotency.mjs +135 -0
  43. package/bin/lib/remote/keepAwake.mjs +100 -0
  44. package/bin/lib/remote/localConfirm.mjs +268 -0
  45. package/bin/lib/remote/localPolicy.mjs +256 -0
  46. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  47. package/bin/lib/remote/mascot/ask.mjs +768 -0
  48. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  49. package/bin/lib/remote/mascot/assets.mjs +827 -0
  50. package/bin/lib/remote/mascot/bot.mjs +372 -0
  51. package/bin/lib/remote/mascot/hostSource.mjs +759 -0
  52. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  53. package/bin/lib/remote/mascot/index.mjs +493 -0
  54. package/bin/lib/remote/mascot/labels.mjs +82 -0
  55. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  56. package/bin/lib/remote/mascot/strings.mjs +375 -0
  57. package/bin/lib/remote/mascot/ui.mjs +104 -0
  58. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  59. package/bin/lib/remote/meeting/index.mjs +415 -0
  60. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  61. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  62. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  63. package/bin/lib/remote/memberFsPool.mjs +134 -0
  64. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  65. package/bin/lib/remote/mission.mjs +156 -0
  66. package/bin/lib/remote/missionQuestion.mjs +63 -0
  67. package/bin/lib/remote/multiUser.mjs +344 -0
  68. package/bin/lib/remote/netProxy.mjs +145 -0
  69. package/bin/lib/remote/notify.mjs +58 -0
  70. package/bin/lib/remote/office/index.mjs +90 -0
  71. package/bin/lib/remote/policyCommand.mjs +93 -0
  72. package/bin/lib/remote/processes.mjs +217 -0
  73. package/bin/lib/remote/sandbox.mjs +221 -0
  74. package/bin/lib/remote/schedule.mjs +213 -0
  75. package/bin/lib/remote/scheduler.mjs +124 -0
  76. package/bin/lib/remote/tabGroups.mjs +209 -0
  77. package/bin/lib/remote/textIndex.mjs +131 -0
  78. package/bin/lib/remote/tokenStore.mjs +77 -0
  79. package/bin/lib/remote/toolHandlers.mjs +741 -0
  80. package/bin/lib/remote/undoStore.mjs +242 -0
  81. package/bin/lib/remoteControl.mjs +26 -0
  82. package/bin/lib/scaffold.mjs +654 -653
  83. package/bin/lib/selfUpdate.mjs +71 -0
  84. package/bin/lib/update/binarySwap.mjs +63 -0
  85. package/bin/lib/update/constants.mjs +56 -0
  86. package/bin/lib/update/download.mjs +145 -0
  87. package/bin/lib/update/signature.mjs +42 -0
  88. package/bin/lib/update/state.mjs +205 -0
  89. package/bin/lib/update/versions.mjs +60 -0
  90. package/docs/AIVIN_MASCOT.md +116 -0
  91. package/docs/CLI.md +1484 -1299
  92. package/docs/media/aivin-mascot-states.mp4 +0 -0
  93. package/package.json +71 -62
@@ -0,0 +1,246 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { createHash } from 'crypto';
4
+ import YAML from 'yaml';
5
+ import { MemoryKind, REMOTE_CONFIG_DIR } from './constants.mjs';
6
+ import { createTextIndex, decodeInt8, fuseRankings, int8Cosine } from './textIndex.mjs';
7
+
8
+ /**
9
+ * Bộ nhớ dài hạn NẰM TRÊN MÁY. Nguồn sự thật là các tệp YAML người dùng đọc / sửa tay được (`~/.aivin/memory/<loại>.yaml`), vector
10
+ * (do BE tính bằng bge-m3, int8 base64) để ở tệp riêng `vectors.json` khoá theo băm nội dung — sửa nội dung một mục thì vector cũ tự
11
+ * bỏ, mục đó vẫn tìm được bằng từ khoá. Daemon nạp hết vào RAM: tìm kết hợp BM25 + cosine, truy cập ngẫu nhiên theo id / loại+khoá /
12
+ * con trỏ phân trang.
13
+ *
14
+ * Ghi: một tiến trình ghi (daemon), ghi tệp tạm rồi đổi tên (mất điện giữa chừng không hỏng tệp). Người dùng sửa tay → theo dõi thư
15
+ * mục, nạp lại.
16
+ */
17
+
18
+ export const DEVICE_MEMORY_DIR = path.join(REMOTE_CONFIG_DIR, 'memory');
19
+ const VECTORS_FILE = path.join(DEVICE_MEMORY_DIR, 'vectors.json');
20
+ const KINDS = Object.values(MemoryKind);
21
+ const MAX_TEXT = 4000;
22
+ const MAX_KEY = 160;
23
+ const RELOAD_DEBOUNCE_MS = 300;
24
+
25
+ const state = {
26
+ loaded: false,
27
+ items: new Map(), // id → item
28
+ byKind: new Map(), // kind → Map<key, id>
29
+ vectors: {}, // contentHash → base64
30
+ index: createTextIndex(),
31
+ watcher: null,
32
+ ownWriteAt: 0,
33
+ };
34
+
35
+ export function memoryItemId(kind, key) {
36
+ return createHash('sha1').update(`${kind}\n${key}`).digest('hex').slice(0, 12);
37
+ }
38
+
39
+ function contentHash(item) {
40
+ return createHash('sha1').update(`${item.kind}\n${item.key}\n${item.text}`).digest('hex').slice(0, 20);
41
+ }
42
+
43
+ function kindFile(kind) {
44
+ return path.join(DEVICE_MEMORY_DIR, `${kind}.yaml`);
45
+ }
46
+
47
+ function atomicWrite(file, content) {
48
+ fs.mkdirSync(path.dirname(file), { recursive: true });
49
+ const tmp = `${file}.tmp-${process.pid}-${Date.now()}`;
50
+ fs.writeFileSync(tmp, content, 'utf8');
51
+ fs.renameSync(tmp, file);
52
+ state.ownWriteAt = Date.now();
53
+ }
54
+
55
+ function normalizeItem(raw, kind) {
56
+ if (!raw || typeof raw !== 'object') return null;
57
+ const key = String(raw.key || '').trim().slice(0, MAX_KEY);
58
+ const text = String(raw.text || '').trim().slice(0, MAX_TEXT);
59
+ if (!key || !text) return null;
60
+ return {
61
+ id: memoryItemId(kind, key),
62
+ kind,
63
+ key,
64
+ text,
65
+ ...(raw.data !== undefined ? { data: raw.data } : {}),
66
+ created_at: raw.created_at || new Date().toISOString(),
67
+ updated_at: raw.updated_at || raw.created_at || new Date().toISOString(),
68
+ };
69
+ }
70
+
71
+ function indexItem(item) {
72
+ state.items.set(item.id, item);
73
+ if (!state.byKind.has(item.kind)) state.byKind.set(item.kind, new Map());
74
+ state.byKind.get(item.kind).set(item.key, item.id);
75
+ state.index.add(item.id, `${item.key} ${item.text}`);
76
+ }
77
+
78
+ function unindexItem(id) {
79
+ const item = state.items.get(id);
80
+ if (!item) return;
81
+ state.items.delete(id);
82
+ state.byKind.get(item.kind)?.delete(item.key);
83
+ state.index.remove(id);
84
+ }
85
+
86
+ function readKindFile(kind) {
87
+ try {
88
+ const parsed = YAML.parse(fs.readFileSync(kindFile(kind), 'utf8'));
89
+ const list = Array.isArray(parsed) ? parsed : Array.isArray(parsed?.items) ? parsed.items : [];
90
+ return list.map((raw) => normalizeItem(raw, kind)).filter(Boolean);
91
+ } catch (error) {
92
+ if (error.code !== 'ENOENT') console.warn(`[remote] Không đọc được ${kindFile(kind)}: ${error.message}`);
93
+ return [];
94
+ }
95
+ }
96
+
97
+ function reloadAll() {
98
+ state.items.clear();
99
+ state.byKind.clear();
100
+ state.index.clear();
101
+ for (const kind of KINDS) readKindFile(kind).forEach(indexItem);
102
+ try { state.vectors = JSON.parse(fs.readFileSync(VECTORS_FILE, 'utf8')) || {}; } catch { state.vectors = {}; }
103
+ state.loaded = true;
104
+ }
105
+
106
+ export function ensureMemoryLoaded() {
107
+ if (!state.loaded) reloadAll();
108
+ }
109
+
110
+ /** Theo dõi người dùng sửa tay tệp YAML → nạp lại (bỏ qua sự kiện do chính mình ghi). */
111
+ export function watchMemoryDir() {
112
+ if (state.watcher) return;
113
+ fs.mkdirSync(DEVICE_MEMORY_DIR, { recursive: true });
114
+ let timer;
115
+ try {
116
+ state.watcher = fs.watch(DEVICE_MEMORY_DIR, () => {
117
+ if (Date.now() - state.ownWriteAt < 1000) return;
118
+ clearTimeout(timer);
119
+ timer = setTimeout(reloadAll, RELOAD_DEBOUNCE_MS);
120
+ });
121
+ state.watcher.unref?.();
122
+ } catch { /* hệ thống tệp không hỗ trợ theo dõi — sửa tay có hiệu lực ở lần khởi động sau */ }
123
+ }
124
+
125
+ export function stopWatchingMemory() {
126
+ state.watcher?.close();
127
+ state.watcher = null;
128
+ }
129
+
130
+ function persistKind(kind) {
131
+ const ids = [...(state.byKind.get(kind)?.values() || [])];
132
+ const list = ids.map((id) => {
133
+ const { id: _id, kind: _kind, ...rest } = state.items.get(id);
134
+ return rest;
135
+ });
136
+ atomicWrite(kindFile(kind), list.length ? YAML.stringify(list, { lineWidth: 0 }) : '[]\n');
137
+ }
138
+
139
+ function persistVectors() {
140
+ const live = new Set([...state.items.values()].map(contentHash));
141
+ for (const hash of Object.keys(state.vectors)) if (!live.has(hash)) delete state.vectors[hash];
142
+ atomicWrite(VECTORS_FILE, JSON.stringify(state.vectors));
143
+ }
144
+
145
+ function publicItem(item, score) {
146
+ return { id: item.id, kind: item.kind, key: item.key, text: item.text, ...(item.data !== undefined ? { data: item.data } : {}), updated_at: item.updated_at, ...(score !== undefined ? { score } : {}) };
147
+ }
148
+
149
+ /** Thêm / cập nhật theo (loại, khoá). `vector`: int8 base64 BE gửi kèm. */
150
+ export function putMemoryItems(items = []) {
151
+ ensureMemoryLoaded();
152
+ const touched = new Set();
153
+ let vectorsChanged = false;
154
+ let saved = 0;
155
+ for (const raw of Array.isArray(items) ? items : []) {
156
+ const kind = KINDS.includes(raw?.kind) ? raw.kind : MemoryKind.FACT;
157
+ const existing = state.items.get(memoryItemId(kind, String(raw?.key || '').trim().slice(0, MAX_KEY)));
158
+ const item = normalizeItem({ ...raw, created_at: existing?.created_at, updated_at: new Date().toISOString() }, kind);
159
+ if (!item) continue;
160
+ indexItem(item);
161
+ if (raw.vector) { state.vectors[contentHash(item)] = String(raw.vector); vectorsChanged = true; }
162
+ touched.add(kind);
163
+ saved++;
164
+ }
165
+ touched.forEach(persistKind);
166
+ if (vectorsChanged || touched.size) persistVectors();
167
+ return { saved };
168
+ }
169
+
170
+ export function getMemoryItem({ id, kind, key } = {}) {
171
+ ensureMemoryLoaded();
172
+ const itemId = id || (kind && key ? memoryItemId(kind, key) : null);
173
+ const item = itemId ? state.items.get(itemId) : null;
174
+ return item ? publicItem(item) : null;
175
+ }
176
+
177
+ /** Phân trang theo con trỏ (vị trí), mới cập nhật trước. */
178
+ export function listMemoryItems({ kind, cursor = 0, limit = 50 } = {}) {
179
+ ensureMemoryLoaded();
180
+ const all = [...state.items.values()]
181
+ .filter((i) => !kind || i.kind === kind)
182
+ .sort((a, b) => String(b.updated_at).localeCompare(String(a.updated_at)));
183
+ const start = Math.max(0, Number(cursor) || 0);
184
+ const size = Math.min(Math.max(1, Number(limit) || 50), 200);
185
+ const page = all.slice(start, start + size).map((i) => publicItem(i));
186
+ return { total: all.length, items: page, next_cursor: start + size < all.length ? start + size : null };
187
+ }
188
+
189
+ export function deleteMemoryItems({ ids = [], kind, key } = {}) {
190
+ ensureMemoryLoaded();
191
+ const targets = [...ids];
192
+ if (kind && key) targets.push(memoryItemId(kind, key));
193
+ const touched = new Set();
194
+ let deleted = 0;
195
+ for (const id of new Set(targets)) {
196
+ const item = state.items.get(id);
197
+ if (!item) continue;
198
+ touched.add(item.kind);
199
+ unindexItem(id);
200
+ deleted++;
201
+ }
202
+ touched.forEach(persistKind);
203
+ if (touched.size) persistVectors();
204
+ return { deleted };
205
+ }
206
+
207
+ export function clearDeviceMemory(kind) {
208
+ ensureMemoryLoaded();
209
+ const kinds = kind ? [kind] : KINDS;
210
+ for (const k of kinds) {
211
+ for (const id of [...(state.byKind.get(k)?.values() || [])]) unindexItem(id);
212
+ persistKind(k);
213
+ }
214
+ persistVectors();
215
+ }
216
+
217
+ /**
218
+ * Tìm kết hợp: BM25 (từ khoá) và cosine (vector đề bài do BE gửi) gộp bằng RRF. `score` trả về là cosine (0 khi mục chưa có vector) —
219
+ * BE dùng nó làm ngưỡng "đủ giống để chạy lại quy trình".
220
+ */
221
+ export function searchMemory({ query = '', vector, kinds, limit = 8 } = {}) {
222
+ ensureMemoryLoaded();
223
+ const kindSet = Array.isArray(kinds) && kinds.length ? new Set(kinds) : null;
224
+ const allowed = (id) => !kindSet || kindSet.has(state.items.get(id)?.kind);
225
+ const wide = Math.max(limit * 3, 20);
226
+ const lexical = query ? state.index.search(query, { limit: wide, filter: allowed }).map((h) => h.id) : [];
227
+ const q = decodeInt8(vector);
228
+ const cosine = new Map();
229
+ if (q) {
230
+ for (const item of state.items.values()) {
231
+ if (!allowed(item.id)) continue;
232
+ const v = decodeInt8(state.vectors[contentHash(item)]);
233
+ if (v) cosine.set(item.id, int8Cosine(q, v));
234
+ }
235
+ }
236
+ const semantic = [...cosine.entries()].sort((a, b) => b[1] - a[1]).slice(0, wide).map(([id]) => id);
237
+ return fuseRankings([lexical, semantic]).slice(0, limit).map((id) => publicItem(state.items.get(id), Number((cosine.get(id) || 0).toFixed(4))));
238
+ }
239
+
240
+ export function memoryStats() {
241
+ ensureMemoryLoaded();
242
+ const byKind = {};
243
+ for (const item of state.items.values()) byKind[item.kind] = (byKind[item.kind] || 0) + 1;
244
+ const withVector = [...state.items.values()].filter((i) => state.vectors[contentHash(i)]).length;
245
+ return { total: state.items.size, by_kind: byKind, with_vector: withVector, dir: DEVICE_MEMORY_DIR };
246
+ }
@@ -0,0 +1,142 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { createHash } from 'crypto';
5
+ import { createRequire } from 'module';
6
+ import { IGNORED_DIRS } from './constants.mjs';
7
+ import { isProtectedPath } from './sandbox.mjs';
8
+
9
+ export { REMOTE_CONFIG_DIR } from './constants.mjs';
10
+
11
+ const require = createRequire(import.meta.url);
12
+ const CLI_VERSION = (() => { try { return require('../../../package.json').version; } catch { return 'unknown'; } })();
13
+
14
+ /** 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
+ const KNOWN_BINARIES = [
16
+ 'git', 'rg', 'node', 'npm', 'pnpm', 'yarn', 'bun', 'deno', 'python', 'python3', 'pip', 'uv', 'docker', 'kubectl', 'go', 'cargo',
17
+ 'java', 'mvn', 'gradle', 'dotnet', 'php', 'composer', 'ruby', 'ffmpeg', 'adb', 'code', 'gh', 'terraform', 'make', 'cmake',
18
+ // Shell + trình quản lý gói + quản lý dịch vụ (28/10/2026): Planner chọn đúng cú pháp / công cụ của máy (gói kỹ năng theo hệ điều hành ở BE).
19
+ 'pwsh', 'claude', 'winget', 'choco', 'scoop', 'brew', 'apt', 'apt-get', 'dnf', 'yum', 'pacman', 'zypper', 'snap', 'systemctl', 'launchctl',
20
+ 'apk', 'flatpak', 'nix-env', 'sudo', 'doas', 'service', 'rc-service',
21
+ ];
22
+
23
+ /**
24
+ * Hệ điều hành cụ thể (28/10/2026): Linux có nhiều bản phân phối, lệnh khác nhau (apt / dnf / pacman / apk, glibc / musl, systemd /
25
+ * OpenRC) → đọc `/etc/os-release` (chuẩn chung của các bản phân phối) + kiểm musl; macOS / Windows lấy tên + phiên bản.
26
+ */
27
+ export function detectOs(platform = process.platform, readFile = (f) => fs.readFileSync(f, 'utf8'), exists = fs.existsSync) {
28
+ if (platform === 'linux') {
29
+ const info = {};
30
+ try {
31
+ for (const line of readFile('/etc/os-release').split(/\r?\n/)) {
32
+ const m = line.match(/^([A-Z_]+)=("?)(.*)\2$/);
33
+ if (m) info[m[1]] = m[3];
34
+ }
35
+ } catch { /* không có os-release */ }
36
+ let musl;
37
+ try { musl = fs.readdirSync('/lib').some((f) => f.startsWith('ld-musl')); } catch { musl = exists('/etc/alpine-release'); }
38
+ return {
39
+ name: info.PRETTY_NAME || info.NAME || 'Linux', id: info.ID, version: info.VERSION_ID, like: info.ID_LIKE,
40
+ libc: musl ? 'musl' : 'glibc', init: exists('/run/systemd/system') ? 'systemd' : exists('/sbin/openrc') ? 'openrc' : undefined,
41
+ };
42
+ }
43
+ if (platform === 'darwin') return { name: 'macOS', version: os.release(), id: 'macos' };
44
+ if (platform === 'win32') return { name: typeof os.version === 'function' ? os.version() : 'Windows', version: os.release(), id: 'windows' };
45
+ return { name: platform };
46
+ }
47
+
48
+ /** Dấu hiệu nhận ra một dự án trong thư mục. */
49
+ const PROJECT_MARKERS = [
50
+ ['package.json', 'node'], ['pyproject.toml', 'python'], ['requirements.txt', 'python'], ['go.mod', 'go'], ['Cargo.toml', 'rust'],
51
+ ['pom.xml', 'java'], ['build.gradle', 'java'], ['build.gradle.kts', 'java'], ['composer.json', 'php'], ['Gemfile', 'ruby'],
52
+ ['pubspec.yaml', 'dart'], ['CMakeLists.txt', 'cpp'],
53
+ ];
54
+ const PROJECT_SCAN_DEPTH = 3;
55
+ const MAX_PROJECTS = 50;
56
+
57
+ /**
58
+ * Chương trình có trên PATH — quét thư mục PATH một lượt (không spawn tiến trình nào), Windows thêm đuôi PATHEXT.
59
+ */
60
+ export function detectBinaries() {
61
+ const dirs = String(process.env.PATH || '').split(path.delimiter).filter(Boolean);
62
+ const exts = process.platform === 'win32'
63
+ ? String(process.env.PATHEXT || '.EXE;.CMD;.BAT;.COM').toLowerCase().split(';').filter(Boolean)
64
+ : [''];
65
+ const names = new Set();
66
+ for (const dir of dirs) {
67
+ let entries;
68
+ try { entries = fs.readdirSync(dir); } catch { continue; }
69
+ for (const entry of entries) names.add(entry.toLowerCase());
70
+ }
71
+ return KNOWN_BINARIES.filter((bin) => exts.some((ext) => names.has(`${bin}${ext}`)));
72
+ }
73
+
74
+ let pwshCached;
75
+ /** `pwsh` (PowerShell 7) có trên PATH không — dò một lần. */
76
+ export function hasPwsh() {
77
+ pwshCached ??= process.platform === 'win32' && detectBinaries().includes('pwsh');
78
+ return pwshCached;
79
+ }
80
+
81
+ /** Dự án trong các thư mục gốc (sâu tối đa 3 cấp): tên, đường tương đối, loại. */
82
+ export function detectProjects(roots) {
83
+ const projects = [];
84
+ for (const root of roots) {
85
+ const queue = [[path.resolve(root), 0]];
86
+ while (queue.length && projects.length < MAX_PROJECTS) {
87
+ const [dir, depth] = queue.shift();
88
+ let entries;
89
+ try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { continue; }
90
+ const names = new Set(entries.map((e) => e.name));
91
+ const marker = PROJECT_MARKERS.find(([file]) => names.has(file));
92
+ const isGit = names.has('.git');
93
+ if (marker || isGit || entries.some((e) => /\.(sln|csproj)$/i.test(e.name))) {
94
+ const kind = marker?.[1] || (isGit ? 'git' : 'dotnet');
95
+ projects.push({ name: path.basename(dir), path: path.relative(path.resolve(root), dir) || '.', kind: isGit && marker ? `${kind}+git` : kind });
96
+ }
97
+ if (depth >= PROJECT_SCAN_DEPTH) continue;
98
+ for (const e of entries) {
99
+ // Thư mục cấu hình Aivin có thể không bắt đầu bằng dấu chấm (`AIVIN_REMOTE_HOME`) → bỏ theo đường, không chỉ theo tên.
100
+ if (e.isDirectory() && !e.isSymbolicLink() && !IGNORED_DIRS.has(e.name) && !e.name.startsWith('.') && !isProtectedPath(path.join(dir, e.name))) queue.push([path.join(dir, e.name), depth + 1]);
101
+ }
102
+ }
103
+ }
104
+ return projects;
105
+ }
106
+
107
+ export function detectShell() {
108
+ // PowerShell 7 có trên máy → dùng (UTF-8 mặc định, có `&&` / `||`, nhanh hơn) thay PowerShell 5.1 đi kèm Windows.
109
+ if (process.platform === 'win32') return hasPwsh() ? 'pwsh' : 'powershell';
110
+ return process.env.SHELL ? path.basename(process.env.SHELL) : 'bash';
111
+ }
112
+
113
+ /** Hồ sơ máy gửi BE lúc chào (không chứa bí mật). */
114
+ export function buildDeviceProfile(roots) {
115
+ return {
116
+ hostname: os.hostname(),
117
+ platform: process.platform === 'win32' ? 'windows' : process.platform === 'darwin' ? 'macos' : process.platform,
118
+ arch: os.arch(),
119
+ shell: detectShell(),
120
+ os: detectOs(),
121
+ node_version: process.version,
122
+ cli_version: CLI_VERSION,
123
+ roots: roots.map((r) => path.resolve(r)),
124
+ binaries: detectBinaries(),
125
+ projects: detectProjects(roots),
126
+ };
127
+ }
128
+
129
+ /** Danh mục công cụ BE thấy (bỏ công cụ nội bộ) + dấu vân tay — BE chỉ xin bản đầy đủ khi dấu vân tay đổi. */
130
+ export function buildCatalog(tools) {
131
+ const catalog = tools.filter((t) => !t.internal).map((t) => ({
132
+ name: t.name,
133
+ description: t.description,
134
+ input_schema: t.input_schema,
135
+ read_only: !!t.read_only,
136
+ side_effect: !t.read_only,
137
+ destructive: !!t.destructive,
138
+ concurrency: t.group,
139
+ }));
140
+ const hash = createHash('sha256').update(JSON.stringify(catalog)).digest('hex').slice(0, 32);
141
+ return { catalog, hash };
142
+ }
@@ -0,0 +1,138 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { DeviceErrorCode, ToolGroup } from './constants.mjs';
4
+ import { DeviceToolError, displayPath, isProtectedPath, resolveInRoots } from './sandbox.mjs';
5
+
6
+ /**
7
+ * Theo dõi trên máy kích hoạt việc của Aivin (28/10/2026): "có tệp mới trong thư mục X thì…", "log Y có dòng ERROR thì…". BE giữ danh sách
8
+ * theo dõi (mỗi cái gắn một Automation Job kiểu `device`) và đẩy xuống bằng công cụ nội bộ `watch.set`; máy vừa nối thì tự xin lại. Có sự
9
+ * kiện → gom trong `COALESCE_MS` rồi báo BE một lần (`device:event`), giới hạn `MAX_EVENTS_PER_HOUR` mỗi theo dõi — một thư mục chép vào
10
+ * 500 tệp là một sự kiện, không phải 500 lượt agentic.
11
+ *
12
+ * Kiểu: `file_created` (tệp MỚI xuất hiện trong thư mục, lọc theo mẫu tên), `log_match` (dòng MỚI ghi thêm vào tệp khớp regex).
13
+ */
14
+
15
+ export const WatchKind = Object.freeze({ FILE_CREATED: 'file_created', LOG_MATCH: 'log_match' });
16
+
17
+ const COALESCE_MS = 5000;
18
+ const MAX_EVENTS_PER_HOUR = 30;
19
+ const MAX_ITEMS_PER_EVENT = 50;
20
+ const MAX_WATCHES = 50;
21
+ const LOG_READ_MAX = 256 * 1024;
22
+
23
+ const globRe = (pattern) => (pattern ? new RegExp(`^${String(pattern).split('*').map((s) => s.replace(/[.+?^${}()|[\]\\]/g, '\\$&')).join('.*')}$`, 'i') : null);
24
+
25
+ export function createWatchManager({ roots, emit, say = () => {}, coalesceMs = COALESCE_MS, settleMs = 1500 }) {
26
+ const active = new Map();
27
+
28
+ function stopOne(id) {
29
+ const w = active.get(id);
30
+ if (!w) return;
31
+ clearTimeout(w.timer);
32
+ try { w.watcher?.close(); } catch { /* đã đóng */ }
33
+ active.delete(id);
34
+ }
35
+
36
+ function flush(w) {
37
+ w.timer = null;
38
+ if (!w.pending.length) return;
39
+ const now = Date.now();
40
+ w.sent = w.sent.filter((t) => now - t < 3600_000);
41
+ if (w.sent.length >= MAX_EVENTS_PER_HOUR) { w.dropped += w.pending.length; w.pending = []; return; }
42
+ w.sent.push(now);
43
+ const items = w.pending.splice(0, MAX_ITEMS_PER_EVENT);
44
+ const more = w.pending.length;
45
+ w.pending = [];
46
+ emit({ watch_id: w.spec.id, kind: w.spec.kind, items, more: more || undefined, dropped_before: w.dropped || undefined, at: new Date().toISOString() });
47
+ w.dropped = 0;
48
+ }
49
+
50
+ function queue(w, item) {
51
+ w.pending.push(item);
52
+ if (!w.timer) w.timer = setTimeout(() => flush(w), coalesceMs);
53
+ }
54
+
55
+ function startFileCreated(spec, abs) {
56
+ const st = fs.statSync(abs, { throwIfNoEntry: false });
57
+ if (!st?.isDirectory()) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Not a folder: ${spec.path}`);
58
+ const match = globRe(spec.pattern);
59
+ const known = new Set();
60
+ const w = { spec, pending: [], sent: [], dropped: 0, timer: null };
61
+ const watcher = fs.watch(abs, { recursive: !!spec.recursive }, (_e, name) => {
62
+ if (!name) return;
63
+ const full = path.join(abs, String(name));
64
+ if (known.has(full) || isProtectedPath(full)) return;
65
+ if (match && !match.test(path.basename(full))) return;
66
+ // Đợi tệp ghi xong một chút rồi mới xét (trình duyệt tải xuống / chép tệp lớn bắn nhiều sự kiện).
67
+ setTimeout(() => {
68
+ const s = fs.statSync(full, { throwIfNoEntry: false });
69
+ if (!s?.isFile() || known.has(full)) return;
70
+ if (Date.now() - s.birthtimeMs > 10 * 60_000 && Date.now() - s.mtimeMs > 10 * 60_000) return;
71
+ known.add(full);
72
+ if (known.size > 5000) known.clear();
73
+ queue(w, { path: displayPath(roots, full), size: s.size });
74
+ }, settleMs);
75
+ });
76
+ watcher.on('error', () => { try { watcher.close(); } catch { /* đã đóng */ } say(`⚠️ Theo dõi "${spec.name || spec.id}" ngừng (thư mục không còn?)`); });
77
+ w.watcher = watcher;
78
+ return w;
79
+ }
80
+
81
+ function startLogMatch(spec, abs) {
82
+ const st = fs.statSync(abs, { throwIfNoEntry: false });
83
+ if (!st?.isFile()) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Not a file: ${spec.path}`);
84
+ let re;
85
+ try { re = new RegExp(String(spec.pattern || ''), 'i'); } catch { throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'pattern is not a valid regex'); }
86
+ const w = { spec, pending: [], sent: [], dropped: 0, timer: null, offset: st.size, partial: '' };
87
+ const readNew = () => {
88
+ const s = fs.statSync(abs, { throwIfNoEntry: false });
89
+ if (!s) return;
90
+ if (s.size < w.offset) w.offset = 0;
91
+ if (s.size === w.offset) return;
92
+ const len = Math.min(s.size - w.offset, LOG_READ_MAX);
93
+ const buf = Buffer.alloc(len);
94
+ const fd = fs.openSync(abs, 'r');
95
+ try { fs.readSync(fd, buf, 0, len, s.size - len); } finally { fs.closeSync(fd); }
96
+ w.offset = s.size;
97
+ const lines = (w.partial + buf.toString('utf8')).split(/\r?\n/);
98
+ w.partial = lines.pop() || '';
99
+ for (const line of lines) if (re.test(line)) queue(w, { line: line.slice(0, 500) });
100
+ };
101
+ const watcher = fs.watch(abs, () => { try { readNew(); } catch { /* tệp đang xoay vòng */ } });
102
+ watcher.on('error', () => { try { watcher.close(); } catch { /* đã đóng */ } });
103
+ w.watcher = watcher;
104
+ return w;
105
+ }
106
+
107
+ /** Đặt TOÀN BỘ danh sách theo dõi (BE là nguồn chân lý): bỏ cái không còn, mở cái mới, giữ cái không đổi. */
108
+ function set(list) {
109
+ const specs = (Array.isArray(list) ? list : []).slice(0, MAX_WATCHES).filter((s) => s && typeof s.id === 'string');
110
+ const want = new Map(specs.map((s) => [s.id, s]));
111
+ for (const id of [...active.keys()]) {
112
+ if (!want.has(id) || JSON.stringify(active.get(id).spec) !== JSON.stringify(want.get(id))) stopOne(id);
113
+ }
114
+ const errors = [];
115
+ for (const spec of specs) {
116
+ if (active.has(spec.id)) continue;
117
+ try {
118
+ const abs = resolveInRoots(roots, String(spec.path || ''));
119
+ const w = spec.kind === WatchKind.LOG_MATCH ? startLogMatch(spec, abs) : startFileCreated(spec, abs);
120
+ active.set(spec.id, w);
121
+ } catch (e) {
122
+ errors.push({ id: spec.id, error: e.message, code: e.code });
123
+ }
124
+ }
125
+ if (specs.length) say(`👁 Đang theo dõi ${active.size} mục trên máy cho Aivin`);
126
+ return { active: [...active.keys()], errors };
127
+ }
128
+
129
+ return { set, closeAll: () => [...active.keys()].forEach(stopOne), size: () => active.size };
130
+ }
131
+
132
+ /** Công cụ nội bộ (chỉ BE gọi) — đặt danh sách theo dõi. */
133
+ export function buildWatchTools(manager) {
134
+ return [
135
+ { name: 'watch.set', group: ToolGroup.SYSTEM, internal: true, handler: (a) => manager.set(a.watches),
136
+ description: 'BE-only: replace the list of folder / log watches that trigger Aivin jobs.', input_schema: { type: 'object', properties: {} } },
137
+ ];
138
+ }
@@ -0,0 +1,117 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import zlib from 'zlib';
4
+
5
+ /**
6
+ * Đoạn chữ đầu của một tệp để lập chỉ mục / xem trước: tệp chữ đọc thẳng; docx/xlsx/pptx/odt/ods/odp là tệp zip chứa XML — đọc bằng bộ
7
+ * giải zip nhỏ (thư mục trung tâm + inflateRaw của Node), không cần thư viện ngoài. PDF chưa đọc nội dung (chỉ tên + đường dẫn).
8
+ */
9
+
10
+ export const DOC_EXTENSIONS = new Set([
11
+ '.docx', '.doc', '.xlsx', '.xls', '.pptx', '.ppt', '.pdf', '.odt', '.ods', '.odp', '.rtf', '.txt', '.md', '.csv',
12
+ ]);
13
+ const PLAIN_EXTENSIONS = new Set(['.txt', '.md', '.csv', '.rtf']);
14
+ const MAX_ZIP_BYTES = 30 * 1024 * 1024;
15
+ const MAX_ENTRY_BYTES = 8 * 1024 * 1024;
16
+ const HEAD_BYTES = 16 * 1024;
17
+
18
+ /** Phần trong gói Office chứa chữ chính, theo thứ tự đọc. */
19
+ function officeParts(ext, names) {
20
+ if (ext === '.docx') return ['word/document.xml'];
21
+ if (ext === '.xlsx') return ['xl/sharedStrings.xml'];
22
+ if (ext === '.pptx') {
23
+ const slide = (n) => Number(/slide(\d+)\.xml$/.exec(n)?.[1] || 0);
24
+ return names.filter((n) => /^ppt\/slides\/slide\d+\.xml$/.test(n)).sort((a, b) => slide(a) - slide(b)).slice(0, 5);
25
+ }
26
+ if (['.odt', '.ods', '.odp'].includes(ext)) return ['content.xml'];
27
+ return [];
28
+ }
29
+
30
+ /** Đọc thư mục trung tâm của zip → { tên: { offset, method, compressedSize } }. */
31
+ function zipEntries(buf) {
32
+ const minEocd = Math.max(0, buf.length - 65_557);
33
+ let eocd = -1;
34
+ for (let i = buf.length - 22; i >= minEocd; i--) if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
35
+ if (eocd < 0) return {};
36
+ const count = buf.readUInt16LE(eocd + 10);
37
+ let at = buf.readUInt32LE(eocd + 16);
38
+ const out = {};
39
+ for (let i = 0; i < count && at + 46 <= buf.length; i++) {
40
+ if (buf.readUInt32LE(at) !== 0x02014b50) break;
41
+ const method = buf.readUInt16LE(at + 10);
42
+ const compressedSize = buf.readUInt32LE(at + 20);
43
+ const nameLen = buf.readUInt16LE(at + 28);
44
+ const extraLen = buf.readUInt16LE(at + 30);
45
+ const commentLen = buf.readUInt16LE(at + 32);
46
+ const offset = buf.readUInt32LE(at + 42);
47
+ out[buf.toString('utf8', at + 46, at + 46 + nameLen)] = { offset, method, compressedSize };
48
+ at += 46 + nameLen + extraLen + commentLen;
49
+ }
50
+ return out;
51
+ }
52
+
53
+ function zipRead(buf, entry) {
54
+ const at = entry.offset;
55
+ if (buf.readUInt32LE(at) !== 0x04034b50) return '';
56
+ const start = at + 30 + buf.readUInt16LE(at + 26) + buf.readUInt16LE(at + 28);
57
+ const raw = buf.subarray(start, start + entry.compressedSize);
58
+ if (entry.method === 0) return raw.toString('utf8');
59
+ if (entry.method !== 8) return '';
60
+ return zlib.inflateRawSync(raw, { maxOutputLength: MAX_ENTRY_BYTES }).toString('utf8');
61
+ }
62
+
63
+ /** XML Office → chữ: đoạn / ô / dòng thành khoảng trắng, bỏ thẻ, giải thực thể cơ bản. */
64
+ export function xmlToText(xml) {
65
+ return String(xml || '')
66
+ .replace(/<\/(w:p|a:p|text:p|text:h|si|row|table:table-row)>/g, ' \n')
67
+ .replace(/<(w:tab|w:br|text:tab|text:line-break)\b[^>]*\/>/g, ' ')
68
+ .replace(/<[^>]+>/g, '')
69
+ .replace(/&lt;/g, '<').replace(/&gt;/g, '>').replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, '&')
70
+ .replace(/[ \t\r\f\v]+/g, ' ')
71
+ .replace(/\s*\n\s*/g, '\n')
72
+ .trim();
73
+ }
74
+
75
+ function officeText(buf, ext) {
76
+ const entries = zipEntries(buf);
77
+ return officeParts(ext, Object.keys(entries))
78
+ .filter((name) => entries[name])
79
+ .map((name) => xmlToText(zipRead(buf, entries[name])))
80
+ .filter(Boolean)
81
+ .join('\n');
82
+ }
83
+
84
+ /** Chữ đầu tệp (tối đa `maxChars`). Lỗi / định dạng chưa đọc được → chuỗi rỗng. */
85
+ export async function extractDocText(abs, size, maxChars = 600) {
86
+ const ext = path.extname(abs).toLowerCase();
87
+ try {
88
+ if (PLAIN_EXTENSIONS.has(ext)) {
89
+ const handle = await fs.promises.open(abs, 'r');
90
+ try {
91
+ const buf = Buffer.alloc(Math.min(HEAD_BYTES, size));
92
+ const { bytesRead } = await handle.read(buf, 0, buf.length, 0);
93
+ return clean(buf.subarray(0, bytesRead).toString('utf8'), maxChars);
94
+ } finally {
95
+ await handle.close();
96
+ }
97
+ }
98
+ if (!officeParts(ext, ['ppt/slides/slide1.xml']).length || size > MAX_ZIP_BYTES) return '';
99
+ return clean(officeText(await fs.promises.readFile(abs), ext), maxChars);
100
+ } catch {
101
+ return '';
102
+ }
103
+ }
104
+
105
+ function clean(text, maxChars) {
106
+ const t = String(text || '').replaceAll(String.fromCharCode(0), '').replace(/\s+/g, ' ').trim();
107
+ return wellFormed(t.length > maxChars ? `${t.slice(0, maxChars)}…` : t);
108
+ }
109
+
110
+ /** Bỏ nửa ký tự lẻ (cắt ngang giữa emoji / ký tự ghép): dịch vụ vector của BE từ chối cả lô có chuỗi như vậy (chạy thật 27/10/2026). */
111
+ export function wellFormed(text) {
112
+ return String(text).replace(/[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/g, '�');
113
+ }
114
+
115
+ export function isDocFile(abs) {
116
+ return DOC_EXTENSIONS.has(path.extname(abs).toLowerCase());
117
+ }