@aivin-labs/cli 1.0.8 → 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 (51) hide show
  1. package/README.md +25 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1912 -1780
  4. package/bin/lib/browserAutomation.mjs +232 -469
  5. package/bin/lib/localBrowser.mjs +345 -0
  6. package/bin/lib/remote/activityLog.mjs +1 -1
  7. package/bin/lib/remote/autoStart.mjs +174 -14
  8. package/bin/lib/remote/browserTunnel.mjs +142 -31
  9. package/bin/lib/remote/callLedger.mjs +1 -1
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +87 -5
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/codingAgents.mjs +293 -0
  14. package/bin/lib/remote/constants.mjs +61 -0
  15. package/bin/lib/remote/dailyBrowser.mjs +1 -1
  16. package/bin/lib/remote/desktop/index.mjs +272 -0
  17. package/bin/lib/remote/desktop/linux.mjs +144 -0
  18. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  19. package/bin/lib/remote/desktop/mac.mjs +187 -0
  20. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  21. package/bin/lib/remote/desktop/strings.mjs +74 -0
  22. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  23. package/bin/lib/remote/docText.mjs +1 -1
  24. package/bin/lib/remote/fileIndexer.mjs +1 -1
  25. package/bin/lib/remote/gui/index.mjs +93 -12
  26. package/bin/lib/remote/gui/windowsHostSource.mjs +280 -28
  27. package/bin/lib/remote/idempotency.mjs +1 -1
  28. package/bin/lib/remote/localPolicy.mjs +9 -2
  29. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  30. package/bin/lib/remote/mascot/ask.mjs +768 -0
  31. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  32. package/bin/lib/remote/mascot/assets.mjs +825 -216
  33. package/bin/lib/remote/mascot/bot.mjs +372 -0
  34. package/bin/lib/remote/mascot/hostSource.mjs +498 -101
  35. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  36. package/bin/lib/remote/mascot/index.mjs +199 -28
  37. package/bin/lib/remote/mascot/labels.mjs +2 -3
  38. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  39. package/bin/lib/remote/mascot/strings.mjs +204 -18
  40. package/bin/lib/remote/mascot/ui.mjs +104 -0
  41. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  42. package/bin/lib/remote/meeting/index.mjs +415 -0
  43. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  44. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  45. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  46. package/bin/lib/remote/tabGroups.mjs +209 -0
  47. package/bin/lib/remote/toolHandlers.mjs +15 -0
  48. package/docs/AIVIN_MASCOT.md +116 -0
  49. package/docs/CLI.md +142 -11
  50. package/docs/media/aivin-mascot-states.mp4 +0 -0
  51. package/package.json +1 -1
