@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,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,209 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import WSClient from 'ws';
5
+
6
+ /**
7
+ * Gom các tab AI đang làm vào một nhóm tab (tab group) trong cửa sổ Aivin (29/10/2026) — mỗi đường hầm (nhiệm vụ) một nhóm, có tên + màu riêng.
8
+ *
9
+ * CDP không có lệnh nào cho nhóm tab — chỉ API tiện ích `chrome.tabGroups` làm được. Nên CLI ghi một tiện ích nhỏ vào `~/.aivin/browser-extension/
10
+ * tab-groups` và nạp qua CDP (`Extensions.loadUnpacked` — Chrome 137+ bỏ qua `--load-extension`; cần cửa sổ mở với
11
+ * `--enable-unsafe-extension-debugging`, localBrowser.mjs thêm cờ này), rồi chạy hàm `aivinGroup` trong service worker của tiện ích qua một kết nối CDP
12
+ * riêng của CLI. Đích CDP → id tab: `chrome.debugger.getTargets()` (quyền `debugger`; chỉ liệt kê, không gắn vào tab nào).
13
+ *
14
+ * Chỉ cho cửa sổ Aivin: trình duyệt hằng ngày của người dùng không mở với cờ đó và CLI không cài gì vào hồ sơ của họ. Cửa sổ Aivin mở bởi bản CLI cũ
15
+ * (không có cờ) → bỏ qua, không lỗi; đóng mở lại cửa sổ là có. Máy chủ không đụng được tiện ích: cdpPolicy.mjs chặn `Extensions.*` và mọi lệnh vào
16
+ * phiên của đích `chrome-extension://`.
17
+ */
18
+
19
+ export const TAB_GROUPS_SW_FILE = 'aivin-tab-groups.js';
20
+ export const TAB_GROUPS_EXTENSION_DIR = path.join(os.homedir(), '.aivin', 'browser-extension', 'tab-groups');
21
+ /** Màu của Chrome cho nhóm tab — xoay vòng để các nhiệm vụ chạy song song phân biệt được. */
22
+ export const GROUP_COLORS = ['blue', 'purple', 'cyan', 'green', 'orange', 'pink', 'yellow', 'red'];
23
+ const CALL_TIMEOUT_MS = 5000;
24
+
25
+ const MANIFEST = {
26
+ manifest_version: 3,
27
+ name: 'Aivin tab groups',
28
+ version: '1.0.0',
29
+ description: 'Groups the tabs Aivin\'s AI Browser is working in. Loaded by the aivin CLI.',
30
+ permissions: ['tabGroups', 'debugger'],
31
+ background: { service_worker: TAB_GROUPS_SW_FILE },
32
+ };
33
+
34
+ // Nhúng dạng chuỗi (không phải tệp trong gói): bản chạy một tệp (bun build) không mang theo thư mục tài nguyên.
35
+ const SW_SOURCE = `// Aivin tab groups - written by the aivin CLI, which calls aivinGroup() over CDP.
36
+ // Keep the worker alive: Chrome stops an idle service worker after 30 s, any extension API call resets that timer.
37
+ setInterval(() => chrome.runtime.getPlatformInfo(), 20000);
38
+
39
+ /** Groups the tabs behind CDP target ids into groupId (if it still exists) or a new group. Returns the group id, or null. */
40
+ self.aivinGroup = async ({ targetIds, groupId, title, color }) => {
41
+ let tabIds = [];
42
+ // The tab may not be listed yet right after Target.createTarget returns.
43
+ for (let i = 0; i < 20; i++) {
44
+ const targets = await chrome.debugger.getTargets();
45
+ tabIds = targets.filter((t) => targetIds.includes(t.id) && t.tabId !== undefined).map((t) => t.tabId);
46
+ if (tabIds.length === targetIds.length) break;
47
+ await new Promise((r) => setTimeout(r, 100));
48
+ }
49
+ if (!tabIds.length) return null;
50
+ if (groupId !== null && groupId !== undefined) {
51
+ try {
52
+ await chrome.tabGroups.get(groupId);
53
+ return await chrome.tabs.group({ groupId, tabIds });
54
+ } catch {
55
+ // the user closed / ungrouped it - start a new group below
56
+ }
57
+ }
58
+ const created = await chrome.tabs.group({ tabIds });
59
+ await chrome.tabGroups.update(created, { title, color, collapsed: false });
60
+ return created;
61
+ };
62
+ `;
63
+
64
+ /** Ghi (hoặc cập nhật) tệp tiện ích vào `dir`, trả `dir`. Không đổi thì không ghi lại. */
65
+ export function ensureTabGroupsExtension(dir = TAB_GROUPS_EXTENSION_DIR) {
66
+ fs.mkdirSync(dir, { recursive: true });
67
+ const files = { 'manifest.json': `${JSON.stringify(MANIFEST, null, 2)}\n`, [TAB_GROUPS_SW_FILE]: SW_SOURCE };
68
+ for (const [name, content] of Object.entries(files)) {
69
+ const full = path.join(dir, name);
70
+ let current = null;
71
+ try { current = fs.readFileSync(full, 'utf8'); } catch { /* chưa có */ }
72
+ if (current !== content) fs.writeFileSync(full, content);
73
+ }
74
+ return dir;
75
+ }
76
+
77
+ /** Tên nhóm: gọn một dòng, tối đa `max` ký tự. */
78
+ export function groupTitle(label, max = 28) {
79
+ const s = String(label || '').replace(/\s+/g, ' ').trim();
80
+ if (!s) return 'Aivin';
81
+ return s.length > max ? `${s.slice(0, max - 1).trimEnd()}…` : s;
82
+ }
83
+
84
+ /**
85
+ * Bộ gom nhóm cho MỘT trình duyệt (`wsUrl` cấp trình duyệt của cửa sổ Aivin). `add(targetId, { key, title })` đưa tab vào nhóm của `key` (đường hầm);
86
+ * không bao giờ ném lỗi — gom nhóm chỉ là tiện ích hiển thị. Nạp tiện ích không được → tắt hẳn cho trình duyệt này, gọi `onUnavailable` một lần.
87
+ */
88
+ export function createTabGrouper({ wsUrl, extensionDir, WebSocketImpl = WSClient, onUnavailable = () => {} }) {
89
+ let ws = null;
90
+ let connecting = null;
91
+ let worker = null; // sessionId của phiên gắn vào service worker
92
+ let disabled = false;
93
+ let closed = false;
94
+ let nextId = 1;
95
+ let colorIndex = 0;
96
+ const pending = new Map();
97
+ const groups = new Map(); // key → { groupId, color }
98
+ const queues = new Map(); // key → Promise — các tab của cùng một nhóm gom lần lượt (không tạo hai nhóm)
99
+
100
+ const call = (method, params = {}, sessionId) => new Promise((resolve, reject) => {
101
+ if (!ws || ws.readyState !== WebSocketImpl.OPEN) { reject(new Error('Browser connection closed')); return; }
102
+ const id = nextId++;
103
+ const timer = setTimeout(() => { pending.delete(id); reject(new Error(`${method} timed out`)); }, CALL_TIMEOUT_MS);
104
+ pending.set(id, { resolve, reject, timer });
105
+ ws.send(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }));
106
+ });
107
+
108
+ const connect = () => {
109
+ if (ws && ws.readyState === WebSocketImpl.OPEN) return Promise.resolve();
110
+ if (connecting) return connecting;
111
+ connecting = new Promise((resolve, reject) => {
112
+ const sock = new WebSocketImpl(wsUrl, { perMessageDeflate: false });
113
+ sock.once('open', () => { ws = sock; connecting = null; resolve(); });
114
+ sock.once('error', (e) => { connecting = null; reject(e); });
115
+ sock.on('message', (data) => {
116
+ let msg;
117
+ try { msg = JSON.parse(String(data)); } catch { return; }
118
+ const p = msg.id !== undefined ? pending.get(msg.id) : null;
119
+ if (!p) return;
120
+ pending.delete(msg.id);
121
+ clearTimeout(p.timer);
122
+ if (msg.error) p.reject(new Error(msg.error.message || 'CDP error'));
123
+ else p.resolve(msg.result || {});
124
+ });
125
+ sock.on('close', () => {
126
+ if (ws === sock) { ws = null; worker = null; }
127
+ for (const p of pending.values()) { clearTimeout(p.timer); p.reject(new Error('Browser connection closed')); }
128
+ pending.clear();
129
+ });
130
+ });
131
+ return connecting;
132
+ };
133
+
134
+ const findWorker = async () => {
135
+ const { targetInfos = [] } = await call('Target.getTargets');
136
+ return targetInfos.find((t) => t.type === 'service_worker' && /^(chrome|edge)-extension:\/\//.test(t.url || '') && t.url.endsWith(`/${TAB_GROUPS_SW_FILE}`));
137
+ };
138
+
139
+ /** Gắn vào service worker của tiện ích; chưa nạp (hoặc `reload` — bản cũ thiếu hàm) thì nạp. Không được → ném lỗi. */
140
+ const attachWorker = async ({ reload = false } = {}) => {
141
+ await connect();
142
+ let sw = reload ? null : await findWorker();
143
+ if (!sw) {
144
+ await call('Extensions.loadUnpacked', { path: extensionDir || ensureTabGroupsExtension() });
145
+ for (let i = 0; i < 30 && !sw; i++) {
146
+ await new Promise((r) => setTimeout(r, 100));
147
+ sw = await findWorker();
148
+ }
149
+ }
150
+ if (!sw) throw new Error('The tab groups extension did not start');
151
+ const { sessionId } = await call('Target.attachToTarget', { targetId: sw.targetId, flatten: true });
152
+ await call('Runtime.runIfWaitingForDebugger', {}, sessionId).catch(() => undefined);
153
+ worker = sessionId;
154
+ };
155
+
156
+ const groupNow = async (targetId, key, title) => {
157
+ let entry = groups.get(key);
158
+ if (!entry) {
159
+ entry = { groupId: null, color: GROUP_COLORS[colorIndex++ % GROUP_COLORS.length] };
160
+ groups.set(key, entry);
161
+ }
162
+ for (let attempt = 0; attempt < 2; attempt++) {
163
+ if (!worker) {
164
+ try {
165
+ await attachWorker({ reload: attempt > 0 });
166
+ } catch (e) {
167
+ disabled = true;
168
+ onUnavailable(e);
169
+ return;
170
+ }
171
+ }
172
+ let res;
173
+ try {
174
+ const args = { targetIds: [targetId], groupId: entry.groupId, title, color: entry.color };
175
+ res = await call('Runtime.evaluate', { expression: `self.aivinGroup(${JSON.stringify(args)})`, awaitPromise: true, returnByValue: true }, worker);
176
+ } catch {
177
+ worker = null; // service worker đã dừng / phiên rớt — gắn lại một lần
178
+ continue;
179
+ }
180
+ if (res.exceptionDetails) {
181
+ // Bản tiện ích cũ hơn (không có aivinGroup) → nạp lại; lỗi khác (tab vừa đóng…) thì thôi.
182
+ if (/aivinGroup/.test(JSON.stringify(res.exceptionDetails))) { worker = null; continue; }
183
+ return;
184
+ }
185
+ if (typeof res.result?.value === 'number') entry.groupId = res.result.value;
186
+ return;
187
+ }
188
+ };
189
+
190
+ return {
191
+ add(targetId, { key = 'aivin', title = 'Aivin' } = {}) {
192
+ if (disabled || closed || !targetId) return Promise.resolve();
193
+ const prev = queues.get(key) || Promise.resolve();
194
+ const next = prev.then(() => (disabled || closed ? undefined : groupNow(targetId, key, title))).catch(() => undefined);
195
+ queues.set(key, next);
196
+ return next;
197
+ },
198
+ /** Đường hầm đóng: quên nhóm của nó (nhóm trong trình duyệt vẫn còn tới khi người dùng đóng tab). */
199
+ forget(key) {
200
+ groups.delete(key);
201
+ queues.delete(key);
202
+ },
203
+ close() {
204
+ closed = true;
205
+ try { ws?.close(); } catch { /* đã đóng */ }
206
+ },
207
+ isDisabled: () => disabled,
208
+ };
209
+ }
@@ -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
+ }