@aivin-labs/cli 1.0.4 → 1.0.8
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 +263 -216
- package/bin/cli.mjs +1780 -1361
- package/bin/lib/browserAutomation.mjs +655 -648
- package/bin/lib/browserTui.mjs +276 -245
- package/bin/lib/cancellation.mjs +61 -0
- package/bin/lib/codegen.mjs +61 -5
- package/bin/lib/connectors.mjs +55 -21
- package/bin/lib/deploy.mjs +25 -2
- package/bin/lib/mcpProxy.mjs +869 -773
- package/bin/lib/mission.mjs +13 -1
- package/bin/lib/missionStream.mjs +696 -660
- package/bin/lib/pluginAuthResolve.mjs +127 -0
- package/bin/lib/pluginTrigger.mjs +207 -90
- package/bin/lib/releaseKeys.mjs +9 -0
- package/bin/lib/remote/activityLog.mjs +68 -0
- package/bin/lib/remote/autoStart.mjs +457 -0
- package/bin/lib/remote/autoUpdate.mjs +129 -0
- package/bin/lib/remote/brand.mjs +60 -0
- package/bin/lib/remote/browserTunnel.mjs +292 -0
- package/bin/lib/remote/callLedger.mjs +134 -0
- package/bin/lib/remote/cdpPolicy.mjs +66 -0
- package/bin/lib/remote/client.mjs +726 -0
- package/bin/lib/remote/constants.mjs +173 -0
- package/bin/lib/remote/credentials.mjs +208 -0
- package/bin/lib/remote/daemonLock.mjs +86 -0
- package/bin/lib/remote/dailyBrowser.mjs +371 -0
- package/bin/lib/remote/deviceMemory.mjs +246 -0
- package/bin/lib/remote/deviceProfile.mjs +142 -0
- package/bin/lib/remote/deviceWatches.mjs +138 -0
- package/bin/lib/remote/docText.mjs +117 -0
- package/bin/lib/remote/fileIndexer.mjs +399 -0
- package/bin/lib/remote/gui/index.mjs +245 -0
- package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
- package/bin/lib/remote/gui/windowsHost.mjs +109 -0
- package/bin/lib/remote/gui/windowsHostSource.mjs +904 -0
- package/bin/lib/remote/httpTransfer.mjs +89 -0
- package/bin/lib/remote/idempotency.mjs +135 -0
- package/bin/lib/remote/keepAwake.mjs +100 -0
- package/bin/lib/remote/localConfirm.mjs +268 -0
- package/bin/lib/remote/localPolicy.mjs +249 -0
- package/bin/lib/remote/mascot/assets.mjs +218 -0
- package/bin/lib/remote/mascot/hostSource.mjs +362 -0
- package/bin/lib/remote/mascot/index.mjs +322 -0
- package/bin/lib/remote/mascot/labels.mjs +83 -0
- package/bin/lib/remote/mascot/strings.mjs +189 -0
- package/bin/lib/remote/memberFsPool.mjs +134 -0
- package/bin/lib/remote/memberFsWorker.mjs +60 -0
- package/bin/lib/remote/mission.mjs +156 -0
- package/bin/lib/remote/missionQuestion.mjs +63 -0
- package/bin/lib/remote/multiUser.mjs +344 -0
- package/bin/lib/remote/netProxy.mjs +145 -0
- package/bin/lib/remote/notify.mjs +58 -0
- package/bin/lib/remote/office/index.mjs +90 -0
- package/bin/lib/remote/policyCommand.mjs +93 -0
- package/bin/lib/remote/processes.mjs +217 -0
- package/bin/lib/remote/sandbox.mjs +221 -0
- package/bin/lib/remote/schedule.mjs +213 -0
- package/bin/lib/remote/scheduler.mjs +124 -0
- package/bin/lib/remote/textIndex.mjs +131 -0
- package/bin/lib/remote/tokenStore.mjs +77 -0
- package/bin/lib/remote/toolHandlers.mjs +726 -0
- package/bin/lib/remote/undoStore.mjs +242 -0
- package/bin/lib/remoteControl.mjs +26 -0
- package/bin/lib/scaffold.mjs +654 -653
- package/bin/lib/selfUpdate.mjs +71 -0
- package/bin/lib/store.mjs +16 -2
- package/bin/lib/tasks.mjs +52 -8
- package/bin/lib/update/binarySwap.mjs +63 -0
- package/bin/lib/update/constants.mjs +56 -0
- package/bin/lib/update/download.mjs +145 -0
- package/bin/lib/update/signature.mjs +42 -0
- package/bin/lib/update/state.mjs +205 -0
- package/bin/lib/update/versions.mjs +60 -0
- package/bin/lib/util.mjs +8 -0
- package/docs/CLI.md +1353 -1274
- package/package.json +71 -62
|
@@ -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(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, "'").replace(/&/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 || '').replace(/\u0000/g, '').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
|
+
}
|