@aivin-labs/cli 1.0.5 → 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.
Files changed (67) hide show
  1. package/README.md +263 -216
  2. package/bin/cli.mjs +1780 -1366
  3. package/bin/lib/browserAutomation.mjs +655 -648
  4. package/bin/lib/browserTui.mjs +276 -251
  5. package/bin/lib/cancellation.mjs +61 -0
  6. package/bin/lib/mcpProxy.mjs +869 -837
  7. package/bin/lib/missionStream.mjs +696 -691
  8. package/bin/lib/releaseKeys.mjs +9 -0
  9. package/bin/lib/remote/activityLog.mjs +68 -0
  10. package/bin/lib/remote/autoStart.mjs +457 -0
  11. package/bin/lib/remote/autoUpdate.mjs +129 -0
  12. package/bin/lib/remote/brand.mjs +60 -0
  13. package/bin/lib/remote/browserTunnel.mjs +292 -0
  14. package/bin/lib/remote/callLedger.mjs +134 -0
  15. package/bin/lib/remote/cdpPolicy.mjs +66 -0
  16. package/bin/lib/remote/client.mjs +726 -0
  17. package/bin/lib/remote/constants.mjs +173 -0
  18. package/bin/lib/remote/credentials.mjs +208 -0
  19. package/bin/lib/remote/daemonLock.mjs +86 -0
  20. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  21. package/bin/lib/remote/deviceMemory.mjs +246 -0
  22. package/bin/lib/remote/deviceProfile.mjs +142 -0
  23. package/bin/lib/remote/deviceWatches.mjs +138 -0
  24. package/bin/lib/remote/docText.mjs +117 -0
  25. package/bin/lib/remote/fileIndexer.mjs +399 -0
  26. package/bin/lib/remote/gui/index.mjs +245 -0
  27. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  28. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  29. package/bin/lib/remote/gui/windowsHostSource.mjs +904 -0
  30. package/bin/lib/remote/httpTransfer.mjs +89 -0
  31. package/bin/lib/remote/idempotency.mjs +135 -0
  32. package/bin/lib/remote/keepAwake.mjs +100 -0
  33. package/bin/lib/remote/localConfirm.mjs +268 -0
  34. package/bin/lib/remote/localPolicy.mjs +249 -0
  35. package/bin/lib/remote/mascot/assets.mjs +218 -0
  36. package/bin/lib/remote/mascot/hostSource.mjs +362 -0
  37. package/bin/lib/remote/mascot/index.mjs +322 -0
  38. package/bin/lib/remote/mascot/labels.mjs +83 -0
  39. package/bin/lib/remote/mascot/strings.mjs +189 -0
  40. package/bin/lib/remote/memberFsPool.mjs +134 -0
  41. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  42. package/bin/lib/remote/mission.mjs +156 -0
  43. package/bin/lib/remote/missionQuestion.mjs +63 -0
  44. package/bin/lib/remote/multiUser.mjs +344 -0
  45. package/bin/lib/remote/netProxy.mjs +145 -0
  46. package/bin/lib/remote/notify.mjs +58 -0
  47. package/bin/lib/remote/office/index.mjs +90 -0
  48. package/bin/lib/remote/policyCommand.mjs +93 -0
  49. package/bin/lib/remote/processes.mjs +217 -0
  50. package/bin/lib/remote/sandbox.mjs +221 -0
  51. package/bin/lib/remote/schedule.mjs +213 -0
  52. package/bin/lib/remote/scheduler.mjs +124 -0
  53. package/bin/lib/remote/textIndex.mjs +131 -0
  54. package/bin/lib/remote/tokenStore.mjs +77 -0
  55. package/bin/lib/remote/toolHandlers.mjs +726 -0
  56. package/bin/lib/remote/undoStore.mjs +242 -0
  57. package/bin/lib/remoteControl.mjs +26 -0
  58. package/bin/lib/scaffold.mjs +654 -653
  59. package/bin/lib/selfUpdate.mjs +71 -0
  60. package/bin/lib/update/binarySwap.mjs +63 -0
  61. package/bin/lib/update/constants.mjs +56 -0
  62. package/bin/lib/update/download.mjs +145 -0
  63. package/bin/lib/update/signature.mjs +42 -0
  64. package/bin/lib/update/state.mjs +205 -0
  65. package/bin/lib/update/versions.mjs +60 -0
  66. package/docs/CLI.md +1353 -1299
  67. package/package.json +71 -62
