@aivin-labs/cli 1.0.8 → 1.0.13

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 (63) hide show
  1. package/README.md +41 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1979 -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 +187 -37
  9. package/bin/lib/remote/callLedger.mjs +74 -15
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +174 -11
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/cloudFiles.mjs +53 -0
  14. package/bin/lib/remote/codingAgents.mjs +293 -0
  15. package/bin/lib/remote/constants.mjs +78 -0
  16. package/bin/lib/remote/dailyBrowser.mjs +9 -3
  17. package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
  18. package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
  19. package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
  20. package/bin/lib/remote/desktop/index.mjs +309 -0
  21. package/bin/lib/remote/desktop/linux.mjs +144 -0
  22. package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -0
  23. package/bin/lib/remote/desktop/mac.mjs +187 -0
  24. package/bin/lib/remote/desktop/macTraySource.mjs +295 -0
  25. package/bin/lib/remote/desktop/strings.mjs +74 -0
  26. package/bin/lib/remote/desktop/traySource.mjs +541 -0
  27. package/bin/lib/remote/deviceProfile.mjs +1 -0
  28. package/bin/lib/remote/docText.mjs +86 -1
  29. package/bin/lib/remote/fileIndexer.mjs +757 -399
  30. package/bin/lib/remote/folderRules.mjs +140 -0
  31. package/bin/lib/remote/gui/index.mjs +208 -18
  32. package/bin/lib/remote/gui/windowsHost.mjs +9 -2
  33. package/bin/lib/remote/gui/windowsHostSource.mjs +444 -49
  34. package/bin/lib/remote/idempotency.mjs +50 -21
  35. package/bin/lib/remote/localPolicy.mjs +17 -4
  36. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  37. package/bin/lib/remote/mascot/ask.mjs +768 -0
  38. package/bin/lib/remote/mascot/askHostSource.mjs +530 -0
  39. package/bin/lib/remote/mascot/assets.mjs +825 -216
  40. package/bin/lib/remote/mascot/bot.mjs +397 -0
  41. package/bin/lib/remote/mascot/hostSource.mjs +500 -103
  42. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  43. package/bin/lib/remote/mascot/index.mjs +199 -28
  44. package/bin/lib/remote/mascot/labels.mjs +2 -3
  45. package/bin/lib/remote/mascot/rigSource.mjs +614 -0
  46. package/bin/lib/remote/mascot/strings.mjs +204 -18
  47. package/bin/lib/remote/mascot/ui.mjs +104 -0
  48. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  49. package/bin/lib/remote/meeting/index.mjs +415 -0
  50. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  51. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  52. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  53. package/bin/lib/remote/osSearch.mjs +107 -0
  54. package/bin/lib/remote/sqliteDb.mjs +51 -0
  55. package/bin/lib/remote/tabGroups.mjs +209 -0
  56. package/bin/lib/remote/toolHandlers.mjs +788 -726
  57. package/bin/lib/remoteControl.mjs +26 -26
  58. package/docs/AIVIN_MASCOT.md +130 -0
  59. package/docs/CLI.md +1504 -1353
  60. package/docs/media/aivin-mascot-live.gif +0 -0
  61. package/docs/media/aivin-mascot-live.png +0 -0
  62. package/docs/media/aivin-remote-architecture.svg +102 -0
  63. package/package.json +71 -71
