@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
@@ -3,43 +3,38 @@ import path from 'path';
3
3
  import os from 'os';
4
4
  import chalk from 'chalk';
5
5
  import axios from 'axios';
6
- import { execSync, spawn } from 'child_process';
7
6
  import { randomUUID } from 'crypto';
8
- import WSClient from 'ws';
9
7
  import { missionServerUrl, missionAuthHeaders, resolveWorkspace, resolveAgentInteractive, createAgent, pullAgentIntoWorkspace } from './workspace.mjs';
10
8
  import { parseApiKeyClient } from './auth.mjs';
11
9
  import { guessStartUrl, BROWSER_MISSION_PREFIX } from './missionStream.mjs';
12
10
  import { watchBrowserMission } from './browserTui.mjs';
11
+ import { DEBUG_PORTS, LOCAL_BROWSER_IDS, findLocalBrowser, printChromeLaunchHelp } from './localBrowser.mjs';
12
+ import { isBlockedUrl } from './remote/cdpPolicy.mjs';
13
+ import { createBrowserTunnels, ensureAivinBrowser } from './remote/browserTunnel.mjs';
13
14
 
14
- // ── `aivin browser` default mode: drive the user's OWN local, already-running browser ──────────
15
+ // Moved to localBrowser.mjs (shared with `aivin remote`) - re-exported so existing imports keep working.
16
+ export {
17
+ AIVIN_BROWSER_PROFILE_DIR, CHROME_DEBUG_PORT, LOCAL_BROWSERS, detectDefaultBrowserId, findLocalBrowser, launchCommandHint,
18
+ launchLocalChromeWithDebugging, printChromeLaunchHelp, probeLocalChromeDebugger, resolveBrowserInstall,
19
+ } from './localBrowser.mjs';
20
+
21
+ // ── `aivin browser` default mode: drive the user's OWN local browser ────────────────────────────
15
22
  //
16
23
  // Real cookies/logins, real fingerprint - much better bot-detection resistance than the server-
17
24
  // side pooled browser `--remote` uses. Architecture: a raw WebSocket relay on the backend
18
25
  // (BrowserTunnelRelay) pairs this CLI's connection to the user's local Chrome CDP endpoint with
19
26
  // AIBrowserService's own `BrowserIO.connect(...)` call server-side - the EXISTING agentic loop
20
- // (causality, bot-guard, semantic matching, HIL) drives that real browser unmodified, this file
21
- // only ever pipes opaque frames, never inspects them.
27
+ // (causality, bot-guard, semantic matching, HIL) drives that real browser unmodified.
28
+ //
29
+ // The tunnel itself is `aivin remote`'s (remote/browserTunnel.mjs), authenticated with the API key
30
+ // instead of a device token. An earlier version had its own raw pipe here that forwarded every frame
31
+ // unfiltered (the server could open file:// URLs, redirect downloads anywhere, upload local files) and
32
+ // attached to ANY Chrome/Edge answering on 9222-9225 - including the user's real daily browser if it
33
+ // happened to have a debug port open. Sharing the tunnel gets the CDP policy filter (cdpPolicy.mjs),
34
+ // "only the Aivin-profile window" check, the guarded daily-browser mode and tab grouping in one place.
22
35
 
23
36
  export const BROWSER_CLI_AGENT_CACHE_PATH = path.join(os.homedir(), '.aivin', 'browser-cli-agents.json');
24
37
 