@@ -0,0 +1,213 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { spawn } from 'child_process';
4
+ import { DeviceErrorCode, REMOTE_CONFIG_DIR, ToolGroup } from './constants.mjs';
5
+ import { DeviceToolError, assertCommandAllowed } from './sandbox.mjs';
6
+
7
+ /**
8
+ * Lịch chạy định kỳ trên máy (28/10/2026) — một công cụ cho mọi hệ điều hành thay vì Planner tự viết `schtasks` / `crontab`: Windows Task
9
+ * Scheduler (thư mục `\Aivin\`), macOS / Linux crontab (mục có dấu `# aivin:<tên>`). AI chỉ thấy / sửa / xoá lịch của chính nó. Lệnh nằm
10
+ * trong tệp script ở thư mục cấu hình Aivin (không vướng giới hạn độ dài / trích dẫn của schtasks / cron). Mỗi lần đặt / xoá: kiểm lại
11
+ * bằng cách đọc lịch của hệ điều hành, ghi vào kho hoàn tác (hoàn tác = trả lịch về như trước).
12
+ */
13
+
14
+ const DIR = path.join(REMOTE_CONFIG_DIR, 'schedules');
15
+ const INDEX = path.join(DIR, 'index.json');
16
+ const NAME_RE = /^[A-Za-z0-9_-]{1,40}$/;
17
+ const EVERY = ['minute', 'hour', 'day', 'week'];
18
+ const WEEKDAYS = ['sun', 'mon', 'tue', 'wed', 'thu', 'fri', 'sat'];
19
+ const WIN_FOLDER = '\\Aivin\\';
20
+ const MARK = '# aivin:';
21
+
22
+ const str = (description) => ({ type: 'string', description });
23
+ const num = (description) => ({ type: 'number', description });
24
+ const schema = (properties, required = []) => ({ type: 'object', properties, required });
25
+
26
+ function run(cmd, argv, input) {
27
+ return new Promise((resolve) => {
28
+ const c = spawn(cmd, argv, { windowsHide: true });
29
+ let out = '';
30
+ let err = '';
31
+ c.stdout.on('data', (d) => { out += d; });
32
+ c.stderr.on('data', (d) => { err += d; });
33
+ c.on('error', (e) => resolve({ code: -1, out, err: e.message }));
34
+ c.on('close', (code) => resolve({ code, out, err }));
35
+ if (input !== undefined) c.stdin.end(input); else c.stdin.end();
36
+ });
37
+ }
38
+
39
+ function readIndex() {
40
+ try { return JSON.parse(fs.readFileSync(INDEX, 'utf8')) || {}; } catch { return {}; }
41
+ }
42
+
43
+ function writeIndex(index) {
44
+ fs.mkdirSync(DIR, { recursive: true });
45
+ fs.writeFileSync(INDEX, JSON.stringify(index, null, 2));
46
+ }
47
+
48
+ /** Kiểm + chuẩn hoá lịch. `at` "HH:MM", `weekday` mon..sun, `interval` cho minute / hour. */
49
+ export function normalizeSpec(a) {
50
+ const name = String(a.name || '');
51
+ if (!NAME_RE.test(name)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'name: 1-40 letters, digits, - or _');
52
+ const every = String(a.every || '').toLowerCase();
53
+ if (!EVERY.includes(every)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `every: ${EVERY.join(' | ')}`);
54
+ const command = String(a.command || '').trim();
55
+ if (!command) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Missing argument: command');
56
+ assertCommandAllowed(command);
57
+ const interval = Math.max(1, Math.min(Number(a.interval) || 1, every === 'minute' ? 59 : 23));
58
+ const at = String(a.at || '09:00');
59
+ if (!/^([01]?\d|2[0-3]):[0-5]\d$/.test(at)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'at: HH:MM');
60
+ const weekday = String(a.weekday || 'mon').toLowerCase().slice(0, 3);
61
+ if (!WEEKDAYS.includes(weekday)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `weekday: ${WEEKDAYS.join(' | ')}`);
62
+ return { name, every, interval, at, weekday, command };
63
+ }
64
+
65
+ /** Dòng cron của lịch (macOS / Linux). */
66
+ export function cronExpression(spec) {
67
+ const [h, m] = spec.at.split(':').map(Number);
68
+ if (spec.every === 'minute') return `*/${spec.interval} * * * *`;
69
+ if (spec.every === 'hour') return `0 */${spec.interval} * * *`;
70
+ if (spec.every === 'day') return `${m} ${h} * * *`;
71
+ return `${m} ${h} * * ${WEEKDAYS.indexOf(spec.weekday)}`;
72
+ }
73
+
74
+ function scriptPath(name) {
75
+ return path.join(DIR, process.platform === 'win32' ? `${name}.ps1` : `${name}.sh`);
76
+ }
77
+
78
+ function writeScript(spec) {
79
+ fs.mkdirSync(DIR, { recursive: true });
80
+ const file = scriptPath(spec.name);
81
+ const log = `${file}.log`;
82
+ if (process.platform === 'win32') fs.writeFileSync(file, `& {\n${spec.command}\n} *>> "${log}"\n`);
83
+ else { fs.writeFileSync(file, `#!/bin/sh\n${spec.command}\n`, { mode: 0o700 }); fs.chmodSync(file, 0o700); }
84
+ return { file, log };
85
+ }
86
+
87
+ // ── Windows ─────────────────────────────────────────────────────────────────────────────────────
88
+
89
+ async function winAdd(spec) {
90
+ const { file } = writeScript(spec);
91
+ const tr = `powershell.exe -NoProfile -NonInteractive -ExecutionPolicy Bypass -WindowStyle Hidden -File "${file}"`;
92
+ const sc = { minute: ['/SC', 'MINUTE', '/MO', String(spec.interval)], hour: ['/SC', 'HOURLY', '/MO', String(spec.interval)], day: ['/SC', 'DAILY', '/ST', spec.at], week: ['/SC', 'WEEKLY', '/D', spec.weekday.toUpperCase(), '/ST', spec.at] }[spec.every];
93
+ const res = await run('schtasks', ['/Create', '/F', '/TN', `${WIN_FOLDER}${spec.name}`, '/TR', tr, ...sc]);
94
+ if (res.code !== 0) throw new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `schtasks: ${(res.err || res.out).trim()}`);
95
+ }
96
+
97
+ async function winRemove(name) {
98
+ await run('schtasks', ['/Delete', '/F', '/TN', `${WIN_FOLDER}${name}`]);
99
+ }
100
+
101
+ async function winQuery(name) {
102
+ const res = await run('schtasks', ['/Query', '/TN', `${WIN_FOLDER}${name}`, '/FO', 'LIST', '/V']);
103
+ if (res.code !== 0) return null;
104
+ const field = (label) => res.out.split(/\r?\n/).find((l) => l.toLowerCase().startsWith(label))?.split(':').slice(1).join(':').trim();
105
+ return { installed: true, next_run: field('next run time'), status: field('status'), last_result: field('last result') };
106
+ }
107
+
108
+ // ── macOS / Linux (crontab) ───────────────────────────────────────────────────────────────────────
109
+
110
+ async function readCrontab() {
111
+ const res = await run('crontab', ['-l']);
112
+ return res.code === 0 ? res.out : '';
113
+ }
114
+
115
+ /** Bỏ mục của `name` (dòng dấu + dòng lệnh ngay sau) khỏi crontab. */
116
+ export function withoutCronEntry(text, name) {
117
+ const lines = text.split('\n');
118
+ const out = [];
119
+ for (let i = 0; i < lines.length; i++) {
120
+ if (lines[i].trim() === `${MARK}${name}`) { i++; continue; }
121
+ out.push(lines[i]);
122
+ }
123
+ return out.join('\n').replace(/\n*$/, '\n');
124
+ }
125
+
126
+ async function writeCrontab(text) {
127
+ const res = await run('crontab', ['-'], text);
128
+ if (res.code !== 0) throw new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `crontab: ${(res.err || res.out).trim()}`);
129
+ }
130
+
131
+ async function cronAdd(spec) {
132
+ const { file, log } = writeScript(spec);
133
+ const current = withoutCronEntry(await readCrontab(), spec.name);
134
+ await writeCrontab(`${current.trim() ? `${current.trimEnd()}\n` : ''}${MARK}${spec.name}\n${cronExpression(spec)} /bin/sh "${file}" >> "${log}" 2>&1\n`);
135
+ }
136
+
137
+ async function cronRemove(name) {
138
+ const current = await readCrontab();
139
+ if (current.includes(`${MARK}${name}`)) await writeCrontab(withoutCronEntry(current, name));
140
+ }
141
+
142
+ async function cronQuery(name) {
143
+ const lines = (await readCrontab()).split('\n');
144
+ const i = lines.findIndex((l) => l.trim() === `${MARK}${name}`);
145
+ return i >= 0 && lines[i + 1] ? { installed: true, cron: lines[i + 1].trim() } : null;
146
+ }
147
+
148
+ const os = {
149
+ add: (spec) => (process.platform === 'win32' ? winAdd(spec) : cronAdd(spec)),
150
+ remove: (name) => (process.platform === 'win32' ? winRemove(name) : cronRemove(name)),
151
+ query: (name) => (process.platform === 'win32' ? winQuery(name) : cronQuery(name)),
152
+ };
153
+
154
+ /** Đặt / xoá lịch + cập nhật danh mục; trả lịch trước đó (để hoàn tác). */
155
+ async function apply(spec, name) {
156
+ const index = readIndex();
157
+ const previous = index[name] || null;
158
+ if (spec) {
159
+ await os.add(spec);
160
+ index[name] = spec;
161
+ } else {
162
+ await os.remove(name);
163
+ delete index[name];
164
+ fs.rmSync(scriptPath(name), { force: true });
165
+ }
166
+ writeIndex(index);
167
+ return previous;
168
+ }
169
+
170
+ export function createScheduleManager({ undo } = {}) {
171
+ // Hoàn tác: trả lịch về như trước lần đặt / xoá.
172
+ undo?.registerHandler('schedule', async (item) => {
173
+ await apply(item.previous || null, item.name);
174
+ return { schedule_restored: item.name };
175
+ });
176
+
177
+ async function set(args) {
178
+ const action = String(args.action || 'add');
179
+ const name = String(args.name || '');
180
+ if (action === 'remove') {
181
+ if (!NAME_RE.test(name)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'name required');
182
+ const previous = await apply(null, name);
183
+ undo?.begin(args.undo_group, 'schedule').custom('schedule', { name, previous });
184
+ const still = await os.query(name);
185
+ return { removed: name, existed: !!previous, verified: !still };
186
+ }
187
+ const spec = normalizeSpec(args);
188
+ const previous = await apply(spec, spec.name);
189
+ undo?.begin(args.undo_group, 'schedule').custom('schedule', { name: spec.name, previous });
190
+ // Kiểm lại: đọc lịch thật của hệ điều hành, không tin lệnh đặt đã chạy.
191
+ const installed = await os.query(spec.name);
192
+ return { name: spec.name, schedule: spec.every === 'week' ? `${spec.weekday} ${spec.at}` : spec.every === 'day' ? `daily ${spec.at}` : `every ${spec.interval} ${spec.every}(s)`, verified: !!installed, ...(installed || {}), replaced: !!previous };
193
+ }
194
+
195
+ async function list() {
196
+ const index = readIndex();
197
+ const items = await Promise.all(Object.values(index).map(async (s) => ({ ...s, ...(await os.query(s.name) || { installed: false }) })));
198
+ return { schedules: items };
199
+ }
200
+
201
+ return { set, list };
202
+ }
203
+
204
+ export function buildScheduleTools(sm) {
205
+ return [
206
+ { name: 'sys.schedule', group: ToolGroup.SYSTEM, handler: (a) => sm.set(a),
207
+ description: `Create, replace or remove a recurring job on this computer (${process.platform === 'win32' ? 'Windows Task Scheduler' : 'crontab'}), managed by Aivin: action add | remove; every minute | hour (with interval) | day (at HH:MM) | week (weekday + at). The command runs in ${process.platform === 'win32' ? 'PowerShell' : 'sh'}; its output goes to a log. Verifies the job is installed and can be undone.`,
208
+ input_schema: schema({ action: str('add | remove'), name: str('job name: letters, digits, - _'), command: str('command to run'), every: str('minute | hour | day | week'), interval: num('for minute / hour, default 1'), at: str('HH:MM for day / week'), weekday: str('mon..sun for week') }, ['action', 'name']) },
209
+ { name: 'sys.schedules', group: ToolGroup.SYSTEM, read_only: true, handler: () => sm.list(),
210
+ description: 'Recurring jobs Aivin set up on this computer, with whether each is installed and its next run.',
211
+ input_schema: schema({}) },
212
+ ];
213
+ }
@@ -0,0 +1,124 @@
1
+ import { DEFAULT_GROUP_LIMITS, DeviceErrorCode } from './constants.mjs';
2
+ import { DeviceToolError } from './sandbox.mjs';
3
+
4
+ function createSemaphore(limit) {
5
+ let active = 0;
6
+ const queue = [];
7
+ const release = () => {
8
+ active--;
9
+ const next = queue.shift();
10
+ if (next) { active++; next(); }
11
+ };
12
+ return {
13
+ async acquire() {
14
+ if (active < limit) { active++; return release; }
15
+ await new Promise((resolve) => queue.push(resolve));
16
+ return release;
17
+ },
18
+ stats: () => ({ active, queued: queue.length, limit }),
19
+ };
20
+ }
21
+
22
+ function groupLimit(group) {
23
+ const fromEnv = Number(process.env[`AIVIN_REMOTE_LIMIT_${String(group).toUpperCase()}`]);
24
+ return Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : (DEFAULT_GROUP_LIMITS[group] ?? 4);
25
+ }
26
+
27
+ /**
28
+ * Bộ điều phối lời gọi trên máy: mỗi nhóm công cụ một semaphore (đọc tệp 16, chạy lệnh 3…), thao tác ghi khoá theo từng đường dẫn
29
+ * (hai lệnh ghi cùng tệp chạy lần lượt, khác tệp chạy song song), mỗi lời gọi một AbortController (huỷ / hết giờ → dừng cả cây tiến
30
+ * trình con).
31
+ *
32
+ * `scopeLimits` (máy tính tổ chức): thêm trần theo từng thành viên (`call.user_scope`) trong mỗi nhóm. Lấy chỗ của vùng TRƯỚC rồi mới
33
+ * tới chỗ chung — lời gọi đang chờ trần của riêng mình không giữ chỗ chung của người khác. Không truyền → như máy một người.
34
+ */
35
+ export function createScheduler({ scopeLimits = null } = {}) {
36
+ const semaphores = new Map();
37
+ const scopeSemaphores = new Map();
38
+ const pathLocks = new Map();
39
+ const inflight = new Map();
40
+
41
+ const semaphoreOf = (group) => {
42
+ if (!semaphores.has(group)) semaphores.set(group, createSemaphore(groupLimit(group)));
43
+ return semaphores.get(group);
44
+ };
45
+
46
+ const scopeSemaphoreOf = (scope, group) => {
47
+ const fromEnv = Number(process.env[`AIVIN_REMOTE_SCOPE_LIMIT_${String(group).toUpperCase()}`]);
48
+ const limit = Number.isFinite(fromEnv) && fromEnv > 0 ? fromEnv : scopeLimits?.[group];
49
+ if (!limit || typeof scope !== 'string' || !scope) return null;
50
+ const key = `${scope}\u0000${group}`;
51
+ if (!scopeSemaphores.has(key)) scopeSemaphores.set(key, createSemaphore(limit));
52
+ return scopeSemaphores.get(key);
53
+ };
54
+
55
+ async function withPathLocks(keys, fn) {
56
+ const sorted = [...new Set(keys)].sort();
57
+ const previous = sorted.map((k) => pathLocks.get(k) || Promise.resolve());
58
+ let done;
59
+ const mine = new Promise((resolve) => { done = resolve; });
60
+ sorted.forEach((k) => pathLocks.set(k, mine));
61
+ try {
62
+ await Promise.all(previous);
63
+ return await fn();
64
+ } finally {
65
+ done();
66
+ sorted.forEach((k) => { if (pathLocks.get(k) === mine) pathLocks.delete(k); });
67
+ }
68
+ }
69
+
70
+ /**
71
+ * Chạy một lời gọi. `spec`: { group, lockKeys?(args) }, `handler(args, ctx)`; ctx = { signal, onOutput }.
72
+ * Không ném lỗi: trả { ok, result } hoặc { ok:false, error, error_code }.
73
+ */
74
+ async function run(call, spec, handler, { onOutput } = {}) {
75
+ const controller = new AbortController();
76
+ inflight.set(call.call_id, controller);
77
+ const startedAt = Date.now();
78
+ const timeoutMs = Math.max(1000, Number(call.timeout_ms) || 60_000);
79
+ const timer = setTimeout(() => controller.abort(new DeviceToolError(DeviceErrorCode.CALL_TIMEOUT, `Timed out after ${timeoutMs} ms`)), timeoutMs);
80
+ const releaseScope = scopeLimits ? await scopeSemaphoreOf(call.user_scope, spec.group)?.acquire() : null;
81
+ const release = await semaphoreOf(spec.group).acquire();
82
+ try {
83
+ if (controller.signal.aborted) throw controller.signal.reason;
84
+ const exec = () => handler(call.args || {}, { signal: controller.signal, onOutput, timeoutMs });
85
+ const keys = spec.lockKeys ? spec.lockKeys(call.args || {}) : [];
86
+ const result = keys.length ? await withPathLocks(keys, exec) : await exec();
87
+ return { ok: true, result, duration_ms: Date.now() - startedAt };
88
+ } catch (error) {
89
+ const reason = controller.signal.aborted ? controller.signal.reason : error;
90
+ return {
91
+ ok: false,
92
+ error: reason?.message || String(reason),
93
+ error_code: reason?.code || DeviceErrorCode.EXECUTION_FAILED,
94
+ duration_ms: Date.now() - startedAt,
95
+ };
96
+ } finally {
97
+ clearTimeout(timer);
98
+ release();
99
+ releaseScope?.();
100
+ inflight.delete(call.call_id);
101
+ }
102
+ }
103
+
104
+ function cancel(callIds) {
105
+ for (const id of callIds || []) {
106
+ inflight.get(id)?.abort(new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled by server'));
107
+ }
108
+ }
109
+
110
+ /** Huỷ mọi lời gọi đang chạy; chờ tối đa `waitMs` cho chúng dọn xong (giết cây tiến trình con) — dùng khi tạm dừng / dừng / bị thu hồi. */
111
+ async function cancelAll(message = 'Cancelled on this device', { waitMs = 5000 } = {}) {
112
+ for (const controller of inflight.values()) controller.abort(new DeviceToolError(DeviceErrorCode.CANCELLED, message));
113
+ const deadline = Date.now() + waitMs;
114
+ while (inflight.size && Date.now() < deadline) await new Promise((r) => setTimeout(r, 50));
115
+ }
116
+
117
+ return {
118
+ run,
119
+ cancel,
120
+ cancelAll,
121
+ stats: () => Object.fromEntries([...semaphores.entries()].map(([g, s]) => [g, s.stats()])),
122
+ inflightCount: () => inflight.size,
123
+ };
124
+ }
@@ -0,0 +1,131 @@
1
+ /**
2
+ * Chỉ mục tìm kiếm trong RAM, dùng chung cho bộ nhớ trên máy và chỉ mục tệp: tách từ theo Unicode (mọi ngôn ngữ, bỏ dấu, tách
3
+ * camelCase/snake_case, chữ Hán/Kana/Hangul tách cặp ký tự), chấm điểm BM25; cosine cho vector int8 do BE tính (bge-m3).
4
+ */
5
+
6
+ const CJK = /[\p{Script=Han}\p{Script=Hiragana}\p{Script=Katakana}\p{Script=Hangul}]/u;
7
+ const MIN_TOKEN = 2;
8
+ const MAX_TOKEN = 48;
9
+ const K1 = 1.2;
10
+ const B = 0.75;
11
+ const PREFIX_MIN = 4;
12
+ const PREFIX_MAX_TERMS = 30;
13
+
14
+ export function normalizeText(text) {
15
+ return String(text || '')
16
+ .replace(/([a-z0-9])([A-Z])/g, '$1 $2')
17
+ .normalize('NFD')
18
+ .replace(/\p{M}+/gu, '')
19
+ .replace(/[đĐ]/g, 'd')
20
+ .toLowerCase();
21
+ }
22
+
23
+ /** Tách từ: chữ/số Unicode; cụm CJK (không có dấu cách) → các cặp ký tự liền nhau. */
24
+ export function tokenize(text) {
25
+ const out = [];
26
+ for (const raw of normalizeText(text).split(/[^\p{L}\p{N}]+/u)) {
27
+ if (!raw) continue;
28
+ if (CJK.test(raw)) {
29
+ const chars = [...raw];
30
+ if (chars.length === 1) out.push(raw);
31
+ for (let i = 0; i + 1 < chars.length; i++) out.push(chars[i] + chars[i + 1]);
32
+ continue;
33
+ }
34
+ if (raw.length >= MIN_TOKEN && raw.length <= MAX_TOKEN) out.push(raw);
35
+ }
36
+ return out;
37
+ }
38
+
39
+ /** Chỉ mục BM25 thêm/xoá từng tài liệu, không dựng lại cả khối. */
40
+ export function createTextIndex() {
41
+ const docs = new Map(); // id → { len, tf: Map<term, n> }
42
+ const postings = new Map(); // term → Set<id>
43
+ let totalLen = 0;
44
+
45
+ function remove(id) {
46
+ const doc = docs.get(id);
47
+ if (!doc) return;
48
+ for (const term of doc.tf.keys()) {
49
+ const set = postings.get(term);
50
+ set?.delete(id);
51
+ if (set && !set.size) postings.delete(term);
52
+ }
53
+ totalLen -= doc.len;
54
+ docs.delete(id);
55
+ }
56
+
57
+ function add(id, text) {
58
+ remove(id);
59
+ const tokens = tokenize(text);
60
+ const tf = new Map();
61
+ for (const t of tokens) tf.set(t, (tf.get(t) || 0) + 1);
62
+ docs.set(id, { len: tokens.length, tf });
63
+ totalLen += tokens.length;
64
+ for (const term of tf.keys()) {
65
+ if (!postings.has(term)) postings.set(term, new Set());
66
+ postings.get(term).add(id);
67
+ }
68
+ }
69
+
70
+ /** Từ trong câu hỏi không có nguyên dạng → khớp tiền tố ("auth" ↔ "authentication"), có trần để không quét cả từ điển mỗi lần. */
71
+ function expand(term) {
72
+ if (postings.has(term) || term.length < PREFIX_MIN) return postings.has(term) ? [term] : [];
73
+ const found = [];
74
+ for (const key of postings.keys()) {
75
+ if (key.startsWith(term)) {
76
+ found.push(key);
77
+ if (found.length >= PREFIX_MAX_TERMS) break;
78
+ }
79
+ }
80
+ return found;
81
+ }
82
+
83
+ function search(query, { limit = 10, filter } = {}) {
84
+ const n = docs.size;
85
+ if (!n) return [];
86
+ const avg = totalLen / n || 1;
87
+ const scores = new Map();
88
+ for (const qTerm of new Set(tokenize(query))) {
89
+ for (const term of expand(qTerm)) {
90
+ const ids = postings.get(term);
91
+ if (!ids) continue;
92
+ const idf = Math.log(1 + (n - ids.size + 0.5) / (ids.size + 0.5));
93
+ const weight = term === qTerm ? 1 : 0.6;
94
+ for (const id of ids) {
95
+ if (filter && !filter(id)) continue;
96
+ const doc = docs.get(id);
97
+ const f = doc.tf.get(term);
98
+ const s = idf * ((f * (K1 + 1)) / (f + K1 * (1 - B + (B * doc.len) / avg))) * weight;
99
+ scores.set(id, (scores.get(id) || 0) + s);
100
+ }
101
+ }
102
+ }
103
+ return [...scores.entries()].sort((a, b) => b[1] - a[1]).slice(0, limit).map(([id, score]) => ({ id, score }));
104
+ }
105
+
106
+ return { add, remove, search, size: () => docs.size, clear: () => { docs.clear(); postings.clear(); totalLen = 0; } };
107
+ }
108
+
109
+ export function decodeInt8(base64) {
110
+ if (!base64) return null;
111
+ const buf = Buffer.from(String(base64), 'base64');
112
+ return buf.length ? new Int8Array(buf.buffer, buf.byteOffset, buf.byteLength) : null;
113
+ }
114
+
115
+ /** Cosine xấp xỉ giữa hai vector int8 đã chuẩn hoá (BE lượng tử `round(v/|v| * 127)`). */
116
+ export function int8Cosine(a, b) {
117
+ if (!a || !b) return 0;
118
+ const n = Math.min(a.length, b.length);
119
+ let dot = 0;
120
+ for (let i = 0; i < n; i++) dot += a[i] * b[i];
121
+ return dot / (127 * 127);
122
+ }
123
+
124
+ /** Gộp nhiều bảng xếp hạng (Reciprocal Rank Fusion) — không cần đưa BM25 và cosine về cùng thang điểm. */
125
+ export function fuseRankings(rankings, k = 60) {
126
+ const fused = new Map();
127
+ for (const ranking of rankings) {
128
+ ranking.forEach((id, rank) => fused.set(id, (fused.get(id) || 0) + 1 / (k + rank + 1)));
129
+ }
130
+ return [...fused.entries()].sort((a, b) => b[1] - a[1]).map(([id]) => id);
131
+ }
@@ -0,0 +1,77 @@
1
+ import { execFileSync } from 'child_process';
2
+ import fs from 'fs';
3
+
4
+ /**
5
+ * Token thiết bị cất trong kho bí mật của hệ điều hành (29/10/2026). Trước đây `~/.aivin/device-credentials.json` giữ token dạng chữ thường
6
+ * (chỉ có quyền 600) — chép thư mục `.aivin` (sao lưu, đồng bộ đám mây, ổ cứng bị lấy) là mang theo được quyền điều khiển máy.
7
+ * - Windows: DPAPI phạm vi người dùng hiện tại (`ProtectedData`, qua PowerShell) — bản mã nằm trong tệp, chỉ đúng tài khoản Windows trên
8
+ * đúng máy này giải được.
9
+ * - macOS: Keychain đăng nhập (`security`), tệp chỉ còn dấu "token ở Keychain".
10
+ * - Linux: Secret Service (`secret-tool`, GNOME Keyring / KWallet) khi có phiên D-Bus; máy chủ không có kho → tệp quyền 600 như cũ.
11
+ * Bảo vệ khỏi chép tệp sang nơi khác; KHÔNG chống được mã độc chạy dưới chính tài khoản người dùng (nó gọi được cùng API).
12
+ */
13
+
14
+ export const TokenStoreKind = Object.freeze({ DPAPI: 'dpapi', KEYCHAIN: 'keychain', LIBSECRET: 'libsecret', FILE: 'file' });
15
+
16
+ const SERVICE = 'aivin-device-token';
17
+ /** Thêm vào DPAPI để ứng dụng khác của cùng người dùng không giải mã nhầm / tình cờ (không phải bí mật). */
18
+ const DPAPI_ENTROPY = 'aivin-device-token-v1';
19
+
20
+ const PS = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command'];
21
+ const DPAPI_PROTECT = `Add-Type -AssemblyName System.Security; $e = [Text.Encoding]::UTF8.GetBytes('${DPAPI_ENTROPY}'); $b = [Text.Encoding]::UTF8.GetBytes([Console]::In.ReadToEnd()); [Convert]::ToBase64String([Security.Cryptography.ProtectedData]::Protect($b, $e, 'CurrentUser'))`;
22
+ const DPAPI_UNPROTECT = `Add-Type -AssemblyName System.Security; $e = [Text.Encoding]::UTF8.GetBytes('${DPAPI_ENTROPY}'); $b = [Convert]::FromBase64String([Console]::In.ReadToEnd().Trim()); [Text.Encoding]::UTF8.GetString([Security.Cryptography.ProtectedData]::Unprotect($b, $e, 'CurrentUser'))`;
23
+
24
+ const run = (cmd, args, input) => execFileSync(cmd, args, { input, encoding: 'utf8', timeout: 20_000, windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] }).trim();
25
+
26
+ /** Kho dùng trên máy này. `AIVIN_TOKEN_STORE=file` ép tệp thường (máy không có kho / gỡ lỗi). */
27
+ export function preferredTokenStore({ platform = process.platform, env = process.env, exists = fs.existsSync } = {}) {
28
+ const forced = String(env.AIVIN_TOKEN_STORE || '').toLowerCase();
29
+ if (Object.values(TokenStoreKind).includes(forced)) return forced;
30
+ if (platform === 'win32') return TokenStoreKind.DPAPI;
31
+ if (platform === 'darwin' && exists('/usr/bin/security')) return TokenStoreKind.KEYCHAIN;
32
+ if (platform === 'linux' && env.DBUS_SESSION_BUS_ADDRESS && ['/usr/bin/secret-tool', '/bin/secret-tool'].some((p) => exists(p))) return TokenStoreKind.LIBSECRET;
33
+ return TokenStoreKind.FILE;
34
+ }
35
+
36
+ const quote = (s) => `"${String(s).replace(/["\\]/g, '\\$&')}"`;
37
+
38
+ /**
39
+ * Cất token → phần ghi vào tệp: `{ token_store, token_enc? }` (kho hệ điều hành) hoặc `{ device_token }` (tệp thường). Kho lỗi (Keychain bị
40
+ * khoá, không có keyring…) → tệp thường, kèm `fallback_reason` để in ra.
41
+ */
42
+ export function sealToken(token, { account, store = preferredTokenStore() } = {}) {
43
+ try {
44
+ if (store === TokenStoreKind.DPAPI) return { token_store: store, token_enc: run('powershell.exe', [...PS, DPAPI_PROTECT], token) };
45
+ if (store === TokenStoreKind.KEYCHAIN) {
46
+ run('/usr/bin/security', ['-i'], `add-generic-password -U -a ${quote(account)} -s ${SERVICE} -l "Aivin device token" -w ${quote(token)}\n`);
47
+ return { token_store: store };
48
+ }
49
+ if (store === TokenStoreKind.LIBSECRET) {
50
+ run('secret-tool', ['store', '--label=Aivin device token', 'service', SERVICE, 'account', account], token);
51
+ return { token_store: store };
52
+ }
53
+ } catch (e) {
54
+ return { device_token: token, fallback_reason: String(e?.stderr || e?.message || e).trim().slice(0, 200) };
55
+ }
56
+ return { device_token: token };
57
+ }
58
+
59
+ /** Lấy lại token từ bản ghi trong tệp — `null` khi không giải được (tệp chép từ máy / tài khoản khác, kho đã xoá). */
60
+ export function openToken(record) {
61
+ if (!record) return null;
62
+ if (record.device_token) return record.device_token;
63
+ try {
64
+ if (record.token_store === TokenStoreKind.DPAPI && record.token_enc) return run('powershell.exe', [...PS, DPAPI_UNPROTECT], record.token_enc) || null;
65
+ if (record.token_store === TokenStoreKind.KEYCHAIN) return run('/usr/bin/security', ['find-generic-password', '-a', record.device_id, '-s', SERVICE, '-w']) || null;
66
+ if (record.token_store === TokenStoreKind.LIBSECRET) return run('secret-tool', ['lookup', 'service', SERVICE, 'account', record.device_id]) || null;
67
+ } catch { /* không giải được */ }
68
+ return null;
69
+ }
70
+
71
+ /** Xoá token khỏi kho hệ điều hành (DPAPI / tệp thường: xoá tệp là đủ). */
72
+ export function forgetToken(record) {
73
+ try {
74
+ if (record?.token_store === TokenStoreKind.KEYCHAIN) run('/usr/bin/security', ['delete-generic-password', '-a', record.device_id, '-s', SERVICE]);
75
+ if (record?.token_store === TokenStoreKind.LIBSECRET) run('secret-tool', ['clear', 'service', SERVICE, 'account', record.device_id]);
76
+ } catch { /* không có thì thôi */ }
77
+ }