@@ -0,0 +1,345 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import chalk from 'chalk';
5
+ import axios from 'axios';
6
+ import { execSync, spawn } from 'child_process';
7
+
8
+ // ── Finding, picking and launching the local Chromium browser AI Browser drives ─────────────────
9
+ //
10
+ // Shared by `aivin browser` (browserAutomation.mjs) and `aivin remote`'s browser tunnels
11
+ // (remote/browserTunnel.mjs, remote/dailyBrowser.mjs) - kept free of imports from either so neither
12
+ // side ends up in an import cycle with the other.
13
+
14
+ // A separate Chrome/Edge profile dedicated to `aivin browser`, NOT the user's real daily-driver
15
+ // profile. Reasoning (confirmed the hard way): `--remote-debugging-port` can only be set at process
16
+ // launch, never toggled on an already-running instance, AND Chromium's single-instance-per-profile
17
+ // lock means launching a second process against the SAME profile the user is already using just
18
+ // silently forwards to the existing (non-debuggable) instance instead of actually starting a new,
19
+ // debuggable one - so reusing the daily-driver profile meant demanding the user close every window
20
+ // first, every single time. A dedicated profile sidesteps all of that: it can launch/stay running
21
+ // fully independently of whatever the user's main browser is doing, at the cost of a one-time login
22
+ // (Facebook etc.) the first time it's used - after that, cookies persist here just like any profile.
23
+ export const AIVIN_BROWSER_PROFILE_DIR = path.join(os.homedir(), '.aivin', 'browser-profile');
24
+
25
+ // 9222 is Chrome/Edge's conventional remote-debugging port, but it's not reserved to them - anything
26
+ // can be listening there (found the hard way: this project's own local docker-compose stack publishes
27
+ // its headless Lightpanda container on host port 9222 too, for the unrelated `--remote` server-side
28
+ // browser pool). `probeLocalChromeDebugger` below verifies the `Browser` field before trusting a hit
29
+ // here, and `--debug-port` lets a real conflict just be sidestepped instead of fought.
30
+ export const CHROME_DEBUG_PORT = 9222;
31
+ export const DEBUG_PORTS = [CHROME_DEBUG_PORT, 9223, 9224, 9225];
32
+
33
+ /** Chrome 137+ ignores `--load-extension`; this flag is what lets the CLI load its own small tab-groups
34
+ * extension over CDP (`Extensions.loadUnpacked`, remote/tabGroups.mjs) - Edge accepts it too. Only ever
35
+ * passed for the dedicated Aivin profile, and the server can't use it: cdpPolicy.mjs blocks the whole
36
+ * `Extensions.*` domain on every tunnel. */
37
+ export const EXTENSION_DEBUGGING_FLAG = '--enable-unsafe-extension-debugging';
38
+
39
+ /** Chrome's own remote-debugging discovery endpoint - reachable only if the user already relaunched
40
+ * Chrome with `--remote-debugging-port`. Returns the CDP WebSocket URL for the whole browser, or
41
+ * null if nothing's listening there (or something else entirely is - see below). */
42
+ export async function probeLocalChromeDebugger(port = CHROME_DEBUG_PORT) {
43
+ try {
44
+ const res = await axios.get(`http://127.0.0.1:${port}/json/version`, { timeout: 2000 });
45
+ // Something answered - but NOT necessarily Chrome/Edge. Confirmed hitting this for real: this
46
+ // port is also where this project's own local dev stack publishes a headless Lightpanda
47
+ // container (no UI at all), which happily speaks CDP and would otherwise look identical to a
48
+ // real browser here - "mission ran but no window ever appeared" was the resulting symptom.
49
+ // Real Chrome/Edge both report a `Browser` field like "Chrome/123.0..." / "Edg/123.0..." (Brave
50
+ // and Chromium report themselves as "Chrome/..." too).
51
+ const product = String(res.data?.Browser || '');
52
+ if (!/^(Chrome|Edg)\//.test(product)) {
53
+ return { wsUrl: null, conflict: product || 'unknown service', browserId: null };
54
+ }
55
+ const browserId = /^Edg\//.test(product) ? 'edge' : 'chrome';
56
+ return { wsUrl: res.data?.webSocketDebuggerUrl || null, conflict: null, browserId };
57
+ } catch {
58
+ return { wsUrl: null, conflict: null, browserId: null };
59
+ }
60
+ }
61
+
62
+ // Any Chromium-based browser works identically here (same --remote-debugging-port / CDP protocol).
63
+ // Order here is only a last-resort tiebreaker (see findLocalBrowser) - actual selection prefers the
64
+ // user's real OS default browser via detectDefaultBrowserId(), or an explicit --browser flag.
65
+ // `%LOCALAPPDATA%` is expanded at lookup time (per-user installs - Chrome offers one without admin
66
+ // rights); Linux entries are executable names looked up on PATH.
67
+ export const LOCAL_BROWSERS = [
68
+ {
69
+ id: 'edge',
70
+ name: 'Microsoft Edge',
71
+ win32: ['C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe', 'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe'],
72
+ darwin: '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
73
+ linux: ['microsoft-edge', 'microsoft-edge-stable'],
74
+ profileDirWin32: ['AppData', 'Local', 'Microsoft', 'Edge', 'User Data'],
75
+ profileDirDarwin: ['Library', 'Application Support', 'Microsoft Edge'],
76
+ profileDirLinux: ['.config', 'microsoft-edge'],
77
+ },
78
+ {
79
+ id: 'chrome',
80
+ name: 'Google Chrome',
81
+ win32: [
82
+ 'C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe',
83
+ 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe',
84
+ '%LOCALAPPDATA%\\Google\\Chrome\\Application\\chrome.exe',
85
+ ],
86
+ darwin: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
87
+ linux: ['google-chrome', 'google-chrome-stable'],
88
+ profileDirWin32: ['AppData', 'Local', 'Google', 'Chrome', 'User Data'],
89
+ profileDirDarwin: ['Library', 'Application Support', 'Google', 'Chrome'],
90
+ profileDirLinux: ['.config', 'google-chrome'],
91
+ },
92
+ {
93
+ id: 'brave',
94
+ name: 'Brave',
95
+ win32: [
96
+ 'C:\\Program Files\\BraveSoftware\\Brave-Browser\\Application\\brave.exe',
97
+ 'C:\\Program Files (x86)\\BraveSoftware\\Brave-Browser\\Application\\brave.exe',
98
+ '%LOCALAPPDATA%\\BraveSoftware\\Brave-Browser\\Application\\brave.exe',
99
+ ],
100
+ darwin: '/Applications/Brave Browser.app/Contents/MacOS/Brave Browser',
101
+ linux: ['brave-browser', 'brave'],
102
+ profileDirWin32: ['AppData', 'Local', 'BraveSoftware', 'Brave-Browser', 'User Data'],
103
+ profileDirDarwin: ['Library', 'Application Support', 'BraveSoftware', 'Brave-Browser'],
104
+ profileDirLinux: ['.config', 'BraveSoftware', 'Brave-Browser'],
105
+ },
106
+ {
107
+ id: 'chromium',
108
+ name: 'Chromium',
109
+ win32: ['%LOCALAPPDATA%\\Chromium\\Application\\chrome.exe'],
110
+ darwin: '/Applications/Chromium.app/Contents/MacOS/Chromium',
111
+ linux: ['chromium', 'chromium-browser'],
112
+ profileDirWin32: ['AppData', 'Local', 'Chromium', 'User Data'],
113
+ profileDirDarwin: ['Library', 'Application Support', 'Chromium'],
114
+ profileDirLinux: ['.config', 'chromium'],
115
+ },
116
+ ];
117
+
118
+ export const LOCAL_BROWSER_IDS = LOCAL_BROWSERS.map((b) => b.id);
119
+
120
+ /** First of `names` found as an executable file on PATH - full path, or null. */
121
+ export function findOnPath(names, { envPath = process.env.PATH || '', exists = fs.existsSync } = {}) {
122
+ for (const dir of envPath.split(path.delimiter).filter(Boolean)) {
123
+ for (const name of names) {
124
+ const full = path.join(dir, name);
125
+ if (exists(full)) return full;
126
+ }
127
+ }
128
+ return null;
129
+ }
130
+
131
+ export function resolveBrowserInstall(browser) {
132
+ const home = os.homedir();
133
+ let exe;
134
+ let profileSegments;
135
+ if (process.platform === 'win32') {
136
+ const localAppData = process.env.LOCALAPPDATA || path.join(home, 'AppData', 'Local');
137
+ exe = browser.win32.map((p) => p.replace('%LOCALAPPDATA%', localAppData)).find((p) => fs.existsSync(p)) || null;
138
+ profileSegments = browser.profileDirWin32;
139
+ } else if (process.platform === 'darwin') {
140
+ exe = fs.existsSync(browser.darwin) ? browser.darwin : null;
141
+ profileSegments = browser.profileDirDarwin;
142
+ } else {
143
+ // Used to be assumed on PATH unconditionally - every Linux box then "had" both Edge and Chrome
144
+ // installed, and launching the missing one crashed the CLI with an unhandled spawn ENOENT.
145
+ exe = findOnPath(browser.linux);
146
+ profileSegments = browser.profileDirLinux;
147
+ }
148
+ if (!exe) return null;
149
+ return { id: browser.id, name: browser.name, exe, profileDir: path.join(home, ...profileSegments) };
150
+ }
151
+
152
+ /** Maps a ProgId / bundle id / .desktop name (anything naming the browser) to a LOCAL_BROWSERS id, or
153
+ * null for a non-Chromium browser (Firefox/Safari - no CDP to tunnel into). Chromium before Chrome:
154
+ * "ChromiumHTM" contains "chrome" too. */
155
+ export function browserIdFromName(name) {
156
+ const s = String(name || '').toLowerCase();
157
+ if (s.includes('edge')) return 'edge';
158
+ if (s.includes('brave')) return 'brave';
159
+ if (s.includes('chromium')) return 'chromium';
160
+ if (s.includes('chrome')) return 'chrome';
161
+ return null;
162
+ }
163
+
164
+ /** `reg query ...\UrlAssociations\http /s` output → the user's chosen browser id. Newer Windows 11
165
+ * builds keep the live choice under `UserChoiceLatest`, older ones under `UserChoice` - Latest wins
166
+ * when both exist. */
167
+ export function browserIdFromRegQuery(output) {
168
+ let current = '';
169
+ const progIds = [];
170
+ for (const line of String(output || '').split(/\r?\n/)) {
171
+ if (/^HKEY_/i.test(line.trim())) current = line.trim();
172
+ const m = /^\s*ProgId\s+REG_SZ\s+(\S+)/i.exec(line);
173
+ if (m) progIds.push({ key: current, progId: m[1] });
174
+ }
175
+ const pick = progIds.find((p) => /UserChoiceLatest/i.test(p.key)) || progIds.find((p) => /UserChoice/i.test(p.key));
176
+ return pick ? browserIdFromName(pick.progId) : null;
177
+ }
178
+
179
+ /** Best-effort read of the OS's actual "default browser" setting, mapped to one of LOCAL_BROWSERS'
180
+ * `id`s - or null if it can't be determined (unsupported platform, unknown browser, command
181
+ * missing/failed) or if the default is a non-Chromium browser (Firefox/Safari - no CDP support, so
182
+ * there's nothing to tunnel into). Never throws - this is a "nice to have" signal, `findLocalBrowser`
183
+ * falls back to install-order when it's unavailable. */
184
+ export function detectDefaultBrowserId() {
185
+ try {
186
+ if (process.platform === 'win32') {
187
+ const query = (key, extra = '') => {
188
+ try {
189
+ return execSync(`reg query "${key}"${extra}`,{ encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'], windowsHide: true });
190
+ } catch {
191
+ return '';
192
+ }
193
+ };
194
+ // What Settings > Default apps writes: the per-user UserChoice ProgId (MSEdgeHTM, ChromeHTML,
195
+ // BraveHTML...). Only WRITING it is hash-protected - reading is a plain registry read. An earlier
196
+ // version read `Classes\http\shell\open\command` instead, which on a stock install only exists
197
+ // under HKLM and keeps pointing at msedge.exe even after the user picks Chrome.
198
+ const choice = browserIdFromRegQuery(query('HKCU\\Software\\Microsoft\\Windows\\Shell\\Associations\\UrlAssociations\\http', ' /s'));
199
+ if (choice) return choice;
200
+ const command = query('HKCU\\Software\\Classes\\http\\shell\\open\\command') || query('HKLM\\Software\\Classes\\http\\shell\\open\\command');
201
+ if (/msedge\.exe/i.test(command)) return 'edge';
202
+ if (/brave\.exe/i.test(command)) return 'brave';
203
+ if (/chrome\.exe/i.test(command)) return 'chrome';
204
+ return null; // Firefox, or something unrecognized
205
+ }
206
+ if (process.platform === 'darwin') {
207
+ // No single stock CLI for this on macOS - LaunchServices' own plist is the source of truth
208
+ // Settings > Desktop & Dock reads from, `plutil` (stock, ships with macOS) can dump it as JSON.
209
+ const plistPath = path.join(
210
+ os.homedir(), 'Library', 'Preferences', 'com.apple.LaunchServices',
211
+ 'com.apple.launchservices.secure.plist',
212
+ );
213
+ if (!fs.existsSync(plistPath)) return null;
214
+ const json = execSync(`plutil -convert json -o - "${plistPath}"`, { encoding: 'utf8' });
215
+ const handlers = JSON.parse(json)?.LSHandlers || [];
216
+ const httpHandler = handlers.find((h) => h.LSHandlerURLScheme === 'http');
217
+ return browserIdFromName(httpHandler?.LSHandlerRoleAll); // Safari, Firefox, or undetermined → null
218
+ }
219
+ // Linux: xdg-settings is the freedesktop.org standard way, present on most desktop distros.
220
+ return browserIdFromName(execSync('xdg-settings get default-web-browser', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim());
221
+ } catch {
222
+ return null; // command missing, key absent, parse failure - all fine to just not know
223
+ }
224
+ }
225
+
226
+ /**
227
+ * Picks which installed browser to drive, in priority order:
228
+ * 1. `preferredId` (from `--browser`) - explicit always wins, errors clearly if that browser isn't
229
+ * actually installed rather than silently falling through to another one.
230
+ * 2. The OS's actual default browser, IF it's Chromium-based and installed - this is what makes
231
+ * "drives your own logged-in browser" true; guessing wrong here would tunnel into a browser
232
+ * profile the user doesn't actually use, with none of the cookies/logins they expect.
233
+ * 3. Whatever's installed from LOCAL_BROWSERS, in list order - last resort when the real default
234
+ * couldn't be determined or isn't Chromium (Firefox/Safari have no CDP to tunnel into).
235
+ * Logs which one it picked and why when there was more than one candidate (unless `quiet`), so step
236
+ * 3 in particular is never a silent surprise.
237
+ */
238
+ export function findLocalBrowser(preferredId, { quiet = false } = {}) {
239
+ const installed = LOCAL_BROWSERS.map(resolveBrowserInstall).filter(Boolean);
240
+ if (installed.length === 0) return null;
241
+
242
+ if (preferredId) {
243
+ const match = installed.find((b) => b.id === preferredId);
244
+ if (match) return match;
245
+ throw new Error(`--browser ${preferredId} was requested, but it isn't installed at any of the usual locations. Installed: ${installed.map((b) => b.id).join(', ') || 'none'}.`);
246
+ }
247
+
248
+ if (installed.length > 1) {
249
+ const defaultId = detectDefaultBrowserId();
250
+ const byDefault = defaultId && installed.find((b) => b.id === defaultId);
251
+ if (byDefault) return byDefault;
252
+ if (!quiet) {
253
+ console.log(chalk.gray(
254
+ ` (multiple browsers installed (${installed.map((b) => b.name).join(', ')}) and couldn't confirm your OS default - ` +
255
+ `using ${installed[0].name}. Pass --browser ${installed.map((b) => b.id).join('|')} to pick.)`,
256
+ ));
257
+ }
258
+ }
259
+
260
+ return installed[0];
261
+ }
262
+
263
+ /** The manual equivalent of launchLocalChromeWithDebugging - on the Aivin profile, since a window on any
264
+ * other profile is never attached to (only the user's everyday browser, via its own remote-debugging
265
+ * switch - see remoteDebuggingHint). */
266
+ export function launchCommandHint(browser, port = CHROME_DEBUG_PORT) {
267
+ const label = browser ? browser.name : 'Chrome or Edge';
268
+ const exe = browser ? `"${browser.exe}"` : '<your browser>';
269
+ const args = `--remote-debugging-port=${port} --user-data-dir="${AIVIN_BROWSER_PROFILE_DIR}" ${EXTENSION_DEBUGGING_FLAG}`;
270
+ if (process.platform === 'win32') return `& ${exe} ${args} (${label})`;
271
+ if (process.platform === 'darwin') return `open -na "${label}" --args ${args}`;
272
+ return `${browser ? browser.exe : 'google-chrome'} ${args}`;
273
+ }
274
+
275
+ /** Where the user switches on "Allow remote debugging" for their everyday browser (Chrome 144+ / Edge). */
276
+ export function remoteDebuggingHint(browser) {
277
+ return browser?.id === 'edge' ? 'edge://inspect/#remote-debugging' : 'chrome://inspect/#remote-debugging';
278
+ }
279
+
280
+ export function printChromeLaunchHelp(port = CHROME_DEBUG_PORT, preferredId) {
281
+ let browser = null;
282
+ try { browser = findLocalBrowser(preferredId, { quiet: true }); } catch { /* already reported by the caller's own error */ }
283
+ console.log(chalk.yellow('\n⚠️ Could not start the Aivin browser window. To start it yourself:'));
284
+ console.log(` ${chalk.cyan(launchCommandHint(browser, port))}\n`);
285
+ console.log(chalk.gray(` ...or use your everyday ${browser?.name || 'browser'}: open ${remoteDebuggingHint(browser)}, turn on "Allow remote debugging", and rerun.`));
286
+ console.log(chalk.gray(' ...or pass --remote for a server-side browser instead (no local browser needed).'));
287
+ }
288
+
289
+ /** Launches a browser window dedicated to `aivin browser`, on ITS OWN profile
290
+ * (AIVIN_BROWSER_PROFILE_DIR) - never the user's real daily-driver one. This is what makes local
291
+ * mode zero-friction after the first run: because it's a separate profile, it never collides with
292
+ * whatever the user's main browser is already doing (no "close all your windows first"), and once
293
+ * running it just stays up - a later mission finds it already listening and reuses it, opening a
294
+ * new tab in the SAME window rather than launching anything again. The one real cost: the first
295
+ * time any given site is used (Facebook, etc.), the user logs in once here, same as any fresh
296
+ * profile - after that it persists exactly like their main browser's cookies do. */
297
+ export async function launchLocalChromeWithDebugging(port = CHROME_DEBUG_PORT, preferredId, { log = (m) => console.log(chalk.gray(m)) } = {}) {
298
+ const browser = findLocalBrowser(preferredId, { quiet: true });
299
+ if (!browser) {
300
+ throw new Error(`Could not find a local Chrome/Edge install automatically - relaunch one manually with: ${launchCommandHint(null, port)}`);
301
+ }
302
+ const firstRun = !fs.existsSync(AIVIN_BROWSER_PROFILE_DIR);
303
+ fs.mkdirSync(AIVIN_BROWSER_PROFILE_DIR, { recursive: true });
304
+ // No pre-flight SingletonLock check here on purpose (an earlier version of this had one, copied
305
+ // from the old "don't touch the user's real profile" logic where it made sense): by the time we
306
+ // get here, probeLocalChromeDebugger() has ALREADY confirmed nothing is answering on `port`, so a
307
+ // present lock file can only be stale (left behind by an unclean shutdown/crash) - Chromium itself
308
+ // already detects and clears stale locks on startup (checks whether the owning PID is still
309
+ // alive), more reliably than re-implementing that check here. A pre-check could only ever produce
310
+ // a false positive: a confusing "already open, go close it" error pointing at a window that isn't
311
+ // actually running anywhere.
312
+ if (firstRun) {
313
+ log(` First run: opening a NEW, separate ${browser.name} window just for AI Browser (your regular ${browser.name} is untouched).`);
314
+ log(` You'll need to log into any site the mission needs (Facebook, etc.) once in THIS window - it'll stay logged in from then on.`);
315
+ } else {
316
+ log(` Opening your dedicated AI Browser window...`);
317
+ }
318
+ const child = spawn(
319
+ browser.exe,
320
+ [`--remote-debugging-port=${port}`, `--user-data-dir=${AIVIN_BROWSER_PROFILE_DIR}`, '--no-first-run', '--start-maximized', EXTENSION_DEBUGGING_FLAG],
321
+ { detached: true, stdio: 'ignore' },
322
+ );
323
+ // Without a listener, a failed spawn (exe gone since lookup, no permission) is an unhandled 'error'
324
+ // event - it took the whole CLI down with a stack trace instead of the launch help below.
325
+ let spawnError = null;
326
+ child.once('error', (e) => { spawnError = e; });
327
+ child.unref();
328
+ for (let i = 0; i < 20; i++) {
329
+ await new Promise((resolve) => setTimeout(resolve, 500));
330
+ if (spawnError) {
331
+ throw new Error(spawnError.code === 'ENOENT'
332
+ ? `Could not find ${browser.name} at ${browser.exe}`
333
+ : `Could not start ${browser.name}: ${spawnError.message}`);
334
+ }
335
+ const { wsUrl, conflict } = await probeLocalChromeDebugger(port);
336
+ if (wsUrl) return wsUrl;
337
+ if (conflict) {
338
+ throw new Error(
339
+ `Port ${port} is already in use by something else (reported itself as "${conflict}", not Chrome/Edge) - ` +
340
+ `${browser.name} can't bind its debug port there. Free that port, or rerun with --debug-port <other-port>.`,
341
+ );
342
+ }
343
+ }
344
+ throw new Error(`${browser.name} launched but its debug port never came up in time.`);
345
+ }
@@ -63,6 +63,6 @@ export function clearLogs() {
63
63
  }
64
64
  return { success: true };
65
65
  } catch (err) {
66
- throw new Error(`Không thể xóa nhật ký hoạt động: ${err.message}`);
66
+ throw new Error(`Không thể xóa nhật ký hoạt động: ${err.message}`, { cause: err });
67
67
  }
68
68
  }
@@ -7,6 +7,16 @@ import { REMOTE_CONFIG_DIR } from './deviceProfile.mjs';
7
7
  import { DeviceAccess } from './constants.mjs';
8
8
  import { loadDeviceCredentials } from './credentials.mjs';
9
9
  import { RESTART_EXIT_CODE, UPDATE_PENDING_FILE, UPDATE_ROLLBACK_FILE } from '../selfUpdate.mjs';
10
+ import {
11
+ DESKTOP_DIR, RUN_KEY, STARTUP_VALUE, TrayLaunch, installDesktop, isDesktopInstalled, launcherExePath, readSavedDaemonArgs, setStartupApproved,
12
+ startMenuShortcutPath, startupState, uninstallDesktop,
13
+ } from './desktop/index.mjs';
14
+ import { installMacDesktop, isMacDesktopInstalled, macAgentPath, macAppPath, macStartupState, setMacStartup, uninstallMacDesktop } from './desktop/mac.mjs';
15
+ import {
16
+ hasLinuxDesktopSession, installLinuxDesktop, isLinuxDesktopInstalled, linuxAppEntryPath, linuxAutostartPath, linuxStartupState, linuxTrayAvailable,
17
+ setLinuxStartup, uninstallLinuxDesktop,
18
+ } from './desktop/linux.mjs';
19
+ import { mascotLang } from './mascot/strings.mjs';
10
20
 
11
21
  const __filename = fileURLToPath(import.meta.url);
12
22
  const __dirname = path.dirname(__filename);
@@ -153,7 +163,7 @@ export function posixRunScript(argv, { supervisor, rollback = null }) {
153
163
  `FAST=${q(rollback.fastFailFile)}`,
154
164
  'started=$(date +%s)',
155
165
  ] : []),