25
- // A separate Chrome/Edge profile dedicated to `aivin browser`, NOT the user's real daily-driver
26
- // profile. Reasoning (confirmed the hard way): `--remote-debugging-port` can only be set at process
27
- // launch, never toggled on an already-running instance, AND Chromium's single-instance-per-profile
28
- // lock means launching a second process against the SAME profile the user is already using just
29
- // silently forwards to the existing (non-debuggable) instance instead of actually starting a new,
30
- // debuggable one - so reusing the daily-driver profile meant demanding the user close every window
31
- // first, every single time. A dedicated profile sidesteps all of that: it can launch/stay running
32
- // fully independently of whatever the user's main browser is doing, at the cost of a one-time login
33
- // (Facebook etc.) the first time it's used - after that, cookies persist here just like any profile.
34
- export const AIVIN_BROWSER_PROFILE_DIR = path.join(os.homedir(), '.aivin', 'browser-profile');
35
-
36
- // 9222 is Chrome/Edge's conventional remote-debugging port, but it's not reserved to them - anything
37
- // can be listening there (found the hard way: this project's own local docker-compose stack publishes
38
- // its headless Lightpanda container on host port 9222 too, for the unrelated `--remote` server-side
39
- // browser pool). `probeLocalChromeDebugger` below verifies the `Browser` field before trusting a hit
40
- // here, and `--debug-port` lets a real conflict just be sidestepped instead of fought.
41
- export const CHROME_DEBUG_PORT = 9222;
42
-
43
38
  export function loadBrowserCliAgentCache() {
44
39
  try {
45
40
  return JSON.parse(fs.readFileSync(BROWSER_CLI_AGENT_CACHE_PATH, 'utf8'));
@@ -128,452 +123,220 @@ export async function resolveOrCreateBrowserAgent(serverUrl, authHeaders, worksp
128
123
  return agentId;
129
124
  }
130
125
 
131
- /** Chrome's own remote-debugging discovery endpoint - reachable only if the user already relaunched
132
- * Chrome with `--remote-debugging-port`. Returns the CDP WebSocket URL for the whole browser, or
133
- * null if nothing's listening there (or something else entirely is - see below). */
134
- export async function probeLocalChromeDebugger(port = CHROME_DEBUG_PORT) {
135
- try {
136
- const res = await axios.get(`http://127.0.0.1:${port}/json/version`, { timeout: 2000 });
137
- // Something answered - but NOT necessarily Chrome/Edge. Confirmed hitting this for real: this
138
- // port is also where this project's own local dev stack publishes a headless Lightpanda
139
- // container (no UI at all), which happily speaks CDP and would otherwise look identical to a
140
- // real browser here - "mission ran but no window ever appeared" was the resulting symptom.
141
- // Real Chrome/Edge both report a `Browser` field like "Chrome/123.0..." / "Edg/123.0...".
142
- const product = String(res.data?.Browser || '');
143
- if (!/^(Chrome|Edg)\//.test(product)) {
144
- return { wsUrl: null, conflict: product || 'unknown service', browserId: null };
145
- }
146
- const browserId = /^Edg\//.test(product) ? 'edge' : 'chrome';
147
- return { wsUrl: res.data?.webSocketDebuggerUrl || null, conflict: null, browserId };
148
- } catch {
149
- return { wsUrl: null, conflict: null, browserId: null };
150
- }
151
- }
152
-
153
- // Any Chromium-based browser works identically here (same --remote-debugging-port / CDP protocol).
154
- // Order here is only a last-resort tiebreaker (see findLocalBrowser) - actual selection prefers the
155
- // user's real OS default browser via detectDefaultBrowserId(), or an explicit --browser flag.
156
- export const LOCAL_BROWSERS = [
157
- {
158
- id: 'edge',
159
- name: 'Microsoft Edge',
160
- win32: ['C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe', 'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe'],
161
- darwin: '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
162
- linux: 'microsoft-edge',
163
- profileDirWin32: ['AppData', 'Local', 'Microsoft', 'Edge', 'User Data'],
164
- profileDirDarwin: ['Library', 'Application Support', 'Microsoft Edge'],
165
- profileDirLinux: ['.config', 'microsoft-edge'],
166
- },
167
- {
168
- id: 'chrome',
169
- name: 'Google Chrome',
170
- win32: ['C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'],
171
- darwin: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
172
- linux: 'google-chrome',
173
- profileDirWin32: ['AppData', 'Local', 'Google', 'Chrome', 'User Data'],
174
- profileDirDarwin: ['Library', 'Application Support', 'Google', 'Chrome'],
175
- profileDirLinux: ['.config', 'google-chrome'],
176
- },
177
- ];
178
-
179
- export function resolveBrowserInstall(browser) {
180
- const home = os.homedir();
181
- let exe;
182
- let profileSegments;
183
- if (process.platform === 'win32') {
184
- exe = browser.win32.find((p) => fs.existsSync(p)) || null;
185
- profileSegments = browser.profileDirWin32;
186
- } else if (process.platform === 'darwin') {
187
- exe = fs.existsSync(browser.darwin) ? browser.darwin : null;
188
- profileSegments = browser.profileDirDarwin;
189
- } else {
190
- exe = browser.linux; // assumed on PATH on Linux - no reliable single default install path there
191
- profileSegments = browser.profileDirLinux;
192
- }
193
- if (!exe) return null;
194
- return { id: browser.id, name: browser.name, exe, profileDir: path.join(home, ...profileSegments) };
195
- }
196
-
197
- /** Best-effort read of the OS's actual "default browser" setting, mapped to one of LOCAL_BROWSERS'
198
- * `id`s - or null if it can't be determined (unsupported platform, unknown browser, command
199
- * missing/failed) or if the default is a non-Chromium browser (Firefox/Safari - no CDP support, so
200
- * there's nothing to tunnel into). Never throws - this is a "nice to have" signal, `findLocalBrowser`
201
- * falls back to install-order when it's unavailable. */
202
- export function detectDefaultBrowserId() {
203
- try {
204
- if (process.platform === 'win32') {
205
- // The per-user UserChoice hash-protected key (what Settings > Default apps itself writes) is
206
- // awkward to read reliably across Windows versions and, confirmed while testing this, is often
207
- // just absent (no explicit override ever made). `Software\Classes\http\shell\open\command` is
208
- // what Windows actually resolves to at launch time regardless of how it got set - HKCU holds a
209
- // per-user override if one exists, HKLM is the system-wide fallback otherwise. Reading the
210
- // command line's exe name directly sidesteps needing to decode a ProgId at all.
211
- const readCommand = (hive) => {
212
- try {
213
- return execSync(`reg query "${hive}\\Software\\Classes\\http\\shell\\open\\command"`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
214
- } catch {
215
- return '';
216
- }
217
- };
218
- const out = readCommand('HKCU') || readCommand('HKLM');
219
- if (/msedge\.exe/i.test(out)) return 'edge';
220
- if (/chrome\.exe/i.test(out)) return 'chrome';
221
- return null; // Firefox, or something unrecognized
222
- }
223
- if (process.platform === 'darwin') {
224
- // No single stock CLI for this on macOS - LaunchServices' own plist is the source of truth
225
- // Settings > Desktop & Dock reads from, `plutil` (stock, ships with macOS) can dump it as JSON.
226
- const plistPath = path.join(
227
- os.homedir(), 'Library', 'Preferences', 'com.apple.LaunchServices',
228
- 'com.apple.launchservices.secure.plist',
229
- );
230
- if (!fs.existsSync(plistPath)) return null;
231
- const json = execSync(`plutil -convert json -o - "${plistPath}"`, { encoding: 'utf8' });
232
- const handlers = JSON.parse(json)?.LSHandlers || [];
233
- const httpHandler = handlers.find((h) => h.LSHandlerURLScheme === 'http');
234
- const bundleId = String(httpHandler?.LSHandlerRoleAll || '').toLowerCase();
235
- if (bundleId.includes('edge')) return 'edge';
236
- if (bundleId.includes('chrome')) return 'chrome';
237
- return null; // Safari, Firefox, or undetermined
238
- }
239
- // Linux: xdg-settings is the freedesktop.org standard way, present on most desktop distros.
240
- const out = execSync('xdg-settings get default-web-browser', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
241
- if (/edge/i.test(out)) return 'edge';
242
- if (/chrome/i.test(out)) return 'chrome';
243
- return null;
244
- } catch {
245
- return null; // command missing, key absent, parse failure - all fine to just not know
246
- }
247
- }
248
-
249
- /**
250
- * Picks which installed browser to drive, in priority order:
251
- * 1. `preferredId` (from `--browser edge|chrome`) - explicit always wins, errors clearly if that
252
- * browser isn't actually installed rather than silently falling through to another one.
253
- * 2. The OS's actual default browser, IF it's Chromium-based and installed - this is what makes
254
- * "drives your own logged-in browser" true; guessing wrong here would tunnel into a browser
255
- * profile the user doesn't actually use, with none of the cookies/logins they expect.
256
- * 3. Whatever's installed from LOCAL_BROWSERS, in list order - last resort when the real default
257
- * couldn't be determined or isn't Chromium (Firefox/Safari have no CDP to tunnel into).
258
- * Always logs which one it picked and why when there was more than one candidate, so step 3 in
259
- * particular is never a silent surprise.
260
- */
261
- export function findLocalBrowser(preferredId) {
262
- const installed = LOCAL_BROWSERS.map(resolveBrowserInstall).filter(Boolean);
263
- if (installed.length === 0) return null;
264
-
265
- if (preferredId) {
266
- const match = installed.find((b) => b.id === preferredId);
267
- if (match) return match;
268
- 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'}.`);
269
- }
270
-
271
- if (installed.length > 1) {
272
- const defaultId = detectDefaultBrowserId();
273
- const byDefault = defaultId && installed.find((b) => b.id === defaultId);
274
- if (byDefault) return byDefault;
275
- console.log(chalk.gray(
276
- ` (multiple browsers installed (${installed.map((b) => b.name).join(', ')}) and couldn't confirm your OS default - ` +
277
- `using ${installed[0].name}. Pass --browser ${installed.map((b) => b.id).join('|')} to pick.)`,
278
- ));
279
- }
280
-
281
- return installed[0];
282
- }
283
-
284
- export function launchCommandHint(browser, port = CHROME_DEBUG_PORT) {
285
- const label = browser ? browser.name : 'Chrome or Edge';
286
- const exe = browser ? `"${browser.exe}"` : '<your browser>';
287
- if (process.platform === 'win32') return `& ${exe} --remote-debugging-port=${port} (${label})`;
288
- if (process.platform === 'darwin') return `open -a "${label}" --args --remote-debugging-port=${port}`;
289
- return `${browser ? browser.exe : 'google-chrome'} --remote-debugging-port=${port}`;
290
- }
291
-
292
- export function printChromeLaunchHelp(port = CHROME_DEBUG_PORT, preferredId) {
293
- const browser = findLocalBrowser(preferredId);
294
- console.log(chalk.yellow('\n⚠️ Could not start a local browser for AI Browser.'));
295
- console.log(` ${chalk.cyan(launchCommandHint(browser, port))}\n`);
296
- console.log(chalk.gray(' ...or pass --remote for a server-side browser instead (no local browser needed).'));
297
- }
298
-
299
- /** Launches a browser window dedicated to `aivin browser`, on ITS OWN profile
300
- * (AIVIN_BROWSER_PROFILE_DIR) - never the user's real daily-driver one. This is what makes local
301
- * mode zero-friction after the first run: because it's a separate profile, it never collides with
302
- * whatever the user's main browser is already doing (no "close all your windows first"), and once
303
- * running it just stays up - a later mission finds it already listening and reuses it, opening a
304
- * new tab in the SAME window rather than launching anything again. The one real cost: the first
305
- * time any given site is used (Facebook, etc.), the user logs in once here, same as any fresh
306
- * profile - after that it persists exactly like their main browser's cookies do. */
307
- export async function launchLocalChromeWithDebugging(port = CHROME_DEBUG_PORT, preferredId) {
308
- const browser = findLocalBrowser(preferredId);
309
- if (!browser) {
310
- throw new Error(`Could not find a local Chrome/Edge install automatically - relaunch one manually with: ${launchCommandHint(null, port)}`);
311
- }
312
- const firstRun = !fs.existsSync(AIVIN_BROWSER_PROFILE_DIR);
313
- fs.mkdirSync(AIVIN_BROWSER_PROFILE_DIR, { recursive: true });
314
- // No pre-flight SingletonLock check here on purpose (an earlier version of this had one, copied
315
- // from the old "don't touch the user's real profile" logic where it made sense): by the time we
316
- // get here, probeLocalChromeDebugger() has ALREADY confirmed nothing is answering on `port`, so a
317
- // present lock file can only be stale (left behind by an unclean shutdown/crash) - Chromium itself
318
- // already detects and clears stale locks on startup (checks whether the owning PID is still
319
- // alive), more reliably than re-implementing that check here. A pre-check could only ever produce
320
- // a false positive: a confusing "already open, go close it" error pointing at a window that isn't
321
- // actually running anywhere.
322
- if (firstRun) {
323
- console.log(chalk.gray(` First run: opening a NEW, separate ${browser.name} window just for AI Browser (your regular ${browser.name} is untouched).`));
324
- console.log(chalk.gray(` 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.`));
325
- } else {
326
- console.log(chalk.gray(` Opening your dedicated AI Browser window...`));
327
- }
328
- const child = spawn(browser.exe, [`--remote-debugging-port=${port}`, `--user-data-dir=${AIVIN_BROWSER_PROFILE_DIR}`, '--no-first-run', '--start-maximized'], { detached: true, stdio: 'ignore' });
329
- child.unref();
330
- for (let i = 0; i < 20; i++) {
331
- await new Promise((resolve) => setTimeout(resolve, 500));
332
- const { wsUrl, conflict } = await probeLocalChromeDebugger(port);
333
- if (wsUrl) return wsUrl;
334
- if (conflict) {
335
- throw new Error(
336
- `Port ${port} is already in use by something else (reported itself as "${conflict}", not Chrome/Edge) - ` +
337
- `${browser.name} can't bind its debug port there. Free that port, or rerun with --debug-port <other-port>.`,
338
- );
339
- }
340
- }
341
- throw new Error(`${browser.name} launched but its debug port never came up in time.`);
342
- }
343
-
344
- /**
345
- * Opens 2 raw WebSocket connections - one to the backend's relay (authenticated by API key), one
346
- * to the user's own local Chrome's real CDP endpoint - and pipes frames both directions verbatim.
347
- * `close()` disconnects both sides; the user's actual browser window is never touched beyond this
348
- * one CDP connection, closing the tunnel just detaches Puppeteer server-side.
349
- *
350
- * `onUnexpectedClose(side)` fires when either leg drops WITHOUT `close()` having been called first
351
- * (side is 'backend' or 'chrome') - lets the caller distinguish "network/tunnel died mid-mission"
352
- * from "we're done, tearing down deliberately" (Ctrl+C, mission finished) without guessing from
353
- * timing alone. Never fires after a deliberate `close()`.
354
- */
355
- export function openLocalTunnel(serverUrl, apiKey, chromeWsUrl, { onUnexpectedClose } = {}) {
356
- const tunnelId = randomUUID();
357
- const relayUrl = `${serverUrl.replace(/^http/, 'ws')}/browser-tunnel/external?tunnel_id=${tunnelId}`;
358
-
359
- // API key goes in a header, NOT a `?token=` query param - WS upgrade URLs are exactly the kind
360
- // of thing that ends up verbatim in reverse-proxy/CDN/access logs, unlike headers.
361
- const toBackend = new WSClient(relayUrl, { headers: { Authorization: `Bearer ${apiKey || ''}` } });
362
- const toChrome = new WSClient(chromeWsUrl);
363
-
364
- let deliberateClose = false;
365
-
366
- const relay = (from, to, side) => {
367
- from.on('message', (data, isBinary) => {
368
- if (to.readyState === WSClient.OPEN) to.send(data, { binary: isBinary });
369
- });
370
- from.on('close', () => {
371
- if (to.readyState === WSClient.OPEN) to.close();
372
- if (!deliberateClose) onUnexpectedClose?.(side);
373
- });
374
- from.on('error', () => {
375
- if (to.readyState === WSClient.OPEN) to.close();
376
- if (!deliberateClose) onUnexpectedClose?.(side);
377
- });
378
- };
379
- relay(toBackend, toChrome, 'backend');
380
- relay(toChrome, toBackend, 'chrome');
381
-
382
- const ready = Promise.all([
383
- new Promise((resolve, reject) => {
384
- toBackend.once('open', resolve);
385
- toBackend.once('error', reject);
386
- }),
387
- new Promise((resolve, reject) => {
388
- toChrome.once('open', resolve);
389
- toChrome.once('error', reject);
390
- }),
391
- ]);
392
-
393
- const close = () => {
394
- deliberateClose = true;
395
- try { toBackend.close(); } catch { /* already closed */ }
396
- try { toChrome.close(); } catch { /* already closed */ }
397
- };
398
-
399
- return { tunnelId, ready, close };
400
- }
401
-
402
- export async function runBrowserMissionLocal(mission, options) {
403
- const serverUrl = missionServerUrl();
404
- const apiKey = process.env.API_KEY;
405
- const authHeaders = missionAuthHeaders();
406
- const tenantClient = parseApiKeyClient(apiKey || '') || 'unknown';
407
-
408
- const preferredId = options.browser ? String(options.browser).toLowerCase() : undefined;
409
- if (preferredId && preferredId !== 'edge' && preferredId !== 'chrome') {
410
- throw new Error(`--browser must be "edge" or "chrome", got "${options.browser}".`);
411
- }
412
-
413
- // --debug-port pins an exact port (strict - errors immediately if it's taken by something else).
414
- // Without it, try the conventional 9222 first, then a few neighbors - confirmed needed for real:
415
- // this project's OWN local dev stack publishes an unrelated container on 9222 (see
416
- // probeLocalChromeDebugger's comment), so erroring out on the very first conflict there would make
417
- // `aivin browser` unusable out of the box for anyone running that stack, every single time.
418
- const explicitPort = options.debugPort !== undefined;
419
- const candidatePorts = explicitPort ? [Number(options.debugPort)] : [CHROME_DEBUG_PORT, 9223, 9224, 9225];
420
-
421
- let debugPort;
422
- let chromeWsUrl;
423
- const triedConflicts = [];
424
- for (const port of candidatePorts) {
425
- const probed = await probeLocalChromeDebugger(port);
426
- if (probed.wsUrl && preferredId && probed.browserId !== preferredId) {
427
- // Something's already listening, but it's the OTHER browser than what --browser asked for -
428
- // using it silently would drive the wrong profile (wrong cookies/logins), so this has to be a
429
- // hard error rather than a best-effort fallback, even mid auto-retry.
430
- throw new Error(
431
- `--browser ${preferredId} was requested, but the browser already listening on port ${port} is ${probed.browserId} instead. ` +
432
- `Close it and relaunch ${preferredId} with --remote-debugging-port=${port}, or use --debug-port to point at a different port.`,
433
- );
434
- }
435
- if (probed.wsUrl) { debugPort = port; chromeWsUrl = probed.wsUrl; break; }
436
- if (probed.conflict) { triedConflicts.push(`${port} (${probed.conflict})`); continue; }
437
- debugPort = port; // free port, nothing answering at all - safe to launch here
438
- break;
439
- }
440
- if (debugPort === undefined) {
441
- throw new Error(
442
- `${explicitPort ? 'Requested' : 'All of the usual'} debug port${candidatePorts.length > 1 ? 's are' : ' is'} already in use by something else, not Chrome/Edge: ${triedConflicts.join(', ')}. ` +
443
- `Free one of them, or pass --debug-port <port> to use a specific one.`,
444
- );
445
- }
446
-
447
- if (!chromeWsUrl) {
448
- // Safe to always auto-launch now (unlike an earlier version of this): this opens AIVIN_BROWSER_
449
- // PROFILE_DIR, a profile dedicated to `aivin browser` that's never the user's real daily-driver
450
- // browser, so there's no risk of colliding with (or having to close) whatever they're already
451
- // running elsewhere.
452
- try {
453
- chromeWsUrl = await launchLocalChromeWithDebugging(debugPort, preferredId);
454
- } catch (error) {
455
- printChromeLaunchHelp(debugPort, preferredId);
456
- throw error;
457
- }
458
- }
459
-
460
- const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
461
- const agentId = options.agent || (await resolveOrCreateBrowserAgent(serverUrl, authHeaders, workspace));
462
-
463
- console.log(chalk.blue('🌐 AI Browser (local - your own browser):'), mission);
464
- console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
465
-
466
- // Retry the local tunnel on an UNEXPECTED drop (flaky WiFi) - checkpoint-resume already exists
467
- // server-side (AIBrowserCheckpointService, matches on tenant + exact mission text), so re-firing
468
- // the SAME mission through a fresh tunnel just continues where it left off instead of restarting.
469
- // Only worth doing when we're actually watching (options.watch !== false) - without the log
470
- // stream there's no reliable signal for "did the mission already finish" vs "tunnel just dropped",
471
- // so a single un-retried attempt (old behavior) is what happens when watch is disabled.
472
- const MAX_TUNNEL_RETRIES = 3;
473
- let interrupted = false;
474
- let terminalReason; // 'success' | 'failed' | undefined (still unresolved / gave up watching)
475
- let attempt = 0;
476
-
477
- while (!interrupted) {
478
- attempt++;
479
- if (attempt > 1) {
480
- // Chrome's CDP websocket URL can go stale after a drop, and the browser itself may have
481
- // closed too (user closed the window) - re-probe rather than blindly reusing the old URL.
482
- const reprobe = await probeLocalChromeDebugger(debugPort);
483
- if (!reprobe.wsUrl) {
484
- console.log(chalk.red(`\n❌ Mất kết nối và không tìm lại được ${preferredId || 'Chrome/Edge'} đang chạy ở cổng ${debugPort} - trình duyệt có thể đã bị đóng. Dừng lại đây (mission có thể vẫn đang chạy trên server - kiểm tra lại bằng \`aivin browser --view\` hoặc chạy lại lệnh này).`));
485
- break;
486
- }
487
- chromeWsUrl = reprobe.wsUrl;
488
- console.log(chalk.yellow(`\n🔄 Tunnel bị rớt kết nối bất ngờ - đang thử lại (lần ${attempt - 1}/${MAX_TUNNEL_RETRIES})...`));
489
- }
490
-
491
- let unexpectedDrop = false;
492
- const tunnel = openLocalTunnel(serverUrl, apiKey, chromeWsUrl, {
493
- onUnexpectedClose: () => { unexpectedDrop = true; },
494
- });
495
- try {
496
- await tunnel.ready;
497
- } catch (error) {
498
- tunnel.close();
499
- if (attempt > MAX_TUNNEL_RETRIES) throw new Error(`Could not open the local browser tunnel: ${error.message}`, { cause: error });
500
- console.log(chalk.yellow(`\n⚠️ Không mở được tunnel (${error.message}) - đang thử lại (lần ${attempt}/${MAX_TUNNEL_RETRIES})...`));
501
- continue;
502
- }
503
-
504
- const sessionId = `browser-cli-${randomUUID()}`;
505
- console.log(chalk.gray(` Session: ${sessionId}`));
506
-
507
- // Ctrl+C: request cooperative cancellation (same mechanism sdk.browser.cancel() uses - checked
508
- // between agentic-loop steps, can't interrupt a step already in flight) AND close the tunnel.
509
- // Closing the tunnel alone isn't enough to stop a mission stuck in an LLM call that hasn't
510
- // touched the browser connection yet (confirmed while testing this) - the cancel request is what
511
- // actually gets it to stop at its next chance to check. The tab this mission was using stays open
512
- // either way - never force-closed, since local mode is explicitly "your own browser, your tabs".
513
- const onSigint = () => {
514
- if (interrupted) return;
515
- interrupted = true;
516
- console.log(chalk.yellow('\n\n⏹ Stopping... (requesting cancellation - may take a moment, one agentic step at a time)'));
517
- requestBrowserCancel(serverUrl, authHeaders, { sessionId }).catch((e) =>
518
- console.log(chalk.red(` ⚠️ Cancellation request failed to send (${e.message}) - the mission may keep running.`)),
519
- );
520
- tunnel.close();
521
- console.log(chalk.gray(' The tab this mission was using is still open in your browser - close it yourself if you don\'t need it.'));
522
- };
523
- process.on('SIGINT', onSigint);
524
-
525
- // Fired concurrently, not sequentially - execute-interactive is a SYNCHRONOUS call (blocks until
526
- // the mission ends), so the log watcher has to already be listening before/as it fires, not after.
527
- const missionPromise = axios.post(
528
- // `/plugins/` prefix: OfficialPluginModules.ts registers every official plugin module (incl.
529
- // AIBrowserModule) via RouterModule.register({ path: 'plugins', ... }) - easy to miss, confirmed
530
- // by testing directly against the API (plain /ai-browser/... 404s, /plugins/ai-browser/... works).
531
- `${serverUrl}/plugins/ai-browser/execute-interactive`,
532
- {
533
- mission,
534
- workspace_id: workspace.id || workspace._id,
535
- agent_id: agentId,
536
- session_id: sessionId,
537
- data: { __local_tunnel_id: tunnel.tunnelId, start_url: options.url || guessStartUrl(mission) },
538
- },
539
- authHeaders,
540
- );
541
- const watchPromise = options.watch !== false
542
- ? watchBrowserMission(serverUrl, apiKey, sessionId, tenantClient, { openViewerOnHIL: false, sessionId })
543
- : Promise.resolve(undefined);
544
-
545
- try {
546
- // execute-interactive responds immediately (fire-and-forget - see AIBrowserController.ts's
547
- // comment on why: a synchronous wait here would hit the same Cloudflare 524 the gRPC
548
- // browser.run() call did). The REAL outcome is whatever the log stream above already printed
549
- // (ai_browser.success/failed) - this Promise.all is just making sure both sides are done.
550
- const [, watchReason] = await Promise.all([missionPromise, watchPromise]);
551
- terminalReason = watchReason;
552
- } catch (error) {
553
- if (!interrupted) {
554
- const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
555
- throw new Error(`AI Browser mission failed to start: ${message}`, { cause: error });
556
- }
557
- } finally {
558
- process.off('SIGINT', onSigint);
559
- tunnel.close();
560
- }
561
-
562
- if (interrupted) break;
563
- if (terminalReason === 'success' || terminalReason === 'failed') break; // genuine mission outcome - done
564
- // options.watch === false (no signal at all) or watch gave up on its own (idle/connect_error,
565
- // NOT a tunnel drop) - neither is worth blindly retrying; only retry on a confirmed tunnel drop.
566
- if (!unexpectedDrop) break;
567
- if (attempt > MAX_TUNNEL_RETRIES) {
568
- console.log(chalk.red(`\n❌ Đã thử lại ${MAX_TUNNEL_RETRIES} lần nhưng tunnel vẫn liên tục rớt kết nối - dừng theo dõi. Mission có thể vẫn đang chạy trên server.`));
569
- break;
570
- }
571
- }
572
-
573
- if (!interrupted && (terminalReason === 'success' || terminalReason === 'failed')) {
574
- console.log(chalk.gray('\n Done - see the log lines above for the outcome, and your own browser for the result.'));
575
- }
576
- }
126
+ /** English wording for the shared tunnel's status events - its own `say` text is Vietnamese, written for
127
+ * `aivin remote`'s daemon log. */
128
+ function sayTunnelEvent(_text, event = {}) {
129
+ switch (event.type) {
130
+ case 'consent':
131
+ console.log(chalk.yellow(` 🔐 ${event.browser} is asking whether Aivin may use it - click "Allow" in ${event.browser}.`));
132
+ break;
133
+ case 'daily-declined':
134
+ console.log(chalk.gray(` ↩️ ${event.browser} didn't allow the connection (${event.reason}) - using the separate Aivin window instead.`));
135
+ break;
136
+ case 'using':
137
+ console.log(chalk.gray(event.daily
138
+ ? ` Using your everyday ${event.browser} - new tabs open in the background, your own tabs stay read-only to the AI.`
139
+ : ` Using the Aivin browser window${event.browser ? ` (${event.browser})` : ''}.`));
140
+ break;
141
+ case 'blocked':
142
+ console.log(chalk.gray(` 🛡️ Blocked ${event.method} on your ${event.browser} - ${event.reason}`));
143
+ break;
144
+ case 'groups-unavailable':
145
+ console.log(chalk.gray(' (Tab grouping is off for this window - close the Aivin browser window and rerun to turn it on.)'));
146
+ break;
147
+ default:
148
+ break; // 'released' - nothing worth printing for a one-shot command
149
+ }
150
+ }
151
+
152
+ export async function runBrowserMissionLocal(mission, options) {
153
+ const serverUrl = missionServerUrl();
154
+ const apiKey = process.env.API_KEY;
155
+ const authHeaders = missionAuthHeaders();
156
+ const tenantClient = parseApiKeyClient(apiKey || '') || 'unknown';
157
+
158
+ const preferredId = options.browser ? String(options.browser).toLowerCase() : undefined;
159
+ if (preferredId && !LOCAL_BROWSER_IDS.includes(preferredId)) {
160
+ throw new Error(`--browser must be one of ${LOCAL_BROWSER_IDS.join(', ')}, got "${options.browser}".`);
161
+ }
162
+ if (options.url && isBlockedUrl(options.url)) {
163
+ throw new Error(`--url must be a web page - ${String(options.url).split(':')[0]}: URLs can't be opened by AI Browser.`);
164
+ }
165
+
166
+ // --debug-port pins an exact port (strict - errors if it's taken by something else). Without it,
167
+ // try the conventional 9222 first, then a few neighbors - confirmed needed for real: this
168
+ // project's OWN local dev stack publishes an unrelated container on 9222 (see
169
+ // probeLocalChromeDebugger's comment). Only used when the Aivin window has to be launched - an
170
+ // already-running one is found through its profile folder, whatever port it's on.
171
+ const explicitPort = options.debugPort !== undefined;
172
+ const ports = explicitPort ? [Number(options.debugPort)] : DEBUG_PORTS;
173
+ if (explicitPort && !(Number.isInteger(ports[0]) && ports[0] > 0 && ports[0] < 65536)) {
174
+ throw new Error(`--debug-port must be a port number, got "${options.debugPort}".`);
175
+ }
176
+
177
+ const browser = findLocalBrowser(preferredId);
178
+ if (!browser) {
179
+ printChromeLaunchHelp(ports[0], preferredId);
180
+ throw new Error('No Chrome, Edge, Brave or Chromium install found on this computer.');
181
+ }
182
+
183
+ // Only ever the window running on the dedicated Aivin profile - never "whatever Chromium answers on
184
+ // the port" (see the header comment). The user's everyday browser is reached separately, only after
185
+ // they've switched on remote debugging in it themselves (dailyBrowser.mjs, consent-gated).
186
+ let launchAllowed = true;
187
+ const ensureBrowser = async () => {
188
+ let found;
189
+ try {
190
+ found = await ensureAivinBrowser(preferredId || browser.id, { ports, launch: launchAllowed, log: (m) => console.log(chalk.gray(m)) });
191
+ } catch (error) {
192
+ if (launchAllowed) printChromeLaunchHelp(ports[0], preferredId);
193
+ error.browserSetup = true;
194
+ throw error;
195
+ }
196
+ // Brave/Chromium report themselves as Chrome over CDP - only Edge vs. the rest is tellable here.
197
+ const family = (id) => (id === 'edge' ? 'edge' : 'chromium');
198
+ if (preferredId && found.browserId && family(found.browserId) !== family(preferredId)) {
199
+ const error = new Error(
200
+ `--browser ${preferredId} was requested, but the Aivin browser window that's already open is ${found.browserId}. ` +
201
+ 'Close that window and rerun, or drop --browser.',
202
+ );
203
+ error.browserSetup = true;
204
+ throw error;
205
+ }
206
+ return found;
207
+ };
208
+
209
+ const tunnels = createBrowserTunnels({
210
+ serverUrl,
211
+ authorization: `Bearer ${apiKey || ''}`,
212
+ browser: { id: browser.id, name: browser.name },
213
+ useDailyBrowser: options.separateBrowser !== true,
214
+ ensureBrowser,
215
+ say: sayTunnelEvent,
216
+ });
217
+
218
+ try {
219
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
220
+ const agentId = options.agent || (await resolveOrCreateBrowserAgent(serverUrl, authHeaders, workspace));
221
+
222
+ console.log(chalk.blue('🌐 AI Browser (local - your own browser):'), mission);
223
+ console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
224
+
225
+ // Retry the local tunnel on an UNEXPECTED drop (flaky WiFi) - checkpoint-resume already exists
226
+ // server-side (AIBrowserCheckpointService, matches on tenant + exact mission text), so re-firing
227
+ // the SAME mission through a fresh tunnel just continues where it left off instead of restarting.
228
+ // Only worth doing when we're actually watching (options.watch !== false) - without the log
229
+ // stream there's no reliable signal for "did the mission already finish" vs "tunnel just dropped",
230
+ // so a single un-retried attempt is what happens when watch is disabled.
231
+ const MAX_TUNNEL_RETRIES = 3;
232
+ let interrupted = false;
233
+ let terminalReason; // 'success' | 'failed' | undefined (still unresolved / gave up watching)
234
+ let attempt = 0;
235
+
236
+ while (!interrupted) {
237
+ attempt++;
238
+ if (attempt > 1) {
239
+ // A closed window mid-mission is the user's call - reconnect to it if it's still there, but
240
+ // never pop a fresh one open on a retry.
241
+ launchAllowed = false;
242
+ console.log(chalk.yellow(`\n🔄 The browser tunnel dropped unexpectedly - retrying (${attempt - 1}/${MAX_TUNNEL_RETRIES})...`));
243
+ }
244
+
245
+ const tunnelId = randomUUID();
246
+ let unexpectedDrop = false;
247
+ try {
248
+ await tunnels.open({ tunnel_id: tunnelId, label: mission }, { onClose: ({ deliberate }) => { if (!deliberate) unexpectedDrop = true; } });
249
+ } catch (error) {
250
+ if (error.browserSetup && attempt > 1) {
251
+ console.log(chalk.red(
252
+ '\n❌ Lost the connection and the browser is gone - it may have been closed. Stopping here (the mission may still be running on the server - ' +
253
+ 'check with `aivin browser --view`, or rerun this command).',
254
+ ));
255
+ break;
256
+ }
257
+ if (error.browserSetup || attempt > MAX_TUNNEL_RETRIES) throw new Error(`Could not open the local browser tunnel: ${error.message}`, { cause: error });
258
+ console.log(chalk.yellow(`\n⚠️ Couldn't open the browser tunnel (${error.message}) - retrying (${attempt}/${MAX_TUNNEL_RETRIES})...`));
259
+ continue;
260
+ }
261
+
262
+ const sessionId = `browser-cli-${randomUUID()}`;
263
+ console.log(chalk.gray(` Session: ${sessionId}`));
264
+
265
+ // Ctrl+C: request cooperative cancellation (same mechanism sdk.browser.cancel() uses - checked
266
+ // between agentic-loop steps, can't interrupt a step already in flight) AND close the tunnel.
267
+ // Closing the tunnel alone isn't enough to stop a mission stuck in an LLM call that hasn't
268
+ // touched the browser connection yet (confirmed while testing this) - the cancel request is what
269
+ // actually gets it to stop at its next chance to check. The tab this mission was using stays open
270
+ // either way - never force-closed, since local mode is explicitly "your own browser, your tabs".
271
+ const onSigint = () => {
272
+ if (interrupted) return;
273
+ interrupted = true;
274
+ console.log(chalk.yellow('\n\n⏹ Stopping... (requesting cancellation - may take a moment, one agentic step at a time)'));
275
+ requestBrowserCancel(serverUrl, authHeaders, { sessionId }).catch((e) =>
276
+ console.log(chalk.red(` ⚠️ Cancellation request failed to send (${e.message}) - the mission may keep running.`)),
277
+ );
278
+ tunnels.close(tunnelId);
279
+ console.log(chalk.gray(' The tab this mission was using is still open in your browser - close it yourself if you don\'t need it.'));
280
+ };
281
+ process.on('SIGINT', onSigint);
282
+
283
+ // Fired concurrently, not sequentially - the log watcher has to already be listening before/as
284
+ // the mission starts, not after.
285
+ const missionPromise = axios.post(
286
+ // `/plugins/` prefix: OfficialPluginModules.ts registers every official plugin module (incl.
287
+ // AIBrowserModule) via RouterModule.register({ path: 'plugins', ... }) - easy to miss, confirmed
288
+ // by testing directly against the API (plain /ai-browser/... 404s, /plugins/ai-browser/... works).
289
+ `${serverUrl}/plugins/ai-browser/execute-interactive`,
290
+ {
291
+ mission,
292
+ workspace_id: workspace.id || workspace._id,
293
+ agent_id: agentId,
294
+ session_id: sessionId,
295
+ data: { __local_tunnel_id: tunnelId, start_url: options.url || guessStartUrl(mission) },
296
+ },
297
+ authHeaders,
298
+ );
299
+ const watchPromise = options.watch !== false
300
+ ? watchBrowserMission(serverUrl, apiKey, sessionId, tenantClient, { openViewerOnHIL: false, sessionId })
301
+ : Promise.resolve(undefined);
302
+
303
+ try {
304
+ // execute-interactive responds immediately (fire-and-forget - see AIBrowserController.ts's
305
+ // comment on why: a synchronous wait here would hit the same Cloudflare 524 the gRPC
306
+ // browser.run() call did). The REAL outcome is whatever the log stream above already printed
307
+ // (ai_browser.success/failed) - this Promise.all is just making sure both sides are done.
308
+ const [, watchReason] = await Promise.all([missionPromise, watchPromise]);
309
+ terminalReason = watchReason;
310
+ } catch (error) {
311
+ if (!interrupted) {
312
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
313
+ throw new Error(`AI Browser mission failed to start: ${message}`, { cause: error });
314
+ }
315
+ } finally {
316
+ process.off('SIGINT', onSigint);
317
+ tunnels.close(tunnelId);
318
+ }
319
+
320
+ if (interrupted) break;
321
+ if (terminalReason === 'success' || terminalReason === 'failed') break; // genuine mission outcome - done
322
+ // options.watch === false (no signal at all) or watch gave up on its own (idle/connect_error,
323
+ // NOT a tunnel drop) - neither is worth blindly retrying; only retry on a confirmed tunnel drop.
324
+ if (!unexpectedDrop) break;
325
+ if (attempt > MAX_TUNNEL_RETRIES) {
326
+ console.log(chalk.red(`\n❌ Retried ${MAX_TUNNEL_RETRIES} times but the tunnel keeps dropping - stopped watching. The mission may still be running on the server.`));
327
+ break;
328
+ }
329
+ }
330
+
331
+ if (!interrupted && (terminalReason === 'success' || terminalReason === 'failed')) {
332
+ console.log(chalk.gray('\n Done - see the log lines above for the outcome, and your own browser for the result.'));
333
+ }
334
+ } finally {
335
+ // Also drops the shared daily-browser connection and the tab-grouping one - both would otherwise
336
+ // keep the process alive after the mission is over.
337
+ tunnels.closeAll();
338
+ }
339
+ }
577
340
 
578
341
  /** REST twin of `sdk.browser.cancel()` - the CLI has no gRPC client, only axios. See
579
342
  * AIBrowserController.cancel's comment for the exact semantics (cooperative, own-tenant-only). */