@aivin-labs/cli 1.0.0

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.
@@ -0,0 +1,575 @@
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
+ import { randomUUID } from 'crypto';
8
+ import WSClient from 'ws';
9
+ import { missionServerUrl, missionAuthHeaders, resolveWorkspace, resolveAgentInteractive, createAgent, pullAgentIntoWorkspace } from './workspace.mjs';
10
+ import { parseApiKeyClient } from './auth.mjs';
11
+ import { guessStartUrl, streamBrowserMissionLog, BROWSER_MISSION_PREFIX } from './missionStream.mjs';
12
+
13
+ // ── `aivin browser` default mode: drive the user's OWN local, already-running browser ──────────
14
+ //
15
+ // Real cookies/logins, real fingerprint - much better bot-detection resistance than the server-
16
+ // side pooled browser `--remote` uses. Architecture: a raw WebSocket relay on the backend
17
+ // (BrowserTunnelRelay) pairs this CLI's connection to the user's local Chrome CDP endpoint with
18
+ // AIBrowserService's own `BrowserIO.connect(...)` call server-side - the EXISTING agentic loop
19
+ // (causality, bot-guard, semantic matching, HIL) drives that real browser unmodified, this file
20
+ // only ever pipes opaque frames, never inspects them.
21
+
22
+ export const BROWSER_CLI_AGENT_CACHE_PATH = path.join(os.homedir(), '.aivin', 'browser-cli-agents.json');
23
+
24
+ // A separate Chrome/Edge profile dedicated to `aivin browser`, NOT the user's real daily-driver
25
+ // profile. Reasoning (confirmed the hard way): `--remote-debugging-port` can only be set at process
26
+ // launch, never toggled on an already-running instance, AND Chromium's single-instance-per-profile
27
+ // lock means launching a second process against the SAME profile the user is already using just
28
+ // silently forwards to the existing (non-debuggable) instance instead of actually starting a new,
29
+ // debuggable one - so reusing the daily-driver profile meant demanding the user close every window
30
+ // first, every single time. A dedicated profile sidesteps all of that: it can launch/stay running
31
+ // fully independently of whatever the user's main browser is doing, at the cost of a one-time login
32
+ // (Facebook etc.) the first time it's used - after that, cookies persist here just like any profile.
33
+ export const AIVIN_BROWSER_PROFILE_DIR = path.join(os.homedir(), '.aivin', 'browser-profile');
34
+
35
+ // 9222 is Chrome/Edge's conventional remote-debugging port, but it's not reserved to them - anything
36
+ // can be listening there (found the hard way: this project's own local docker-compose stack publishes
37
+ // its headless Lightpanda container on host port 9222 too, for the unrelated `--remote` server-side
38
+ // browser pool). `probeLocalChromeDebugger` below verifies the `Browser` field before trusting a hit
39
+ // here, and `--debug-port` lets a real conflict just be sidestepped instead of fought.
40
+ export const CHROME_DEBUG_PORT = 9222;
41
+
42
+ export function loadBrowserCliAgentCache() {
43
+ try {
44
+ return JSON.parse(fs.readFileSync(BROWSER_CLI_AGENT_CACHE_PATH, 'utf8'));
45
+ } catch {
46
+ return {};
47
+ }
48
+ }
49
+
50
+ export function saveBrowserCliAgentCache(cache) {
51
+ fs.mkdirSync(path.dirname(BROWSER_CLI_AGENT_CACHE_PATH), { recursive: true });
52
+ fs.writeFileSync(BROWSER_CLI_AGENT_CACHE_PATH, JSON.stringify(cache, null, 2) + '\n');
53
+ }
54
+
55
+ /**
56
+ * `aivin browser` shouldn't require the user to know/pick an "agent" - AI Browser is what actually
57
+ * does the work, the agent is just session/HIL identity plumbing the platform's data model requires
58
+ * underneath. Creates one dedicated agent per workspace the first time, with `official.ai_browser`
59
+ * already enabled, and caches its id so every later run is instant. Both API calls below (create,
60
+ * then a second update call with `plugins.plugin_ids`) were verified working directly against the
61
+ * API this session - `workspace_id` must be a query param on the update call (the DTO whitelists
62
+ * it out of the body), and name/nickname/email must be repeated even though only `plugins` changed.
63
+ */
64
+ export async function resolveOrCreateBrowserAgent(serverUrl, authHeaders, workspace) {
65
+ const workspaceId = workspace.id || workspace._id;
66
+ const cache = loadBrowserCliAgentCache();
67
+ const cachedId = cache[workspaceId];
68
+ if (cachedId && workspace.agents?.some((a) => (a.id || a.agent_id) === cachedId)) {
69
+ return cachedId;
70
+ }
71
+
72
+ console.log(chalk.gray(' (no cached browser agent for this workspace yet - creating one, one-time only)'));
73
+ const identity = {
74
+ name: 'AI Browser (CLI)',
75
+ nickname: 'aivin-browser-cli',
76
+ email: `aivin-browser-cli+${workspaceId}@local.invalid`,
77
+ };
78
+
79
+ // `/ai-staff/update` requires name/nickname/email again even though only `plugins` is actually
80
+ // changing (confirmed while testing) - default to the NEW agent's own identity, but when falling
81
+ // back to an EXISTING agent below, this must become THAT agent's real identity instead, or the
82
+ // update call would silently overwrite/rename someone's real agent with the CLI's placeholder
83
+ // name - a real, destructive bug caught in review before ever shipping.
84
+ let agentId;
85
+ let updateIdentity = identity;
86
+ try {
87
+ const created = await createAgent(serverUrl, authHeaders, {
88
+ ...identity,
89
+ bio: 'Auto-created by `aivin browser` - runs AI Browser missions triggered from the CLI.',
90
+ workspaceId,
91
+ });
92
+ agentId = created.id || created.agent_id;
93
+ await pullAgentIntoWorkspace(serverUrl, authHeaders, { agentId, workspaceId });
94
+ } catch (error) {
95
+ // Confirmed hitting this directly while testing: accounts on a plan with a low agent-count
96
+ // limit get a clear "limit reached" error here. Rather than dead-ending, fall back to reusing
97
+ // the workspace's own first existing agent (if any) - enabling official.ai_browser on it is a
98
+ // much better outcome than making the user go figure out --agent <id> themselves after a
99
+ // confusing failure.
100
+ const existing = workspace.agents?.[0];
101
+ if (!existing) throw error; // nothing to fall back to - surface the original error as-is
102
+ const message = error.response?.data?.message || error.message;
103
+ console.log(chalk.yellow(` ⚠️ Couldn't create a dedicated agent (${message}) - reusing "${existing.nickname || existing.name}" instead.`));
104
+ agentId = existing.id || existing.agent_id;
105
+ updateIdentity = { name: existing.name, nickname: existing.nickname, email: existing.email };
106
+ }
107
+
108
+ // Merge, don't replace - an existing agent (the fallback path above) may already have OTHER
109
+ // plugins enabled; sending plugin_ids: ['official.ai_browser'] alone would silently wipe those.
110
+ const existingPluginIds = workspace.agents?.find((a) => (a.id || a.agent_id) === agentId)?.plugins?.plugin_ids || [];
111
+ const mergedPluginIds = existingPluginIds.includes('official.ai_browser') ? existingPluginIds : [...existingPluginIds, 'official.ai_browser'];
112
+
113
+ await axios
114
+ .post(
115
+ `${serverUrl}/ai-staff/update?workspace_id=${encodeURIComponent(workspaceId)}`,
116
+ { id: agentId, ...updateIdentity, plugins: { plugin_ids: mergedPluginIds } },
117
+ authHeaders,
118
+ )
119
+ .catch((error) => {
120
+ const message = error.response?.data?.message || error.message;
121
+ console.log(chalk.yellow(` ⚠️ Could not enable official.ai_browser on the agent automatically: ${message}`));
122
+ });
123
+
124
+ cache[workspaceId] = agentId;
125
+ saveBrowserCliAgentCache(cache);
126
+ console.log(chalk.green(` ✅ Agent ready for AI Browser CLI use (cached for next time).`));
127
+ return agentId;
128
+ }
129
+
130
+ /** Chrome's own remote-debugging discovery endpoint - reachable only if the user already relaunched
131
+ * Chrome with `--remote-debugging-port`. Returns the CDP WebSocket URL for the whole browser, or
132
+ * null if nothing's listening there (or something else entirely is - see below). */
133
+ export async function probeLocalChromeDebugger(port = CHROME_DEBUG_PORT) {
134
+ try {
135
+ const res = await axios.get(`http://127.0.0.1:${port}/json/version`, { timeout: 2000 });
136
+ // Something answered - but NOT necessarily Chrome/Edge. Confirmed hitting this for real: this
137
+ // port is also where this project's own local dev stack publishes a headless Lightpanda
138
+ // container (no UI at all), which happily speaks CDP and would otherwise look identical to a
139
+ // real browser here - "mission ran but no window ever appeared" was the resulting symptom.
140
+ // Real Chrome/Edge both report a `Browser` field like "Chrome/123.0..." / "Edg/123.0...".
141
+ const product = String(res.data?.Browser || '');
142
+ if (!/^(Chrome|Edg)\//.test(product)) {
143
+ return { wsUrl: null, conflict: product || 'unknown service', browserId: null };
144
+ }
145
+ const browserId = /^Edg\//.test(product) ? 'edge' : 'chrome';
146
+ return { wsUrl: res.data?.webSocketDebuggerUrl || null, conflict: null, browserId };
147
+ } catch {
148
+ return { wsUrl: null, conflict: null, browserId: null };
149
+ }
150
+ }
151
+
152
+ // Any Chromium-based browser works identically here (same --remote-debugging-port / CDP protocol).
153
+ // Order here is only a last-resort tiebreaker (see findLocalBrowser) - actual selection prefers the
154
+ // user's real OS default browser via detectDefaultBrowserId(), or an explicit --browser flag.
155
+ export const LOCAL_BROWSERS = [
156
+ {
157
+ id: 'edge',
158
+ name: 'Microsoft Edge',
159
+ win32: ['C:\\Program Files (x86)\\Microsoft\\Edge\\Application\\msedge.exe', 'C:\\Program Files\\Microsoft\\Edge\\Application\\msedge.exe'],
160
+ darwin: '/Applications/Microsoft Edge.app/Contents/MacOS/Microsoft Edge',
161
+ linux: 'microsoft-edge',
162
+ profileDirWin32: ['AppData', 'Local', 'Microsoft', 'Edge', 'User Data'],
163
+ profileDirDarwin: ['Library', 'Application Support', 'Microsoft Edge'],
164
+ profileDirLinux: ['.config', 'microsoft-edge'],
165
+ },
166
+ {
167
+ id: 'chrome',
168
+ name: 'Google Chrome',
169
+ win32: ['C:\\Program Files\\Google\\Chrome\\Application\\chrome.exe', 'C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe'],
170
+ darwin: '/Applications/Google Chrome.app/Contents/MacOS/Google Chrome',
171
+ linux: 'google-chrome',
172
+ profileDirWin32: ['AppData', 'Local', 'Google', 'Chrome', 'User Data'],
173
+ profileDirDarwin: ['Library', 'Application Support', 'Google', 'Chrome'],
174
+ profileDirLinux: ['.config', 'google-chrome'],
175
+ },
176
+ ];
177
+
178
+ export function resolveBrowserInstall(browser) {
179
+ const home = os.homedir();
180
+ let exe;
181
+ let profileSegments;
182
+ if (process.platform === 'win32') {
183
+ exe = browser.win32.find((p) => fs.existsSync(p)) || null;
184
+ profileSegments = browser.profileDirWin32;
185
+ } else if (process.platform === 'darwin') {
186
+ exe = fs.existsSync(browser.darwin) ? browser.darwin : null;
187
+ profileSegments = browser.profileDirDarwin;
188
+ } else {
189
+ exe = browser.linux; // assumed on PATH on Linux - no reliable single default install path there
190
+ profileSegments = browser.profileDirLinux;
191
+ }
192
+ if (!exe) return null;
193
+ return { id: browser.id, name: browser.name, exe, profileDir: path.join(home, ...profileSegments) };
194
+ }
195
+
196
+ /** Best-effort read of the OS's actual "default browser" setting, mapped to one of LOCAL_BROWSERS'
197
+ * `id`s - or null if it can't be determined (unsupported platform, unknown browser, command
198
+ * missing/failed) or if the default is a non-Chromium browser (Firefox/Safari - no CDP support, so
199
+ * there's nothing to tunnel into). Never throws - this is a "nice to have" signal, `findLocalBrowser`
200
+ * falls back to install-order when it's unavailable. */
201
+ export function detectDefaultBrowserId() {
202
+ try {
203
+ if (process.platform === 'win32') {
204
+ // The per-user UserChoice hash-protected key (what Settings > Default apps itself writes) is
205
+ // awkward to read reliably across Windows versions and, confirmed while testing this, is often
206
+ // just absent (no explicit override ever made). `Software\Classes\http\shell\open\command` is
207
+ // what Windows actually resolves to at launch time regardless of how it got set - HKCU holds a
208
+ // per-user override if one exists, HKLM is the system-wide fallback otherwise. Reading the
209
+ // command line's exe name directly sidesteps needing to decode a ProgId at all.
210
+ const readCommand = (hive) => {
211
+ try {
212
+ return execSync(`reg query "${hive}\\Software\\Classes\\http\\shell\\open\\command"`, { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] });
213
+ } catch {
214
+ return '';
215
+ }
216
+ };
217
+ const out = readCommand('HKCU') || readCommand('HKLM');
218
+ if (/msedge\.exe/i.test(out)) return 'edge';
219
+ if (/chrome\.exe/i.test(out)) return 'chrome';
220
+ return null; // Firefox, or something unrecognized
221
+ }
222
+ if (process.platform === 'darwin') {
223
+ // No single stock CLI for this on macOS - LaunchServices' own plist is the source of truth
224
+ // Settings > Desktop & Dock reads from, `plutil` (stock, ships with macOS) can dump it as JSON.
225
+ const plistPath = path.join(
226
+ os.homedir(), 'Library', 'Preferences', 'com.apple.LaunchServices',
227
+ 'com.apple.launchservices.secure.plist',
228
+ );
229
+ if (!fs.existsSync(plistPath)) return null;
230
+ const json = execSync(`plutil -convert json -o - "${plistPath}"`, { encoding: 'utf8' });
231
+ const handlers = JSON.parse(json)?.LSHandlers || [];
232
+ const httpHandler = handlers.find((h) => h.LSHandlerURLScheme === 'http');
233
+ const bundleId = String(httpHandler?.LSHandlerRoleAll || '').toLowerCase();
234
+ if (bundleId.includes('edge')) return 'edge';
235
+ if (bundleId.includes('chrome')) return 'chrome';
236
+ return null; // Safari, Firefox, or undetermined
237
+ }
238
+ // Linux: xdg-settings is the freedesktop.org standard way, present on most desktop distros.
239
+ const out = execSync('xdg-settings get default-web-browser', { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
240
+ if (/edge/i.test(out)) return 'edge';
241
+ if (/chrome/i.test(out)) return 'chrome';
242
+ return null;
243
+ } catch {
244
+ return null; // command missing, key absent, parse failure - all fine to just not know
245
+ }
246
+ }
247
+
248
+ /**
249
+ * Picks which installed browser to drive, in priority order:
250
+ * 1. `preferredId` (from `--browser edge|chrome`) - explicit always wins, errors clearly if that
251
+ * browser isn't actually installed rather than silently falling through to another one.
252
+ * 2. The OS's actual default browser, IF it's Chromium-based and installed - this is what makes
253
+ * "drives your own logged-in browser" true; guessing wrong here would tunnel into a browser
254
+ * profile the user doesn't actually use, with none of the cookies/logins they expect.
255
+ * 3. Whatever's installed from LOCAL_BROWSERS, in list order - last resort when the real default
256
+ * couldn't be determined or isn't Chromium (Firefox/Safari have no CDP to tunnel into).
257
+ * Always logs which one it picked and why when there was more than one candidate, so step 3 in
258
+ * particular is never a silent surprise.
259
+ */
260
+ export function findLocalBrowser(preferredId) {
261
+ const installed = LOCAL_BROWSERS.map(resolveBrowserInstall).filter(Boolean);
262
+ if (installed.length === 0) return null;
263
+
264
+ if (preferredId) {
265
+ const match = installed.find((b) => b.id === preferredId);
266
+ if (match) return match;
267
+ 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'}.`);
268
+ }
269
+
270
+ if (installed.length > 1) {
271
+ const defaultId = detectDefaultBrowserId();
272
+ const byDefault = defaultId && installed.find((b) => b.id === defaultId);
273
+ if (byDefault) return byDefault;
274
+ console.log(chalk.gray(
275
+ ` (multiple browsers installed (${installed.map((b) => b.name).join(', ')}) and couldn't confirm your OS default - ` +
276
+ `using ${installed[0].name}. Pass --browser ${installed.map((b) => b.id).join('|')} to pick.)`,
277
+ ));
278
+ }
279
+
280
+ return installed[0];
281
+ }
282
+
283
+ export function launchCommandHint(browser, port = CHROME_DEBUG_PORT) {
284
+ const label = browser ? browser.name : 'Chrome or Edge';
285
+ const exe = browser ? `"${browser.exe}"` : '<your browser>';
286
+ if (process.platform === 'win32') return `& ${exe} --remote-debugging-port=${port} (${label})`;
287
+ if (process.platform === 'darwin') return `open -a "${label}" --args --remote-debugging-port=${port}`;
288
+ return `${browser ? browser.exe : 'google-chrome'} --remote-debugging-port=${port}`;
289
+ }
290
+
291
+ export function printChromeLaunchHelp(port = CHROME_DEBUG_PORT, preferredId) {
292
+ const browser = findLocalBrowser(preferredId);
293
+ console.log(chalk.yellow('\n⚠️ Could not start a local browser for AI Browser.'));
294
+ console.log(` ${chalk.cyan(launchCommandHint(browser, port))}\n`);
295
+ console.log(chalk.gray(' ...or pass --remote for a server-side browser instead (no local browser needed).'));
296
+ }
297
+
298
+ /** Launches a browser window dedicated to `aivin browser`, on ITS OWN profile
299
+ * (AIVIN_BROWSER_PROFILE_DIR) - never the user's real daily-driver one. This is what makes local
300
+ * mode zero-friction after the first run: because it's a separate profile, it never collides with
301
+ * whatever the user's main browser is already doing (no "close all your windows first"), and once
302
+ * running it just stays up - a later mission finds it already listening and reuses it, opening a
303
+ * new tab in the SAME window rather than launching anything again. The one real cost: the first
304
+ * time any given site is used (Facebook, etc.), the user logs in once here, same as any fresh
305
+ * profile - after that it persists exactly like their main browser's cookies do. */
306
+ export async function launchLocalChromeWithDebugging(port = CHROME_DEBUG_PORT, preferredId) {
307
+ const browser = findLocalBrowser(preferredId);
308
+ if (!browser) {
309
+ throw new Error(`Could not find a local Chrome/Edge install automatically - relaunch one manually with: ${launchCommandHint(null, port)}`);
310
+ }
311
+ const firstRun = !fs.existsSync(AIVIN_BROWSER_PROFILE_DIR);
312
+ fs.mkdirSync(AIVIN_BROWSER_PROFILE_DIR, { recursive: true });
313
+ // No pre-flight SingletonLock check here on purpose (an earlier version of this had one, copied
314
+ // from the old "don't touch the user's real profile" logic where it made sense): by the time we
315
+ // get here, probeLocalChromeDebugger() has ALREADY confirmed nothing is answering on `port`, so a
316
+ // present lock file can only be stale (left behind by an unclean shutdown/crash) - Chromium itself
317
+ // already detects and clears stale locks on startup (checks whether the owning PID is still
318
+ // alive), more reliably than re-implementing that check here. A pre-check could only ever produce
319
+ // a false positive: a confusing "already open, go close it" error pointing at a window that isn't
320
+ // actually running anywhere.
321
+ if (firstRun) {
322
+ console.log(chalk.gray(` First run: opening a NEW, separate ${browser.name} window just for AI Browser (your regular ${browser.name} is untouched).`));
323
+ 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.`));
324
+ } else {
325
+ console.log(chalk.gray(` Opening your dedicated AI Browser window...`));
326
+ }
327
+ 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' });
328
+ child.unref();
329
+ for (let i = 0; i < 20; i++) {
330
+ await new Promise((resolve) => setTimeout(resolve, 500));
331
+ const { wsUrl, conflict } = await probeLocalChromeDebugger(port);
332
+ if (wsUrl) return wsUrl;
333
+ if (conflict) {
334
+ throw new Error(
335
+ `Port ${port} is already in use by something else (reported itself as "${conflict}", not Chrome/Edge) - ` +
336
+ `${browser.name} can't bind its debug port there. Free that port, or rerun with --debug-port <other-port>.`,
337
+ );
338
+ }
339
+ }
340
+ throw new Error(`${browser.name} launched but its debug port never came up in time.`);
341
+ }
342
+
343
+ /**
344
+ * Opens 2 raw WebSocket connections - one to the backend's relay (authenticated by API key), one
345
+ * to the user's own local Chrome's real CDP endpoint - and pipes frames both directions verbatim.
346
+ * `close()` disconnects both sides; the user's actual browser window is never touched beyond this
347
+ * one CDP connection, closing the tunnel just detaches Puppeteer server-side.
348
+ */
349
+ export function openLocalTunnel(serverUrl, apiKey, chromeWsUrl) {
350
+ const tunnelId = randomUUID();
351
+ const relayUrl = `${serverUrl.replace(/^http/, 'ws')}/browser-tunnel/external?tunnel_id=${tunnelId}`;
352
+
353
+ // API key goes in a header, NOT a `?token=` query param - WS upgrade URLs are exactly the kind
354
+ // of thing that ends up verbatim in reverse-proxy/CDN/access logs, unlike headers.
355
+ const toBackend = new WSClient(relayUrl, { headers: { Authorization: `Bearer ${apiKey || ''}` } });
356
+ const toChrome = new WSClient(chromeWsUrl);
357
+
358
+ const relay = (from, to) => {
359
+ from.on('message', (data, isBinary) => {
360
+ if (to.readyState === WSClient.OPEN) to.send(data, { binary: isBinary });
361
+ });
362
+ from.on('close', () => {
363
+ if (to.readyState === WSClient.OPEN) to.close();
364
+ });
365
+ from.on('error', () => {
366
+ if (to.readyState === WSClient.OPEN) to.close();
367
+ });
368
+ };
369
+ relay(toBackend, toChrome);
370
+ relay(toChrome, toBackend);
371
+
372
+ const ready = Promise.all([
373
+ new Promise((resolve, reject) => {
374
+ toBackend.once('open', resolve);
375
+ toBackend.once('error', reject);
376
+ }),
377
+ new Promise((resolve, reject) => {
378
+ toChrome.once('open', resolve);
379
+ toChrome.once('error', reject);
380
+ }),
381
+ ]);
382
+
383
+ const close = () => {
384
+ try { toBackend.close(); } catch { /* already closed */ }
385
+ try { toChrome.close(); } catch { /* already closed */ }
386
+ };
387
+
388
+ return { tunnelId, ready, close };
389
+ }
390
+
391
+ export async function runBrowserMissionLocal(mission, options) {
392
+ const serverUrl = missionServerUrl();
393
+ const apiKey = process.env.API_KEY;
394
+ const authHeaders = missionAuthHeaders();
395
+ const tenantClient = parseApiKeyClient(apiKey || '') || 'unknown';
396
+
397
+ const preferredId = options.browser ? String(options.browser).toLowerCase() : undefined;
398
+ if (preferredId && preferredId !== 'edge' && preferredId !== 'chrome') {
399
+ throw new Error(`--browser must be "edge" or "chrome", got "${options.browser}".`);
400
+ }
401
+
402
+ // --debug-port pins an exact port (strict - errors immediately if it's taken by something else).
403
+ // Without it, try the conventional 9222 first, then a few neighbors - confirmed needed for real:
404
+ // this project's OWN local dev stack publishes an unrelated container on 9222 (see
405
+ // probeLocalChromeDebugger's comment), so erroring out on the very first conflict there would make
406
+ // `aivin browser` unusable out of the box for anyone running that stack, every single time.
407
+ const explicitPort = options.debugPort !== undefined;
408
+ const candidatePorts = explicitPort ? [Number(options.debugPort)] : [CHROME_DEBUG_PORT, 9223, 9224, 9225];
409
+
410
+ let debugPort;
411
+ let chromeWsUrl;
412
+ const triedConflicts = [];
413
+ for (const port of candidatePorts) {
414
+ const probed = await probeLocalChromeDebugger(port);
415
+ if (probed.wsUrl && preferredId && probed.browserId !== preferredId) {
416
+ // Something's already listening, but it's the OTHER browser than what --browser asked for -
417
+ // using it silently would drive the wrong profile (wrong cookies/logins), so this has to be a
418
+ // hard error rather than a best-effort fallback, even mid auto-retry.
419
+ throw new Error(
420
+ `--browser ${preferredId} was requested, but the browser already listening on port ${port} is ${probed.browserId} instead. ` +
421
+ `Close it and relaunch ${preferredId} with --remote-debugging-port=${port}, or use --debug-port to point at a different port.`,
422
+ );
423
+ }
424
+ if (probed.wsUrl) { debugPort = port; chromeWsUrl = probed.wsUrl; break; }
425
+ if (probed.conflict) { triedConflicts.push(`${port} (${probed.conflict})`); continue; }
426
+ debugPort = port; // free port, nothing answering at all - safe to launch here
427
+ break;
428
+ }
429
+ if (debugPort === undefined) {
430
+ throw new Error(
431
+ `${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(', ')}. ` +
432
+ `Free one of them, or pass --debug-port <port> to use a specific one.`,
433
+ );
434
+ }
435
+
436
+ if (!chromeWsUrl) {
437
+ // Safe to always auto-launch now (unlike an earlier version of this): this opens AIVIN_BROWSER_
438
+ // PROFILE_DIR, a profile dedicated to `aivin browser` that's never the user's real daily-driver
439
+ // browser, so there's no risk of colliding with (or having to close) whatever they're already
440
+ // running elsewhere.
441
+ try {
442
+ chromeWsUrl = await launchLocalChromeWithDebugging(debugPort, preferredId);
443
+ } catch (error) {
444
+ printChromeLaunchHelp(debugPort, preferredId);
445
+ throw error;
446
+ }
447
+ }
448
+
449
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
450
+ const agentId = options.agent || (await resolveOrCreateBrowserAgent(serverUrl, authHeaders, workspace));
451
+
452
+ console.log(chalk.blue('🌐 AI Browser (local - your own browser):'), mission);
453
+ console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
454
+
455
+ const tunnel = openLocalTunnel(serverUrl, apiKey, chromeWsUrl);
456
+ try {
457
+ await tunnel.ready;
458
+ } catch (error) {
459
+ tunnel.close();
460
+ throw new Error(`Could not open the local browser tunnel: ${error.message}`, { cause: error });
461
+ }
462
+
463
+ const sessionId = `browser-cli-${randomUUID()}`;
464
+ console.log(chalk.gray(` Session: ${sessionId}`));
465
+
466
+ // Ctrl+C: request cooperative cancellation (same mechanism sdk.browser.cancel() uses - checked
467
+ // between agentic-loop steps, can't interrupt a step already in flight) AND close the tunnel.
468
+ // Closing the tunnel alone isn't enough to stop a mission stuck in an LLM call that hasn't
469
+ // touched the browser connection yet (confirmed while testing this) - the cancel request is what
470
+ // actually gets it to stop at its next chance to check. The tab this mission was using stays open
471
+ // either way - never force-closed, since local mode is explicitly "your own browser, your tabs".
472
+ let interrupted = false;
473
+ const onSigint = () => {
474
+ if (interrupted) return;
475
+ interrupted = true;
476
+ console.log(chalk.yellow('\n\n⏹ Stopping... (requesting cancellation - may take a moment, one agentic step at a time)'));
477
+ requestBrowserCancel(serverUrl, authHeaders).catch(() => {});
478
+ tunnel.close();
479
+ 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.'));
480
+ };
481
+ process.on('SIGINT', onSigint);
482
+
483
+ // Fired concurrently, not sequentially - execute-interactive is a SYNCHRONOUS call (blocks until
484
+ // the mission ends), so the log watcher has to already be listening before/as it fires, not after.
485
+ const missionPromise = axios.post(
486
+ // `/plugins/` prefix: OfficialPluginModules.ts registers every official plugin module (incl.
487
+ // AIBrowserModule) via RouterModule.register({ path: 'plugins', ... }) - easy to miss, confirmed
488
+ // by testing directly against the API (plain /ai-browser/... 404s, /plugins/ai-browser/... works).
489
+ `${serverUrl}/plugins/ai-browser/execute-interactive`,
490
+ {
491
+ mission,
492
+ workspace_id: workspace.id || workspace._id,
493
+ agent_id: agentId,
494
+ session_id: sessionId,
495
+ data: { __local_tunnel_id: tunnel.tunnelId, start_url: options.url || guessStartUrl(mission) },
496
+ },
497
+ authHeaders,
498
+ );
499
+ const watchPromise = options.watch !== false
500
+ ? streamBrowserMissionLog(serverUrl, apiKey, sessionId, tenantClient, { openViewerOnHIL: false })
501
+ : Promise.resolve();
502
+
503
+ try {
504
+ // execute-interactive responds immediately (fire-and-forget - see AIBrowserController.ts's
505
+ // comment on why: a synchronous wait here would hit the same Cloudflare 524 the gRPC
506
+ // browser.run() call did). The REAL outcome is whatever the log stream above already printed
507
+ // (ai_browser.success/failed) - this Promise.all is just making sure both sides are done.
508
+ await Promise.all([missionPromise, watchPromise]);
509
+ } catch (error) {
510
+ if (!interrupted) {
511
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
512
+ throw new Error(`AI Browser mission failed to start: ${message}`, { cause: error });
513
+ }
514
+ } finally {
515
+ process.off('SIGINT', onSigint);
516
+ tunnel.close();
517
+ }
518
+
519
+ if (!interrupted) {
520
+ console.log(chalk.gray('\n Done - see the log lines above for the outcome, and your own browser for the result.'));
521
+ }
522
+ }
523
+
524
+ /** REST twin of `sdk.browser.cancel()` - the CLI has no gRPC client, only axios. See
525
+ * AIBrowserController.cancel's comment for the exact semantics (cooperative, own-tenant-only). */
526
+ export async function requestBrowserCancel(serverUrl, authHeaders) {
527
+ await axios.post(`${serverUrl}/plugins/ai-browser/cancel`, {}, authHeaders);
528
+ }
529
+
530
+ export async function runBrowserMissionRemote(mission, options) {
531
+ const serverUrl = missionServerUrl();
532
+ const apiKey = process.env.API_KEY;
533
+ const authHeaders = missionAuthHeaders();
534
+ const tenantClient = parseApiKeyClient(apiKey || '') || 'unknown';
535
+
536
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
537
+ // Same interactive resolver `aivin do` uses (not the throw-if-missing resolveAgentId) - a fresh
538
+ // workspace commonly has zero agents installed yet, and this offers to search/install/create one
539
+ // instead of just failing. AI Browser itself is always used as the TOOL; the agent is only the
540
+ // identity/session context the mission (and HIL suspend/resume) runs under.
541
+ const agent = await resolveAgentInteractive(serverUrl, authHeaders, workspace, options.agent);
542
+ const agentId = agent.id || agent.agent_id;
543
+
544
+ console.log(chalk.blue('🌐 AI Browser (remote - server-side browser):'), mission);
545
+ console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id} Agent: ${agent.nickname || agent.name || agentId}`));
546
+
547
+ let response;
548
+ try {
549
+ response = await axios.post(
550
+ `${serverUrl}/agent/start-work`,
551
+ {
552
+ prompt: BROWSER_MISSION_PREFIX + mission,
553
+ mission: BROWSER_MISSION_PREFIX + mission,
554
+ workspace_id: workspace.id || workspace._id,
555
+ agent_id: agentId,
556
+ project_id: options.project,
557
+ },
558
+ authHeaders,
559
+ );
560
+ } catch (error) {
561
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
562
+ throw new Error(`Failed to start AI Browser mission: ${message}`, { cause: error });
563
+ }
564
+
565
+ const result = response.data ?? {};
566
+ if (result.success === false) {
567
+ throw new Error(result.message || 'Failed to start AI Browser mission');
568
+ }
569
+ const threadId = result.data?.thread_id;
570
+ console.log(chalk.gray(` Thread: ${threadId || 'unknown'}`));
571
+
572
+ if (options.watch !== false && threadId) {
573
+ await streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClient);
574
+ }
575
+ }