@@ -0,0 +1,272 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { createHash } from 'crypto';
5
+ import { execFileSync, spawn } from 'child_process';
6
+ import { REMOTE_CONFIG_DIR } from '../constants.mjs';
7
+ import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
8
+ import { TRAY_CS } from './traySource.mjs';
9
+ import { trayStrings } from './strings.mjs';
10
+
11
+ /**
12
+ * Aivin trên màn hình Windows (29/10/2026): `Aivin.exe` (khay hệ thống + trình giữ chạy daemon, traySource.mjs) biên dịch trên máy, lối tắt
13
+ * Start menu (tìm "Aivin" là thấy), mục khởi động cùng Windows ở khoá HKCU Run — Task Manager → Startup apps liệt kê và bật / tắt được
14
+ * (Task Manager ghi vào StartupApproved\Run, Aivin.exe và `aivin remote enable|disable` đọc / ghi cùng chỗ đó). Tác vụ Task Scheduler cũ
15
+ * không hiện trong Task Manager, nên Windows chuyển sang cách này; không biên dịch được (máy chặn csc) thì autoStart.mjs lùi về tác vụ.
16
+ */
17
+
18
+ export const DESKTOP_DIR = path.join(REMOTE_CONFIG_DIR, 'desktop');
19
+ export const LAUNCH_CONFIG_FILE = path.join(DESKTOP_DIR, 'launch.cfg');
20
+ const LOGO_FILE = path.join(DESKTOP_DIR, 'logo.png');
21
+ const SOURCE_HASH_FILE = path.join(DESKTOP_DIR, 'launcher.sha');
22
+ const LAUNCHER_VERSION = '1.0.0.0';
23
+
24
+ export const RUN_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Run';
25
+ export const STARTUP_APPROVED_KEY = 'HKCU\\Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\StartupApproved\\Run';
26
+ export const STARTUP_VALUE = 'Aivin';
27
+
28
+ /** %LOCALAPPDATA%\Aivin\Aivin.exe — không đặt trong bin\ (cạnh aivin.exe): Windows không phân biệt hoa thường, hai tệp sẽ trùng tên. */
29
+ export function launcherExePath(env = process.env) {
30
+ return path.join(env.LOCALAPPDATA || path.join(os.homedir(), 'AppData', 'Local'), 'Aivin', 'Aivin.exe');
31
+ }
32
+
33
+ /** Tên hiện ở Start menu / Task Manager → Startup apps (mô tả của Aivin.exe) / khay: "AIVIN Bot CLI" (30/10/2026; trước là "Aivin"). */
34
+ export const DISPLAY_NAME = 'AIVIN Bot CLI';
35
+ const startMenuDir = (env) => path.join(env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs');
36
+
37
+ export function startMenuShortcutPath(env = process.env) {
38
+ return path.join(startMenuDir(env), `${DISPLAY_NAME}.lnk`);
39
+ }
40
+
41
+ /** Lối tắt tên cũ ("Aivin.lnk") — dọn khi cài / gỡ để Start menu không có hai mục. */
42
+ export function legacyStartMenuShortcutPath(env = process.env) {
43
+ return path.join(startMenuDir(env), 'Aivin.lnk');
44
+ }
45
+
46
+ /** Mã C# của Aivin.exe cho thư mục cấu hình này (gắn cứng: lối tắt / khoá Run không mang biến môi trường AIVIN_REMOTE_HOME theo). */
47
+ export function launcherSource(home = REMOTE_CONFIG_DIR) {
48
+ const literal = `@"${String(home).replace(/"/g, '""')}"`;
49
+ return TRAY_CS.replace('@@HOME@@', literal).replaceAll('@@VERSION@@', LAUNCHER_VERSION);
50
+ }
51
+
52
+ /** Tệp .ico chứa nguyên ảnh PNG (Windows Vista+, csc /win32icon nhận được). */
53
+ export function pngToIco(png) {
54
+ const width = png.readUInt32BE(16);
55
+ const height = png.readUInt32BE(20);
56
+ const header = Buffer.alloc(22);
57
+ header.writeUInt16LE(0, 0);
58
+ header.writeUInt16LE(1, 2);
59
+ header.writeUInt16LE(1, 4);
60
+ header[6] = width >= 256 ? 0 : width;
61
+ header[7] = height >= 256 ? 0 : height;
62
+ header.writeUInt16LE(1, 10);
63
+ header.writeUInt16LE(32, 12);
64
+ header.writeUInt32LE(png.length, 14);
65
+ header.writeUInt32LE(22, 18);
66
+ return Buffer.concat([header, png]);
67
+ }
68
+
69
+ /**
70
+ * launch.cfg: `exe=` tệp chạy, mỗi `arg=` một đối số, `pending=` / `rollback=` để tự lùi bản (Windows; macOS / Linux tự lùi trong
71
+ * aivin-remote-run.sh), `extra` = khoá riêng của từng hệ điều hành (chỗ đặt mục tự khởi động…), `s.<khoá>=` chữ trên menu.
72
+ */
73
+ export function launchConfigText({ argv, rollback = null, lang = 'en', extra = {}, platform = 'win32' }) {
74
+ const clean = (v) => String(v).replace(/[\r\n]+/g, ' ');
75
+ const lines = [`exe=${clean(argv[0])}`, ...argv.slice(1).map((a) => `arg=${clean(a)}`)];
76
+ if (rollback) lines.push(`pending=${clean(rollback.pendingFile)}`, `rollback=${clean(rollback.rollbackFile)}`);
77
+ for (const [key, value] of Object.entries(extra)) lines.push(`${key}=${clean(value)}`);
78
+ for (const [key, value] of Object.entries(trayStrings(lang, platform))) lines.push(`s.${key}=${clean(value)}`);
79
+ return lines.join('\r\n') + '\r\n';
80
+ }
81
+
82
+ /** Đối số daemon đã lưu (sau `remote start`) — cài lại giữ `--dir` / `--proxy` của lần `aivin remote enable` trước. */
83
+ export function savedDaemonArgs(text) {
84
+ const args = String(text || '').split(/\r?\n/).filter((l) => l.startsWith('arg=')).map((l) => l.slice(4));
85
+ const at = args.indexOf('start');
86
+ return at > 0 && args[at - 1] === 'remote' ? args.slice(at + 1) : null;
87
+ }
88
+
89
+ export function readSavedDaemonArgs(file = LAUNCH_CONFIG_FILE) {
90
+ try { return savedDaemonArgs(fs.readFileSync(file, 'utf8')); } catch { return null; }
91
+ }
92
+
93
+ // --- Registry: khoá Run + StartupApproved (Task Manager) ---------------------------------------------------------------------------
94
+
95
+ /** StartupApproved: byte đầu chẵn (02) = bật, lẻ (03) = Task Manager / người dùng đã tắt, kèm thời điểm tắt (FILETIME). */
96
+ export function startupApprovedHex(enabled, now = Date.now()) {
97
+ const data = Buffer.alloc(12);
98
+ data[0] = enabled ? 2 : 3;
99
+ if (!enabled) data.writeBigUInt64LE((BigInt(now) + 11_644_473_600_000n) * 10_000n, 4);
100
+ return data.toString('hex');
101
+ }
102
+
103
+ export function isStartupApproved(hex) {
104
+ const first = parseInt(String(hex || '').slice(0, 2), 16);
105
+ return Number.isNaN(first) || (first & 1) === 0;
106
+ }
107
+
108
+ const reg = (args) => execFileSync('reg', args, { encoding: 'utf8', timeout: 15_000, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
109
+
110
+ /** Dữ liệu một giá trị từ `reg query` (null nếu không có). */
111
+ export function parseRegQuery(out, name) {
112
+ const line = String(out).split(/\r?\n/).find((l) => l.trim().startsWith(`${name} `) || l.trim().startsWith(`${name}\t`));
113
+ const m = line?.trim().match(/^\S+\s+(REG_\w+)\s*(.*)$/);
114
+ return m ? { type: m[1], data: m[2].trim() } : null;
115
+ }
116
+
117
+ function regValue(key, name) {
118
+ try { return parseRegQuery(reg(['query', key, '/v', name]), name); } catch { return null; }
119
+ }
120
+
121
+ /** registered = có mục ở khoá Run; enabled = có và không bị tắt ở Task Manager. */
122
+ export function startupState() {
123
+ const run = regValue(RUN_KEY, STARTUP_VALUE);
124
+ if (!run) return { registered: false, enabled: false };
125
+ return { registered: true, enabled: isStartupApproved(regValue(STARTUP_APPROVED_KEY, STARTUP_VALUE)?.data) };
126
+ }
127
+
128
+ export function setStartupApproved(enabled) {
129
+ reg(['add', STARTUP_APPROVED_KEY, '/v', STARTUP_VALUE, '/t', 'REG_BINARY', '/d', startupApprovedHex(enabled), '/f']);
130
+ }
131
+
132
+ export function registerStartup(exe = launcherExePath()) {
133
+ reg(['add', RUN_KEY, '/v', STARTUP_VALUE, '/t', 'REG_SZ', '/d', `"${exe}" --autostart`, '/f']);
134
+ setStartupApproved(true);
135
+ }
136
+
137
+ export function unregisterStartup() {
138
+ for (const key of [RUN_KEY, STARTUP_APPROVED_KEY]) {
139
+ try { reg(['delete', key, '/v', STARTUP_VALUE, '/f']); } catch { /* chưa có */ }
140
+ }
141
+ }
142
+
143
+ // --- Biên dịch Aivin.exe + lối tắt Start menu ------------------------------------------------------------------------------------
144
+
145
+ const SETUP_PS1 = `param([string]$Src, [string]$Ico, [string]$Out, [string]$Lnk, [string]$Target, [string]$Desc)
146
+ $ErrorActionPreference = 'Stop'
147
+ if ($Src) {
148
+ $p = New-Object System.CodeDom.Compiler.CompilerParameters
149
+ $p.GenerateExecutable = $true
150
+ $p.OutputAssembly = $Out
151
+ $p.CompilerOptions = '/target:winexe /optimize+ /win32icon:"' + $Ico + '"'
152
+ [void]$p.ReferencedAssemblies.AddRange([string[]]@('System.dll', 'System.Drawing.dll', 'System.Windows.Forms.dll'))
153
+ $r = (New-Object Microsoft.CSharp.CSharpCodeProvider).CompileAssemblyFromSource($p, [IO.File]::ReadAllText($Src, [Text.Encoding]::UTF8))
154
+ if ($r.Errors.HasErrors) { $r.Errors | Where-Object { -not $_.IsWarning } | ForEach-Object { [Console]::Error.WriteLine($_.ToString()) }; exit 1 }
155
+ }
156
+ if ($Lnk) {
157
+ New-Item -ItemType Directory -Force -Path (Split-Path $Lnk) | Out-Null
158
+ $s = (New-Object -ComObject WScript.Shell).CreateShortcut($Lnk)
159
+ $s.TargetPath = $Target
160
+ $s.IconLocation = "$Target,0"
161
+ $s.WorkingDirectory = Split-Path $Target
162
+ $s.Description = $Desc
163
+ $s.Save()
164
+ }
165
+ `;
166
+
167
+ function runSetup(params, dir) {
168
+ const script = path.join(dir, 'setup.ps1');
169
+ fs.writeFileSync(script, SETUP_PS1);
170
+ const args = ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', script];
171
+ for (const [k, v] of Object.entries(params)) if (v) args.push(`-${k}`, v);
172
+ try {
173
+ execFileSync('powershell.exe', args, { encoding: 'utf8', timeout: 120_000, windowsHide: true, stdio: ['ignore', 'pipe', 'pipe'] });
174
+ } catch (e) {
175
+ throw new Error(String(e?.stderr || e?.message || e).trim().split(/\r?\n/).slice(-3).join(' '), { cause: e });
176
+ }
177
+ }
178
+
179
+ /** Dọn bản Aivin.exe cũ đã đổi tên (lúc đó còn đang chạy). */
180
+ function cleanupOldLaunchers(exe) {
181
+ const dir = path.dirname(exe);
182
+ let names;
183
+ try { names = fs.readdirSync(dir); } catch { return; }
184
+ for (const name of names) {
185
+ if (/^Aivin\.exe\.old-\d+$/i.test(name)) try { fs.rmSync(path.join(dir, name), { force: true }); } catch { /* vẫn đang chạy */ }
186
+ }
187
+ }
188
+
189
+ /**
190
+ * Biên dịch Aivin.exe khi chưa có / mã đổi. Bản cũ đang chạy (khoá tệp) thì đổi tên sang `.old-*` (Windows cho đổi tên tệp đang chạy) —
191
+ * khay đang mở vẫn chạy bản cũ tới lần mở sau.
192
+ */
193
+ export function ensureLauncher({ exe = launcherExePath(), home = REMOTE_CONFIG_DIR, dir = DESKTOP_DIR, force = false } = {}) {
194
+ const source = launcherSource(home);
195
+ const png = Buffer.from(AIVIN_LOGO_PNG_BASE64, 'base64');
196
+ const hash = createHash('sha256').update(source).update(png).digest('hex');
197
+ fs.mkdirSync(dir, { recursive: true });
198
+ const hashFile = path.join(dir, path.basename(SOURCE_HASH_FILE));
199
+ let current = null;
200
+ try { current = fs.readFileSync(hashFile, 'utf8').trim(); } catch { /* chưa biên dịch */ }
201
+ if (!force && current === hash && fs.existsSync(exe)) return { exe, built: false };
202
+
203
+ fs.mkdirSync(path.dirname(exe), { recursive: true });
204
+ cleanupOldLaunchers(exe);
205
+ const src = path.join(dir, 'tray.cs');
206
+ const ico = path.join(dir, 'aivin.ico');
207
+ fs.writeFileSync(src, source);
208
+ fs.writeFileSync(ico, pngToIco(png));
209
+ const out = `${exe}.new`;
210
+ fs.rmSync(out, { force: true });
211
+ runSetup({ Src: src, Ico: ico, Out: out }, dir);
212
+ if (fs.existsSync(exe)) {
213
+ try { fs.rmSync(exe, { force: true }); } catch { fs.renameSync(exe, `${exe}.old-${Date.now()}`); }
214
+ }
215
+ fs.renameSync(out, exe);
216
+ fs.writeFileSync(hashFile, hash);
217
+ return { exe, built: true };
218
+ }
219
+
220
+ export function ensureStartMenuShortcut({ exe = launcherExePath(), lnk = startMenuShortcutPath(), lang = 'en', dir = DESKTOP_DIR } = {}) {
221
+ runSetup({ Lnk: lnk, Target: exe, Desc: trayStrings(lang).shortcut }, dir);
222
+ return lnk;
223
+ }
224
+
225
+ export function isDesktopInstalled() {
226
+ return fs.existsSync(launcherExePath()) && fs.existsSync(LAUNCH_CONFIG_FILE);
227
+ }
228
+
229
+ /**
230
+ * Cách mở khay: OPEN = như bấm Start menu (mở Aivin; khay đang chạy thì nó mở); AUTOSTART = im lặng (khởi động cùng Windows);
231
+ * INSTALLED = vừa cài: chỉ hiện bong bóng gợi ý, không bật hộp nhập mã.
232
+ */
233
+ export const TrayLaunch = Object.freeze({ OPEN: 'open', AUTOSTART: 'autostart', INSTALLED: 'installed' });
234
+
235
+ export function launchTray({ exe = launcherExePath(), mode = TrayLaunch.OPEN } = {}) {
236
+ const args = mode === TrayLaunch.OPEN ? [] : [`--${mode}`];
237
+ spawn(exe, args, { detached: true, stdio: 'ignore', windowsHide: true }).unref();
238
+ }
239
+
240
+ /**
241
+ * Cài trọn: launch.cfg (lệnh daemon + chữ menu), logo, Aivin.exe, lối tắt Start menu; `autostart` → mục khởi động cùng Windows (bật);
242
+ * `launch` → mở khay ngay theo `launchMode` (TrayLaunch).
243
+ */
244
+ export function installDesktop({ argv, rollback = null, lang = 'en', autostart = true, launch = true, launchMode = TrayLaunch.INSTALLED }) {
245
+ fs.mkdirSync(DESKTOP_DIR, { recursive: true });
246
+ fs.writeFileSync(LAUNCH_CONFIG_FILE, launchConfigText({ argv, rollback, lang }));
247
+ fs.writeFileSync(LOGO_FILE, Buffer.from(AIVIN_LOGO_PNG_BASE64, 'base64'));
248
+ const { exe, built } = ensureLauncher();
249
+ const lnk = startMenuShortcutPath();
250
+ fs.rmSync(legacyStartMenuShortcutPath(), { force: true });
251
+ if (built || !fs.existsSync(lnk)) ensureStartMenuShortcut({ exe, lnk, lang });
252
+ if (autostart) registerStartup(exe);
253
+ if (launch) launchTray({ exe, mode: launchMode });
254
+ return { exe, shortcut: lnk, built, autostart: startupState().enabled };
255
+ }
256
+
257
+ /** Gỡ: đóng khay (dừng daemon nó đang giữ), xoá mục khởi động, lối tắt, Aivin.exe, desktop\. */
258
+ export function uninstallDesktop({ wait = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) } = {}) {
259
+ const exe = launcherExePath();
260
+ if (fs.existsSync(exe)) {
261
+ try { execFileSync(exe, ['--quit'], { stdio: 'ignore', windowsHide: true, timeout: 10_000 }); } catch { /* không chạy */ }
262
+ }
263
+ unregisterStartup();
264
+ fs.rmSync(startMenuShortcutPath(), { force: true });
265
+ fs.rmSync(legacyStartMenuShortcutPath(), { force: true });
266
+ for (let i = 0; i < 20 && fs.existsSync(exe); i++) {
267
+ try { fs.rmSync(exe, { force: true }); } catch { wait(250); }
268
+ }
269
+ cleanupOldLaunchers(exe);
270
+ fs.rmSync(DESKTOP_DIR, { recursive: true, force: true });
271
+ return { removed: !fs.existsSync(exe) };
272
+ }
@@ -0,0 +1,144 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import { posix as path } from 'path';
4
+ import { execFileSync, spawn } from 'child_process';
5
+ import { REMOTE_CONFIG_DIR } from '../constants.mjs';
6
+ import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
7
+ import { DESKTOP_DIR, LAUNCH_CONFIG_FILE, TrayLaunch, launchConfigText } from './index.mjs';
8
+ import { LINUX_LAUNCHER_SH, LINUX_TRAY_PY } from './linuxTraySource.mjs';
9
+ import { trayStrings } from './strings.mjs';
10
+
11
+ /**
12
+ * Aivin trên màn hình Linux (29/10/2026): mục "Aivin" trong menu ứng dụng (~/.local/share/applications — GNOME Activities, KDE, XFCE…
13
+ * tìm được), tự khởi động bằng ~/.config/autostart/aivin.desktop — "Startup Applications" (GNOME), Autostart (KDE)… liệt kê và bật / tắt
14
+ * được; một cơ chế duy nhất (bản cũ ghi aivin-remote.desktop chạy thẳng daemon, gỡ khi cài). Khay: linuxTraySource.mjs.
15
+ */
16
+
17
+ const dataHome = (env = process.env) => env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share');
18
+ const configHome = (env = process.env) => env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
19
+ export const linuxAppEntryPath = (env) => path.join(dataHome(env), 'applications', 'aivin.desktop');
20
+ export const linuxAutostartPath = (env) => path.join(configHome(env), 'autostart', 'aivin.desktop');
21
+ const LEGACY_AUTOSTART = (env) => path.join(configHome(env), 'autostart', 'aivin-remote.desktop');
22
+ export const LINUX_LAUNCHER_FILE = path.join(DESKTOP_DIR, 'aivin-desktop.sh');
23
+ const TRAY_FILE = path.join(DESKTOP_DIR, 'tray.py');
24
+ const LOGO_FILE = path.join(DESKTOP_DIR, 'logo.png');
25
+ /** Bản sao mục autostart: menu khay bật lại = chép lại (GNOME Tweaks xoá hẳn tệp khi tắt). */
26
+ const AUTOSTART_COPY_FILE = path.join(DESKTOP_DIR, 'autostart.desktop');
27
+
28
+ const shq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
29
+
30
+ /** Một đối số của dòng Exec= (Desktop Entry spec): bọc nháy kép, thoát " ` $ \ — rồi thoát \ lần nữa vì giá trị chuỗi cũng thoát \. */
31
+ export function desktopExecArg(s) {
32
+ const quoted = `"${String(s).replace(/(["`$\\])/g, '\\$1')}"`;
33
+ return quoted.replace(/\\/g, '\\\\');
34
+ }
35
+
36
+ /** Có phiên màn hình (X11 / Wayland) — không có (máy chủ, SSH) thì tự khởi động bằng systemd như trước. */
37
+ export function hasLinuxDesktopSession(env = process.env) {
38
+ return Boolean(env.DISPLAY || env.WAYLAND_DISPLAY || env.XDG_CURRENT_DESKTOP);
39
+ }
40
+
41
+ export function linuxDesktopEntry({ launcher = LINUX_LAUNCHER_FILE, icon = LOGO_FILE, lang = 'en', autostart = false } = {}) {
42
+ const s = trayStrings(lang, 'linux');
43
+ return [
44
+ '[Desktop Entry]',
45
+ 'Type=Application',
46
+ 'Version=1.0',
47
+ 'Name=AIVIN Bot CLI',
48
+ `Comment=${s.shortcut}`,
49
+ `Exec=${desktopExecArg(launcher)}${autostart ? ' --autostart' : ''}`,
50
+ `Icon=${icon}`,
51
+ 'Terminal=false',
52
+ 'Categories=Utility;Network;',
53
+ 'Keywords=aivin;ai;agent;assistant;',
54
+ 'StartupNotify=false',
55
+ ...(autostart ? ['X-GNOME-Autostart-enabled=true', 'Hidden=false'] : []),
56
+ ].join('\n') + '\n';
57
+ }
58
+
59
+ export function linuxLauncherScript({ runScript, home = REMOTE_CONFIG_DIR } = {}) {
60
+ return LINUX_LAUNCHER_SH
61
+ .replace('@@LOG@@', shq(path.join(home, 'remote-service.log')))
62
+ .replace('@@TRAY@@', shq(path.join(home, 'desktop', 'tray.py')))
63
+ .replace('@@CREDS@@', shq(path.join(home, 'device-credentials.json')))
64
+ .replace('@@RUN@@', shq(runScript));
65
+ }
66
+
67
+ export function linuxTraySource(home = REMOTE_CONFIG_DIR) {
68
+ return LINUX_TRAY_PY.replace('@@HOME@@', JSON.stringify(home));
69
+ }
70
+
71
+ /** Tắt = Hidden=true / X-GNOME-Autostart-enabled=false (như các trình quản lý khởi động ghi), hoặc đã bị xoá. */
72
+ export function isAutostartEnabled(text) {
73
+ if (text == null) return false;
74
+ return !/^Hidden\s*=\s*true\s*$/m.test(text) && !/^X-GNOME-Autostart-enabled\s*=\s*false\s*$/m.test(text);
75
+ }
76
+
77
+ export function linuxStartupState() {
78
+ let text = null;
79
+ try { text = fs.readFileSync(linuxAutostartPath(), 'utf8'); } catch { /* chưa có / đã bị xoá */ }
80
+ return { registered: text != null, enabled: isAutostartEnabled(text) };
81
+ }
82
+
83
+ export function setLinuxStartup(enabled) {
84
+ const file = linuxAutostartPath();
85
+ if (enabled) {
86
+ fs.mkdirSync(path.dirname(file), { recursive: true });
87
+ fs.copyFileSync(AUTOSTART_COPY_FILE, file);
88
+ return;
89
+ }
90
+ let text;
91
+ try { text = fs.readFileSync(file, 'utf8'); } catch { return; }
92
+ fs.writeFileSync(file, text.replace(/^X-GNOME-Autostart-enabled=.*$/m, 'X-GNOME-Autostart-enabled=false').replace(/^Hidden=.*$/m, 'Hidden=true'));
93
+ }
94
+
95
+ /** python3 + PyGObject + AppIndicator có trên máy không (chỉ để báo ở `aivin desktop`). */
96
+ export function linuxTrayAvailable() {
97
+ const probe = "import gi\ntry:\n gi.require_version('AyatanaAppIndicator3','0.1')\nexcept ValueError:\n gi.require_version('AppIndicator3','0.1')";
98
+ try {
99
+ execFileSync('python3', ['-c', probe], { stdio: 'ignore', timeout: 15_000 });
100
+ return true;
101
+ } catch {
102
+ return false;
103
+ }
104
+ }
105
+
106
+ export function launchLinuxTray({ mode = TrayLaunch.OPEN } = {}) {
107
+ const args = mode === TrayLaunch.OPEN ? [] : [`--${mode}`];
108
+ spawn('/bin/sh', [LINUX_LAUNCHER_FILE, ...args], { detached: true, stdio: 'ignore' }).unref();
109
+ }
110
+
111
+ export function installLinuxDesktop({ runScript, lang = 'en', autostart = true, launch = true, launchMode = TrayLaunch.INSTALLED }) {
112
+ fs.mkdirSync(DESKTOP_DIR, { recursive: true });
113
+ const autostartFile = linuxAutostartPath();
114
+ fs.writeFileSync(LAUNCH_CONFIG_FILE, launchConfigText({
115
+ argv: ['/bin/sh', runScript], lang, platform: 'linux', extra: { autostart: autostartFile, autostart_copy: AUTOSTART_COPY_FILE },
116
+ }));
117
+ fs.writeFileSync(LOGO_FILE, Buffer.from(AIVIN_LOGO_PNG_BASE64, 'base64'));
118
+ fs.writeFileSync(TRAY_FILE, linuxTraySource());
119
+ fs.writeFileSync(LINUX_LAUNCHER_FILE, linuxLauncherScript({ runScript }), { mode: 0o755 });
120
+ fs.chmodSync(LINUX_LAUNCHER_FILE, 0o755);
121
+ const entry = linuxAppEntryPath();
122
+ fs.mkdirSync(path.dirname(entry), { recursive: true });
123
+ fs.writeFileSync(entry, linuxDesktopEntry({ lang }));
124
+ fs.writeFileSync(AUTOSTART_COPY_FILE, linuxDesktopEntry({ lang, autostart: true }));
125
+ fs.rmSync(LEGACY_AUTOSTART(), { force: true });
126
+ if (autostart) setLinuxStartup(true);
127
+ try { execFileSync('update-desktop-database', [path.dirname(entry)], { stdio: 'ignore', timeout: 15_000 }); } catch { /* không bắt buộc */ }
128
+ if (launch) launchLinuxTray({ mode: launchMode });
129
+ return { exe: LINUX_LAUNCHER_FILE, shortcut: entry, built: true, autostart: linuxStartupState().enabled };
130
+ }
131
+
132
+ export function isLinuxDesktopInstalled() {
133
+ return fs.existsSync(LINUX_LAUNCHER_FILE) && fs.existsSync(LAUNCH_CONFIG_FILE);
134
+ }
135
+
136
+ export function uninstallLinuxDesktop({ wait = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) } = {}) {
137
+ if (fs.existsSync(LINUX_LAUNCHER_FILE)) {
138
+ try { execFileSync('/bin/sh', [LINUX_LAUNCHER_FILE, '--quit'], { stdio: 'ignore', timeout: 15_000 }); } catch { /* không chạy */ }
139
+ wait(3000);
140
+ }
141
+ for (const file of [linuxAutostartPath(), linuxAppEntryPath()]) fs.rmSync(file, { force: true });
142
+ fs.rmSync(DESKTOP_DIR, { recursive: true, force: true });
143
+ return { removed: true };
144
+ }