156
- argv.map(q).join(' '),
166
+ `${argv.map(q).join(' ')} "$@"`,
157
167
  'rc=$?',
158
168
  ...(rollback ? [
159
169
  'elapsed=$(( $(date +%s) - started ))',
@@ -182,7 +192,7 @@ function writePosixRunScript(argv, supervisor, launch) {
182
192
 
183
193
  /** Biến môi trường trình giữ chạy của Aivin đặt cho daemon. */
184
194
  export const SUPERVISOR_ENV = 'AIVIN_SUPERVISOR';
185
- export const Supervisor = Object.freeze({ WSCRIPT: 'wscript', LAUNCHD: 'launchd', SYSTEMD: 'systemd' });
195
+ export const Supervisor = Object.freeze({ WSCRIPT: 'wscript', TRAY: 'tray', LAUNCHD: 'launchd', SYSTEMD: 'systemd' });
186
196
 
187
197
  function parentCommandLine() {
188
198
  try {
@@ -287,8 +297,16 @@ function windowsTaskExists() {
287
297
  }
288
298
  }
289
299
 
290
- /** Windows: tác vụ Task Scheduler chạy kịch bản giữ chạy; máy chặn tạo tác vụ (chính sách công ty) → chép kịch bản vào thư mục Startup. */
291
- function enableWindows(argv, launch) {
300
+ /** Gỡ cách tự khởi động cũ của Windows (tác vụ Task Scheduler / VBS ở Startup) — tiến trình VBS đang chạy vẫn chạy tới khi tắt máy. */
301
+ function removeLegacyWindowsAutoStart() {
302
+ try { schtasks(['/Delete', '/TN', WINDOWS_TASK_NAME, '/F']); } catch { /* chưa có tác vụ */ }
303
+ for (const file of [getAutoStartFilePath(), WINDOWS_WATCHDOG_FILE, WINDOWS_TASK_XML_FILE]) {
304
+ try { fs.rmSync(file, { force: true }); } catch { /* tệp đang bị khoá */ }
305
+ }
306
+ }
307
+
308
+ /** Dự phòng: tác vụ Task Scheduler chạy kịch bản VBS; máy chặn tạo tác vụ (chính sách công ty) → chép kịch bản vào thư mục Startup. */
309
+ function enableWindowsTask(argv, launch) {
292
310
  const script = windowsWatchdogScript(argv, { rollback: supervisorRollbackPaths(launch) });
293
311
  writeUtf16(WINDOWS_WATCHDOG_FILE, script);
294
312
  const startupFile = getAutoStartFilePath();
@@ -305,6 +323,135 @@ function enableWindows(argv, launch) {
305
323
  }
306
324
  }
307
325
 
326
+ const RUN_ENTRY = `${RUN_KEY}\\${STARTUP_VALUE}`;
327
+
328
+ /**
329
+ * Windows: ứng dụng khay Aivin.exe (desktop/) giữ daemon chạy, mục khởi động ở khoá Run (hiện + bật / tắt được trong Task Manager →
330
+ * Startup apps), lối tắt Start menu. Không dựng được Aivin.exe (máy chặn csc / PowerShell) → lùi về tác vụ Task Scheduler như trước.
331
+ */
332
+ function enableWindows(argv, launch) {
333
+ try {
334
+ installDesktop({ argv, rollback: supervisorRollbackPaths(launch), lang: mascotLang(), autostart: true, launch: true, launchMode: TrayLaunch.AUTOSTART });
335
+ removeLegacyWindowsAutoStart();
336
+ return { filePath: `${RUN_ENTRY} (Task Manager → Startup apps)`, method: 'run' };
337
+ } catch (e) {
338
+ const res = enableWindowsTask(argv, launch);
339
+ const why = `Không dựng được ứng dụng khay Aivin (${String(e?.message || e).trim()}) — dùng ${res.method === 'task' ? 'Task Scheduler' : 'thư mục Startup'}`;
340
+ return { ...res, warning: [why, res.warning].filter(Boolean).join('; ') };
341
+ }
342
+ }
343
+
344
+ function writeDaemonConfig({ rootDir, filePath, method, nodeExec }) {
345
+ fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
346
+ const daemonConfig = {
347
+ enabled: true,
348
+ platform: process.platform,
349
+ rootDir,
350
+ autoStartFile: filePath,
351
+ ...(method ? { method } : {}),
352
+ nodeExec,
353
+ updatedAt: new Date().toISOString(),
354
+ };
355
+ fs.writeFileSync(REMOTE_DAEMON_FILE, JSON.stringify(daemonConfig, null, 2) + '\n', 'utf8');
356
+ }
357
+
358
+ /**
359
+ * macOS / Linux: biểu tượng thanh menu / khay (desktop/mac.mjs, desktop/linux.mjs) chạy aivin-remote-run.sh — một kịch bản cho cả hai,
360
+ * dấu trình giữ chạy = tray. Đối số daemon lưu riêng (daemon-args.json) để `aivin desktop install` sau giữ `--dir` / `--proxy`.
361
+ */
362
+ const POSIX_DESKTOP = {
363
+ darwin: {
364
+ install: installMacDesktop, uninstall: uninstallMacDesktop, installed: isMacDesktopInstalled, state: macStartupState, setStartup: setMacStartup,
365
+ entry: () => `${macAgentPath()} (System Settings → General → Login Items)`, app: () => macAppPath(), search: 'Spotlight / Launchpad',
366
+ },
367
+ linux: {
368
+ install: installLinuxDesktop, uninstall: uninstallLinuxDesktop, installed: isLinuxDesktopInstalled, state: linuxStartupState, setStartup: setLinuxStartup,
369
+ entry: () => linuxAutostartPath(), app: () => linuxAppEntryPath(), search: 'menu ứng dụng',
370
+ },
371
+ };
372
+ const DAEMON_ARGS_FILE = path.join(DESKTOP_DIR, 'daemon-args.json');
373
+
374
+ function readPosixDaemonArgs() {
375
+ try {
376
+ const args = JSON.parse(fs.readFileSync(DAEMON_ARGS_FILE, 'utf8'));
377
+ return Array.isArray(args) ? args.map(String) : null;
378
+ } catch {
379
+ return null;
380
+ }
381
+ }
382
+
383
+ function installPosixDesktop(argv, launch, options) {
384
+ const desktop = POSIX_DESKTOP[process.platform];
385
+ const [runShell, runScript] = writePosixRunScript(argv, Supervisor.TRAY, launch);
386
+ fs.mkdirSync(DESKTOP_DIR, { recursive: true });
387
+ fs.writeFileSync(DAEMON_ARGS_FILE, JSON.stringify(argv.slice(argv.indexOf('start') + 1)));
388
+ const res = desktop.install({ runScript, lang: mascotLang(), ...options });
389
+ return { ...res, runShell };
390
+ }
391
+
392
+ /** `aivin remote enable` trên macOS / Linux có màn hình: thanh menu / khay + mục khởi động; lỗi → cách cũ (LaunchAgent / systemd + autostart). */
393
+ function tryPosixDesktop(argv, launch) {
394
+ const desktop = POSIX_DESKTOP[process.platform];
395
+ if (!desktop || (process.platform === 'linux' && !hasLinuxDesktopSession())) return null;
396
+ try {
397
+ installPosixDesktop(argv, launch, { autostart: true, launch: true, launchMode: TrayLaunch.AUTOSTART });
398
+ return { filePath: desktop.entry(), method: 'desktop' };
399
+ } catch (e) {
400
+ return { warning: `Không dựng được ứng dụng Aivin trên màn hình (${String(e?.message || e).trim()}) — dùng cách tự khởi động cũ` };
401
+ }
402
+ }
403
+
404
+ /**
405
+ * `aivin desktop install` (bộ cài install.ps1 / install.sh gọi): Windows = khay + Start menu, macOS = Aivin.app + thanh menu, Linux = menu ứng
406
+ * dụng + khay; (mặc định) khởi động cùng máy. Giữ đối số daemon của lần `aivin remote enable` trước; chưa có thì `remote start --quiet`
407
+ * trần — daemon dùng thư mục / chế độ đã lưu lúc ghép máy.
408
+ */
409
+ export function installDesktopApp({ autostart = true, launch = true } = {}) {
410
+ const cli = cliLaunchCommand();
411
+ if (process.platform === 'win32') {
412
+ const argv = [...cli, 'remote', 'start', ...(readSavedDaemonArgs() || ['--quiet'])];
413
+ const res = installDesktop({ argv, rollback: supervisorRollbackPaths(cli), lang: mascotLang(), autostart, launch });
414
+ if (autostart) {
415
+ removeLegacyWindowsAutoStart();
416
+ writeDaemonConfig({ rootDir: os.homedir(), filePath: RUN_ENTRY, method: 'run', nodeExec: cli[0] });
417
+ }
418
+ return res;
419
+ }
420
+ const desktop = POSIX_DESKTOP[process.platform];
421
+ if (!desktop) throw new Error(`Chưa hỗ trợ ứng dụng Aivin trên màn hình cho ${process.platform}.`);
422
+ const argv = [...cli, 'remote', 'start', ...(readPosixDaemonArgs() || ['--quiet'])];
423
+ const res = installPosixDesktop(argv, cli, { autostart, launch, launchMode: TrayLaunch.INSTALLED });
424
+ if (autostart) writeDaemonConfig({ rootDir: os.homedir(), filePath: desktop.entry(), method: 'desktop', nodeExec: cli[0] });
425
+ return res;
426
+ }
427
+
428
+ /** `aivin desktop uninstall`: gỡ ứng dụng + mục khởi động (tiến trình daemon nó giữ cũng dừng). */
429
+ export function uninstallDesktopApp() {
430
+ if (process.platform === 'win32') return uninstallDesktop();
431
+ const desktop = POSIX_DESKTOP[process.platform];
432
+ if (!desktop) return { removed: true };
433
+ const res = desktop.uninstall();
434
+ fs.rmSync(POSIX_RUN_SCRIPT_FILE, { force: true });
435
+ return res;
436
+ }
437
+
438
+ /** `aivin desktop`: đã cài chưa, ở đâu, tìm bằng gì, khởi động cùng máy, (Linux) có biểu tượng khay không. */
439
+ export function desktopAppStatus() {
440
+ if (process.platform === 'win32') {
441
+ return {
442
+ installed: isDesktopInstalled(), app: launcherExePath(), search: fs.existsSync(startMenuShortcutPath()) ? 'Start menu' : null,
443
+ startup: startupState(), tray: true,
444
+ };
445
+ }
446
+ const desktop = POSIX_DESKTOP[process.platform];
447
+ if (!desktop) return { installed: false, supported: false };
448
+ const installed = desktop.installed();
449
+ return {
450
+ installed, app: desktop.app(), search: installed ? desktop.search : null, startup: desktop.state(),
451
+ tray: process.platform === 'darwin' ? true : linuxTrayAvailable(),
452
+ };
453
+ }
454
+
308
455
  /** Kích hoạt tự khởi động cùng máy tính trên mọi hệ điều hành (Windows, macOS, Linux). */
309
456
  export function enableAutoStart(options = {}) {
310
457
  const rootDir = path.resolve(options.dir || process.cwd());
@@ -320,10 +467,15 @@ export function enableAutoStart(options = {}) {
320
467
 
321
468
  fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
322
469
 
470
+ const desktop = process.platform === 'win32' ? null : tryPosixDesktop(argv, launch);
323
471
  if (process.platform === 'win32') {
324
472
  extra = enableWindows(argv, launch);
325
473
  filePath = extra.filePath;
474
+ } else if (desktop?.filePath) {
475
+ extra = desktop;
476
+ filePath = desktop.filePath;
326
477
  } else if (process.platform === 'darwin') {
478
+ if (desktop?.warning) extra = { warning: desktop.warning };
327
479
  // macOS: LaunchAgent chạy kịch bản sh (tự lùi bản ngoài tệp chạy), chỉ chạy lại khi thoát bất thường (mã khác 0).
328
480
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
329
481
  const runArgv = writePosixRunScript(argv, Supervisor.LAUNCHD, launch);
@@ -360,6 +512,7 @@ ${runArgv.map((part) => ` <string>${xmlEscape(part)}</string>`).join('\n'
360
512
  `;
361
513
  fs.writeFileSync(filePath, plistContent, 'utf8');
362
514
  } else {
515
+ if (desktop?.warning) extra = { warning: desktop.warning };
363
516
  // Linux: dịch vụ người dùng systemd chạy kịch bản sh (chạy lại khi thoát bất thường, tự lùi bản) + tệp XDG autostart cho máy không bật
364
517
  // systemd user session (chạy thẳng, không có trình giữ chạy → không tự chuyển bản).
365
518
  fs.mkdirSync(path.dirname(filePath), { recursive: true });
@@ -397,16 +550,7 @@ X-GNOME-Autostart-enabled=true
397
550
  fs.writeFileSync(desktopPath, desktopContent, 'utf8');
398
551
  }
399
552
 
400
- const daemonConfig = {
401
- enabled: true,
402
- platform: process.platform,
403
- rootDir,
404
- autoStartFile: filePath,
405
- ...(extra.method ? { method: extra.method } : {}),
406
- nodeExec,
407
- updatedAt: new Date().toISOString(),
408
- };
409
- fs.writeFileSync(REMOTE_DAEMON_FILE, JSON.stringify(daemonConfig, null, 2) + '\n', 'utf8');
553
+ writeDaemonConfig({ rootDir, filePath, method: extra.method, nodeExec });
410
554
 
411
555
  return { success: true, filePath, rootDir, platform: process.platform, ...(extra.warning ? { warning: extra.warning } : {}) };
412
556
  }
@@ -415,8 +559,15 @@ X-GNOME-Autostart-enabled=true
415
559
  export function disableAutoStart() {
416
560
  if (process.platform === 'win32') {
417
561
  try { schtasks(['/Delete', '/TN', WINDOWS_TASK_NAME, '/F']); } catch { /* chưa có tác vụ */ }
562
+ // Khoá Run: đánh dấu tắt như Task Manager — mục vẫn hiện "Disabled", bật lại được ở đó / menu khay / `aivin remote enable`.
563
+ if (startupState().registered) setStartupApproved(false);
418
564
  }
565
+ // macOS / Linux đã cài ứng dụng: chỉ tắt mục khởi động (bật lại được ở menu / Login Items / Startup Applications); giữ kịch bản chạy cho app.
566
+ const desktop = POSIX_DESKTOP[process.platform];
567
+ const keepRunScript = Boolean(desktop?.installed());
568
+ if (keepRunScript) desktop.setStartup(false);
419
569
  for (const filePath of getAllAutoStartFilePaths()) {
570
+ if (keepRunScript && filePath === POSIX_RUN_SCRIPT_FILE) continue;
420
571
  try { fs.rmSync(filePath, { force: true }); } catch { /* tệp đang bị khoá */ }
421
572
  }
422
573
 
@@ -445,6 +596,15 @@ export function getAutoStartStatus() {
445
596
  daemonConfig = null;
446
597
  }
447
598
  }
599
+ // Windows: khoá Run là nguồn sự thật — người dùng có thể bật / tắt ở Task Manager hay menu khay, không qua aivin.
600
+ const run = process.platform === 'win32' ? startupState() : null;
601
+ if (run?.registered) {
602
+ return { enabled: run.enabled, filePath: RUN_ENTRY, rootDir: daemonConfig?.rootDir || process.cwd(), updatedAt: daemonConfig?.updatedAt || null };
603
+ }
604
+ const desktop = POSIX_DESKTOP[process.platform];
605
+ if (desktop?.installed() && desktop.state().registered) {
606
+ return { enabled: desktop.state().enabled, filePath: desktop.entry(), rootDir: daemonConfig?.rootDir || process.cwd(), updatedAt: daemonConfig?.updatedAt || null };
607
+ }
448
608
  const task = process.platform === 'win32' && daemonConfig?.method === 'task' && windowsTaskExists();
449
609
  const installed = task || fs.existsSync(startupFile);
450
610