@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.
- package/README.md +288 -216
- package/bin/assets/aivin-mascot.png +0 -0
- package/bin/cli.mjs +551 -5
- package/bin/lib/browserAutomation.mjs +384 -614
- package/bin/lib/browserTui.mjs +276 -251
- package/bin/lib/cancellation.mjs +61 -0
- package/bin/lib/localBrowser.mjs +345 -0
- package/bin/lib/mcpProxy.mjs +869 -837
- package/bin/lib/missionStream.mjs +696 -691
- package/bin/lib/releaseKeys.mjs +9 -0
- package/bin/lib/remote/activityLog.mjs +68 -0
- package/bin/lib/remote/autoStart.mjs +617 -0
- package/bin/lib/remote/autoUpdate.mjs +129 -0
- package/bin/lib/remote/brand.mjs +60 -0
- package/bin/lib/remote/browserTunnel.mjs +403 -0
- package/bin/lib/remote/callLedger.mjs +134 -0
- package/bin/lib/remote/cdpPolicy.mjs +79 -0
- package/bin/lib/remote/client.mjs +808 -0
- package/bin/lib/remote/clipboard.mjs +138 -0
- package/bin/lib/remote/codingAgents.mjs +293 -0
- package/bin/lib/remote/constants.mjs +234 -0
- package/bin/lib/remote/credentials.mjs +208 -0
- package/bin/lib/remote/daemonLock.mjs +86 -0
- package/bin/lib/remote/dailyBrowser.mjs +371 -0
- package/bin/lib/remote/desktop/index.mjs +272 -0
- package/bin/lib/remote/desktop/linux.mjs +144 -0
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
- package/bin/lib/remote/desktop/mac.mjs +187 -0
- package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
- package/bin/lib/remote/desktop/strings.mjs +74 -0
- package/bin/lib/remote/desktop/traySource.mjs +527 -0
- package/bin/lib/remote/deviceMemory.mjs +246 -0
- package/bin/lib/remote/deviceProfile.mjs +142 -0
- package/bin/lib/remote/deviceWatches.mjs +138 -0
- package/bin/lib/remote/docText.mjs +117 -0
- package/bin/lib/remote/fileIndexer.mjs +399 -0
- package/bin/lib/remote/gui/index.mjs +326 -0
- package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
- package/bin/lib/remote/gui/windowsHost.mjs +109 -0
- package/bin/lib/remote/gui/windowsHostSource.mjs +1156 -0
- package/bin/lib/remote/httpTransfer.mjs +89 -0
- package/bin/lib/remote/idempotency.mjs +135 -0
- package/bin/lib/remote/keepAwake.mjs +100 -0
- package/bin/lib/remote/localConfirm.mjs +268 -0
- package/bin/lib/remote/localPolicy.mjs +256 -0
- package/bin/lib/remote/mascot/adpcm.mjs +70 -0
- package/bin/lib/remote/mascot/ask.mjs +768 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
- package/bin/lib/remote/mascot/assets.mjs +827 -0
- package/bin/lib/remote/mascot/bot.mjs +372 -0
- package/bin/lib/remote/mascot/hostSource.mjs +759 -0
- package/bin/lib/remote/mascot/hotkey.mjs +66 -0
- package/bin/lib/remote/mascot/index.mjs +493 -0
- package/bin/lib/remote/mascot/labels.mjs +82 -0
- package/bin/lib/remote/mascot/rigSource.mjs +609 -0
- package/bin/lib/remote/mascot/strings.mjs +375 -0
- package/bin/lib/remote/mascot/ui.mjs +104 -0
- package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
- package/bin/lib/remote/meeting/index.mjs +415 -0
- package/bin/lib/remote/meeting/recorder.mjs +109 -0
- package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
- package/bin/lib/remote/meeting/transcribe.mjs +259 -0
- package/bin/lib/remote/memberFsPool.mjs +134 -0
- package/bin/lib/remote/memberFsWorker.mjs +60 -0
- package/bin/lib/remote/mission.mjs +156 -0
- package/bin/lib/remote/missionQuestion.mjs +63 -0
- package/bin/lib/remote/multiUser.mjs +344 -0
- package/bin/lib/remote/netProxy.mjs +145 -0
- package/bin/lib/remote/notify.mjs +58 -0
- package/bin/lib/remote/office/index.mjs +90 -0
- package/bin/lib/remote/policyCommand.mjs +93 -0
- package/bin/lib/remote/processes.mjs +217 -0
- package/bin/lib/remote/sandbox.mjs +221 -0
- package/bin/lib/remote/schedule.mjs +213 -0
- package/bin/lib/remote/scheduler.mjs +124 -0
- package/bin/lib/remote/tabGroups.mjs +209 -0
- package/bin/lib/remote/textIndex.mjs +131 -0
- package/bin/lib/remote/tokenStore.mjs +77 -0
- package/bin/lib/remote/toolHandlers.mjs +741 -0
- package/bin/lib/remote/undoStore.mjs +242 -0
- package/bin/lib/remoteControl.mjs +26 -0
- package/bin/lib/scaffold.mjs +654 -653
- package/bin/lib/selfUpdate.mjs +71 -0
- package/bin/lib/update/binarySwap.mjs +63 -0
- package/bin/lib/update/constants.mjs +56 -0
- package/bin/lib/update/download.mjs +145 -0
- package/bin/lib/update/signature.mjs +42 -0
- package/bin/lib/update/state.mjs +205 -0
- package/bin/lib/update/versions.mjs +60 -0
- package/docs/AIVIN_MASCOT.md +116 -0
- package/docs/CLI.md +1484 -1299
- package/docs/media/aivin-mascot-states.mp4 +0 -0
- package/package.json +71 -62
|
@@ -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
|
+
}
|