@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.
Files changed (93) hide show
  1. package/README.md +288 -216
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +551 -5
  4. package/bin/lib/browserAutomation.mjs +384 -614
  5. package/bin/lib/browserTui.mjs +276 -251
  6. package/bin/lib/cancellation.mjs +61 -0
  7. package/bin/lib/localBrowser.mjs +345 -0
  8. package/bin/lib/mcpProxy.mjs +869 -837
  9. package/bin/lib/missionStream.mjs +696 -691
  10. package/bin/lib/releaseKeys.mjs +9 -0
  11. package/bin/lib/remote/activityLog.mjs +68 -0
  12. package/bin/lib/remote/autoStart.mjs +617 -0
  13. package/bin/lib/remote/autoUpdate.mjs +129 -0
  14. package/bin/lib/remote/brand.mjs +60 -0
  15. package/bin/lib/remote/browserTunnel.mjs +403 -0
  16. package/bin/lib/remote/callLedger.mjs +134 -0
  17. package/bin/lib/remote/cdpPolicy.mjs +79 -0
  18. package/bin/lib/remote/client.mjs +808 -0
  19. package/bin/lib/remote/clipboard.mjs +138 -0
  20. package/bin/lib/remote/codingAgents.mjs +293 -0
  21. package/bin/lib/remote/constants.mjs +234 -0
  22. package/bin/lib/remote/credentials.mjs +208 -0
  23. package/bin/lib/remote/daemonLock.mjs +86 -0
  24. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  25. package/bin/lib/remote/desktop/index.mjs +272 -0
  26. package/bin/lib/remote/desktop/linux.mjs +144 -0
  27. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  28. package/bin/lib/remote/desktop/mac.mjs +187 -0
  29. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  30. package/bin/lib/remote/desktop/strings.mjs +74 -0
  31. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  32. package/bin/lib/remote/deviceMemory.mjs +246 -0
  33. package/bin/lib/remote/deviceProfile.mjs +142 -0
  34. package/bin/lib/remote/deviceWatches.mjs +138 -0
  35. package/bin/lib/remote/docText.mjs +117 -0
  36. package/bin/lib/remote/fileIndexer.mjs +399 -0
  37. package/bin/lib/remote/gui/index.mjs +326 -0
  38. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  39. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  40. package/bin/lib/remote/gui/windowsHostSource.mjs +1156 -0
  41. package/bin/lib/remote/httpTransfer.mjs +89 -0
  42. package/bin/lib/remote/idempotency.mjs +135 -0
  43. package/bin/lib/remote/keepAwake.mjs +100 -0
  44. package/bin/lib/remote/localConfirm.mjs +268 -0
  45. package/bin/lib/remote/localPolicy.mjs +256 -0
  46. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  47. package/bin/lib/remote/mascot/ask.mjs +768 -0
  48. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  49. package/bin/lib/remote/mascot/assets.mjs +827 -0
  50. package/bin/lib/remote/mascot/bot.mjs +372 -0
  51. package/bin/lib/remote/mascot/hostSource.mjs +759 -0
  52. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  53. package/bin/lib/remote/mascot/index.mjs +493 -0
  54. package/bin/lib/remote/mascot/labels.mjs +82 -0
  55. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  56. package/bin/lib/remote/mascot/strings.mjs +375 -0
  57. package/bin/lib/remote/mascot/ui.mjs +104 -0
  58. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  59. package/bin/lib/remote/meeting/index.mjs +415 -0
  60. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  61. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  62. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  63. package/bin/lib/remote/memberFsPool.mjs +134 -0
  64. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  65. package/bin/lib/remote/mission.mjs +156 -0
  66. package/bin/lib/remote/missionQuestion.mjs +63 -0
  67. package/bin/lib/remote/multiUser.mjs +344 -0
  68. package/bin/lib/remote/netProxy.mjs +145 -0
  69. package/bin/lib/remote/notify.mjs +58 -0
  70. package/bin/lib/remote/office/index.mjs +90 -0
  71. package/bin/lib/remote/policyCommand.mjs +93 -0
  72. package/bin/lib/remote/processes.mjs +217 -0
  73. package/bin/lib/remote/sandbox.mjs +221 -0
  74. package/bin/lib/remote/schedule.mjs +213 -0
  75. package/bin/lib/remote/scheduler.mjs +124 -0
  76. package/bin/lib/remote/tabGroups.mjs +209 -0
  77. package/bin/lib/remote/textIndex.mjs +131 -0
  78. package/bin/lib/remote/tokenStore.mjs +77 -0
  79. package/bin/lib/remote/toolHandlers.mjs +741 -0
  80. package/bin/lib/remote/undoStore.mjs +242 -0
  81. package/bin/lib/remoteControl.mjs +26 -0
  82. package/bin/lib/scaffold.mjs +654 -653
  83. package/bin/lib/selfUpdate.mjs +71 -0
  84. package/bin/lib/update/binarySwap.mjs +63 -0
  85. package/bin/lib/update/constants.mjs +56 -0
  86. package/bin/lib/update/download.mjs +145 -0
  87. package/bin/lib/update/signature.mjs +42 -0
  88. package/bin/lib/update/state.mjs +205 -0
  89. package/bin/lib/update/versions.mjs +60 -0
  90. package/docs/AIVIN_MASCOT.md +116 -0
  91. package/docs/CLI.md +1484 -1299
  92. package/docs/media/aivin-mascot-states.mp4 +0 -0
  93. package/package.json +71 -62
@@ -1,402 +1,152 @@
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, BROWSER_MISSION_PREFIX } from './missionStream.mjs';
12
- import { watchBrowserMission } from './browserTui.mjs';
13
-
14
- // ── `aivin browser` default mode: drive the user's OWN local, already-running browser ──────────
15
- //
16
- // Real cookies/logins, real fingerprint - much better bot-detection resistance than the server-
17
- // side pooled browser `--remote` uses. Architecture: a raw WebSocket relay on the backend
18
- // (BrowserTunnelRelay) pairs this CLI's connection to the user's local Chrome CDP endpoint with
19
- // 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.
22
-
23
- export const BROWSER_CLI_AGENT_CACHE_PATH = path.join(os.homedir(), '.aivin', 'browser-cli-agents.json');
24
-
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
- export function loadBrowserCliAgentCache() {
44
- try {
45
- return JSON.parse(fs.readFileSync(BROWSER_CLI_AGENT_CACHE_PATH, 'utf8'));
46
- } catch {
47
- return {};
48
- }
49
- }
50
-
51
- export function saveBrowserCliAgentCache(cache) {
52
- fs.mkdirSync(path.dirname(BROWSER_CLI_AGENT_CACHE_PATH), { recursive: true });
53
- fs.writeFileSync(BROWSER_CLI_AGENT_CACHE_PATH, JSON.stringify(cache, null, 2) + '\n');
54
- }
55
-
56
- /**
57
- * `aivin browser` shouldn't require the user to know/pick an "agent" - AI Browser is what actually
58
- * does the work, the agent is just session/HIL identity plumbing the platform's data model requires
59
- * underneath. Creates one dedicated agent per workspace the first time, with `official.ai_browser`
60
- * already enabled, and caches its id so every later run is instant. Both API calls below (create,
61
- * then a second update call with `plugins.plugin_ids`) were verified working directly against the
62
- * API this session - `workspace_id` must be a query param on the update call (the DTO whitelists
63
- * it out of the body), and name/nickname/email must be repeated even though only `plugins` changed.
64
- */
65
- export async function resolveOrCreateBrowserAgent(serverUrl, authHeaders, workspace) {
66
- const workspaceId = workspace.id || workspace._id;
67
- const cache = loadBrowserCliAgentCache();
68
- const cachedId = cache[workspaceId];
69
- if (cachedId && workspace.agents?.some((a) => (a.id || a.agent_id) === cachedId)) {
70
- return cachedId;
71
- }
72
-
73
- console.log(chalk.gray(' (no cached browser agent for this workspace yet - creating one, one-time only)'));
74
- const identity = {
75
- name: 'AI Browser (CLI)',
76
- nickname: 'aivin-browser-cli',
77
- email: `aivin-browser-cli+${workspaceId}@local.invalid`,
78
- };
79
-
80
- // `/ai-staff/update` requires name/nickname/email again even though only `plugins` is actually
81
- // changing (confirmed while testing) - default to the NEW agent's own identity, but when falling
82
- // back to an EXISTING agent below, this must become THAT agent's real identity instead, or the
83
- // update call would silently overwrite/rename someone's real agent with the CLI's placeholder
84
- // name - a real, destructive bug caught in review before ever shipping.
85
- let agentId;
86
- let updateIdentity = identity;
87
- try {
88
- const created = await createAgent(serverUrl, authHeaders, {
89
- ...identity,
90
- bio: 'Auto-created by `aivin browser` - runs AI Browser missions triggered from the CLI.',
91
- workspaceId,
92
- });
93
- agentId = created.id || created.agent_id;
94
- await pullAgentIntoWorkspace(serverUrl, authHeaders, { agentId, workspaceId });
95
- } catch (error) {
96
- // Confirmed hitting this directly while testing: accounts on a plan with a low agent-count
97
- // limit get a clear "limit reached" error here. Rather than dead-ending, fall back to reusing
98
- // the workspace's own first existing agent (if any) - enabling official.ai_browser on it is a
99
- // much better outcome than making the user go figure out --agent <id> themselves after a
100
- // confusing failure.
101
- const existing = workspace.agents?.[0];
102
- if (!existing) throw error; // nothing to fall back to - surface the original error as-is
103
- const message = error.response?.data?.message || error.message;
104
- console.log(chalk.yellow(` āš ļø Couldn't create a dedicated agent (${message}) - reusing "${existing.nickname || existing.name}" instead.`));
105
- agentId = existing.id || existing.agent_id;
106
- updateIdentity = { name: existing.name, nickname: existing.nickname, email: existing.email };
107
- }
108
-
109
- // Merge, don't replace - an existing agent (the fallback path above) may already have OTHER
110
- // plugins enabled; sending plugin_ids: ['official.ai_browser'] alone would silently wipe those.
111
- const existingPluginIds = workspace.agents?.find((a) => (a.id || a.agent_id) === agentId)?.plugins?.plugin_ids || [];
112
- const mergedPluginIds = existingPluginIds.includes('official.ai_browser') ? existingPluginIds : [...existingPluginIds, 'official.ai_browser'];
113
-
114
- await axios
115
- .post(
116
- `${serverUrl}/ai-staff/update?workspace_id=${encodeURIComponent(workspaceId)}`,
117
- { id: agentId, ...updateIdentity, plugins: { plugin_ids: mergedPluginIds } },
118
- authHeaders,
119
- )
120
- .catch((error) => {
121
- const message = error.response?.data?.message || error.message;
122
- console.log(chalk.yellow(` āš ļø Could not enable official.ai_browser on the agent automatically: ${message}`));
123
- });
124
-
125
- cache[workspaceId] = agentId;
126
- saveBrowserCliAgentCache(cache);
127
- console.log(chalk.green(` āœ… Agent ready for AI Browser CLI use (cached for next time).`));
128
- return agentId;
129
- }
130
-
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
- }
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 { randomUUID } from 'crypto';
7
+ import { missionServerUrl, missionAuthHeaders, resolveWorkspace, resolveAgentInteractive, createAgent, pullAgentIntoWorkspace } from './workspace.mjs';
8
+ import { parseApiKeyClient } from './auth.mjs';
9
+ import { guessStartUrl, BROWSER_MISSION_PREFIX } from './missionStream.mjs';
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';
14
+
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 ────────────────────────────
22
+ //
23
+ // Real cookies/logins, real fingerprint - much better bot-detection resistance than the server-
24
+ // side pooled browser `--remote` uses. Architecture: a raw WebSocket relay on the backend
25
+ // (BrowserTunnelRelay) pairs this CLI's connection to the user's local Chrome CDP endpoint with
26
+ // AIBrowserService's own `BrowserIO.connect(...)` call server-side - the EXISTING agentic loop
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.
35
+
36
+ export const BROWSER_CLI_AGENT_CACHE_PATH = path.join(os.homedir(), '.aivin', 'browser-cli-agents.json');
37
+
38
+ export function loadBrowserCliAgentCache() {
39
+ try {
40
+ return JSON.parse(fs.readFileSync(BROWSER_CLI_AGENT_CACHE_PATH, 'utf8'));
41
+ } catch {
42
+ return {};
43
+ }
44
+ }
45
+
46
+ export function saveBrowserCliAgentCache(cache) {
47
+ fs.mkdirSync(path.dirname(BROWSER_CLI_AGENT_CACHE_PATH), { recursive: true });
48
+ fs.writeFileSync(BROWSER_CLI_AGENT_CACHE_PATH, JSON.stringify(cache, null, 2) + '\n');
49
+ }
50
+
51
+ /**
52
+ * `aivin browser` shouldn't require the user to know/pick an "agent" - AI Browser is what actually
53
+ * does the work, the agent is just session/HIL identity plumbing the platform's data model requires
54
+ * underneath. Creates one dedicated agent per workspace the first time, with `official.ai_browser`
55
+ * already enabled, and caches its id so every later run is instant. Both API calls below (create,
56
+ * then a second update call with `plugins.plugin_ids`) were verified working directly against the
57
+ * API this session - `workspace_id` must be a query param on the update call (the DTO whitelists
58
+ * it out of the body), and name/nickname/email must be repeated even though only `plugins` changed.
59
+ */
60
+ export async function resolveOrCreateBrowserAgent(serverUrl, authHeaders, workspace) {
61
+ const workspaceId = workspace.id || workspace._id;
62
+ const cache = loadBrowserCliAgentCache();
63
+ const cachedId = cache[workspaceId];
64
+ if (cachedId && workspace.agents?.some((a) => (a.id || a.agent_id) === cachedId)) {
65
+ return cachedId;
66
+ }
67
+
68
+ console.log(chalk.gray(' (no cached browser agent for this workspace yet - creating one, one-time only)'));
69
+ const identity = {
70
+ name: 'AI Browser (CLI)',
71
+ nickname: 'aivin-browser-cli',
72
+ email: `aivin-browser-cli+${workspaceId}@local.invalid`,
73
+ };
74
+
75
+ // `/ai-staff/update` requires name/nickname/email again even though only `plugins` is actually
76
+ // changing (confirmed while testing) - default to the NEW agent's own identity, but when falling
77
+ // back to an EXISTING agent below, this must become THAT agent's real identity instead, or the
78
+ // update call would silently overwrite/rename someone's real agent with the CLI's placeholder
79
+ // name - a real, destructive bug caught in review before ever shipping.
80
+ let agentId;
81
+ let updateIdentity = identity;
82
+ try {
83
+ const created = await createAgent(serverUrl, authHeaders, {
84
+ ...identity,
85
+ bio: 'Auto-created by `aivin browser` - runs AI Browser missions triggered from the CLI.',
86
+ workspaceId,
87
+ });
88
+ agentId = created.id || created.agent_id;
89
+ await pullAgentIntoWorkspace(serverUrl, authHeaders, { agentId, workspaceId });
90
+ } catch (error) {
91
+ // Confirmed hitting this directly while testing: accounts on a plan with a low agent-count
92
+ // limit get a clear "limit reached" error here. Rather than dead-ending, fall back to reusing
93
+ // the workspace's own first existing agent (if any) - enabling official.ai_browser on it is a
94
+ // much better outcome than making the user go figure out --agent <id> themselves after a
95
+ // confusing failure.
96
+ const existing = workspace.agents?.[0];
97
+ if (!existing) throw error; // nothing to fall back to - surface the original error as-is
98
+ const message = error.response?.data?.message || error.message;
99
+ console.log(chalk.yellow(` āš ļø Couldn't create a dedicated agent (${message}) - reusing "${existing.nickname || existing.name}" instead.`));
100
+ agentId = existing.id || existing.agent_id;
101
+ updateIdentity = { name: existing.name, nickname: existing.nickname, email: existing.email };
102
+ }
103
+
104
+ // Merge, don't replace - an existing agent (the fallback path above) may already have OTHER
105
+ // plugins enabled; sending plugin_ids: ['official.ai_browser'] alone would silently wipe those.
106
+ const existingPluginIds = workspace.agents?.find((a) => (a.id || a.agent_id) === agentId)?.plugins?.plugin_ids || [];
107
+ const mergedPluginIds = existingPluginIds.includes('official.ai_browser') ? existingPluginIds : [...existingPluginIds, 'official.ai_browser'];
108
+
109
+ await axios
110
+ .post(
111
+ `${serverUrl}/ai-staff/update?workspace_id=${encodeURIComponent(workspaceId)}`,
112
+ { id: agentId, ...updateIdentity, plugins: { plugin_ids: mergedPluginIds } },
113
+ authHeaders,
114
+ )
115
+ .catch((error) => {
116
+ const message = error.response?.data?.message || error.message;
117
+ console.log(chalk.yellow(` āš ļø Could not enable official.ai_browser on the agent automatically: ${message}`));
118
+ });
119
+
120
+ cache[workspaceId] = agentId;
121
+ saveBrowserCliAgentCache(cache);
122
+ console.log(chalk.green(` āœ… Agent ready for AI Browser CLI use (cached for next time).`));
123
+ return agentId;
124
+ }
125
+
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
340
149
  }
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
150
  }
401
151
 
402
152
  export async function runBrowserMissionLocal(mission, options) {
@@ -406,243 +156,263 @@ export async function runBrowserMissionLocal(mission, options) {
406
156
  const tenantClient = parseApiKeyClient(apiKey || '') || 'unknown';
407
157
 
408
158
  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}".`);
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.`);
411
164
  }
412
165
 
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.
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.
418
171
  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;
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}".`);
439
175
  }
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
- );
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.');
445
181
  }
446
182
 
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.
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;
452
189
  try {
453
- chromeWsUrl = await launchLocalChromeWithDebugging(debugPort, preferredId);
190
+ found = await ensureAivinBrowser(preferredId || browser.id, { ports, launch: launchAllowed, log: (m) => console.log(chalk.gray(m)) });
454
191
  } catch (error) {
455
- printChromeLaunchHelp(debugPort, preferredId);
192
+ if (launchAllowed) printChromeLaunchHelp(ports[0], preferredId);
193
+ error.browserSetup = true;
456
194
  throw error;
457
195
  }
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}`));
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
+ };
465
208
 
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;
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
+ });
476
217
 
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;
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})...`));
486
243
  }
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
244
 
504
- const sessionId = `browser-cli-${randomUUID()}`;
505
- console.log(chalk.gray(` Session: ${sessionId}`));
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
+ }
506
261
 
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).catch((e) =>
518
- console.log(chalk.red(` āš ļø Cancellation request failed to send (${e.message}) - the mission may keep running.`)),
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,
519
298
  );
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 })
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 });
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);
556
318
  }
557
- } finally {
558
- process.off('SIGINT', onSigint);
559
- tunnel.close();
560
- }
561
319
 
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;
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
+ }
570
329
  }
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
- }
577
-
578
- /** REST twin of `sdk.browser.cancel()` - the CLI has no gRPC client, only axios. See
579
- * AIBrowserController.cancel's comment for the exact semantics (cooperative, own-tenant-only). */
580
- export async function requestBrowserCancel(serverUrl, authHeaders) {
581
- await axios.post(`${serverUrl}/plugins/ai-browser/cancel`, {}, authHeaders);
582
- }
583
330
 
584
- export async function runBrowserMissionRemote(mission, options) {
585
- const serverUrl = missionServerUrl();
586
- const apiKey = process.env.API_KEY;
587
- const authHeaders = missionAuthHeaders();
588
- const tenantClient = parseApiKeyClient(apiKey || '') || 'unknown';
589
-
590
- const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
591
- // Same interactive resolver `aivin do` uses (not the throw-if-missing resolveAgentId) - a fresh
592
- // workspace commonly has zero agents installed yet, and this offers to search/install/create one
593
- // instead of just failing. AI Browser itself is always used as the TOOL; the agent is only the
594
- // identity/session context the mission (and HIL suspend/resume) runs under.
595
- const agent = await resolveAgentInteractive(serverUrl, authHeaders, workspace, options.agent);
596
- const agentId = agent.id || agent.agent_id;
597
-
598
- console.log(chalk.blue('🌐 AI Browser (remote - server-side browser):'), mission);
599
- console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id} Agent: ${agent.nickname || agent.name || agentId}`));
600
-
601
- let response;
602
- try {
603
- response = await axios.post(
604
- `${serverUrl}/agent/start-work`,
605
- {
606
- prompt: BROWSER_MISSION_PREFIX + mission,
607
- mission: BROWSER_MISSION_PREFIX + mission,
608
- workspace_id: workspace.id || workspace._id,
609
- agent_id: agentId,
610
- project_id: options.project,
611
- },
612
- authHeaders,
613
- );
614
- } catch (error) {
615
- const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
616
- throw new Error(`Failed to start AI Browser mission: ${message}`, { cause: error });
617
- }
618
-
619
- const result = response.data ?? {};
620
- if (result.success === false) {
621
- throw new Error(result.message || 'Failed to start AI Browser mission');
622
- }
623
- const threadId = result.data?.thread_id;
624
- console.log(chalk.gray(` Thread: ${threadId || 'unknown'}`));
625
-
626
- // Same cooperative-cancel wiring as the local-mode path above (requestBrowserCancel is
627
- // tenant-scoped, not session/thread-scoped, so it applies here unchanged) - without this, Ctrl+C
628
- // only stopped streamBrowserMissionLog's own SIGINT handler, which just disconnects the log
629
- // socket and returns; the mission itself kept running server-side with nothing telling it to stop.
630
- let interrupted = false;
631
- const onSigint = () => {
632
- if (interrupted) return;
633
- interrupted = true;
634
- console.log(chalk.yellow('\n\nā¹ Stopping... (requesting cancellation - may take a moment, one agentic step at a time)'));
635
- requestBrowserCancel(serverUrl, authHeaders).catch((e) =>
636
- console.log(chalk.red(` āš ļø Cancellation request failed to send (${e.message}) - the mission may keep running.`)),
637
- );
638
- };
639
- process.on('SIGINT', onSigint);
640
-
641
- try {
642
- if (options.watch !== false && threadId) {
643
- await watchBrowserMission(serverUrl, apiKey, threadId, tenantClient);
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.'));
644
333
  }
645
334
  } finally {
646
- process.off('SIGINT', onSigint);
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();
647
338
  }
648
339
  }
340
+
341
+ /** REST twin of `sdk.browser.cancel()` - the CLI has no gRPC client, only axios. See
342
+ * AIBrowserController.cancel's comment for the exact semantics (cooperative, own-tenant-only). */
343
+ export async function requestBrowserCancel(serverUrl, authHeaders, { sessionId, threadId } = {}) {
344
+ await axios.post(
345
+ `${serverUrl}/plugins/ai-browser/cancel`,
346
+ {
347
+ ...(sessionId ? { session_id: sessionId } : {}),
348
+ ...(threadId ? { thread_id: threadId } : {}),
349
+ },
350
+ authHeaders,
351
+ );
352
+ }
353
+
354
+ export async function runBrowserMissionRemote(mission, options) {
355
+ const serverUrl = missionServerUrl();
356
+ const apiKey = process.env.API_KEY;
357
+ const authHeaders = missionAuthHeaders();
358
+ const tenantClient = parseApiKeyClient(apiKey || '') || 'unknown';
359
+
360
+ const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
361
+ // Same interactive resolver `aivin do` uses (not the throw-if-missing resolveAgentId) - a fresh
362
+ // workspace commonly has zero agents installed yet, and this offers to search/install/create one
363
+ // instead of just failing. AI Browser itself is always used as the TOOL; the agent is only the
364
+ // identity/session context the mission (and HIL suspend/resume) runs under.
365
+ const agent = await resolveAgentInteractive(serverUrl, authHeaders, workspace, options.agent);
366
+ const agentId = agent.id || agent.agent_id;
367
+
368
+ console.log(chalk.blue('🌐 AI Browser (remote - server-side browser):'), mission);
369
+ console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id} Agent: ${agent.nickname || agent.name || agentId}`));
370
+
371
+ let response;
372
+ try {
373
+ response = await axios.post(
374
+ `${serverUrl}/agent/start-work`,
375
+ {
376
+ prompt: BROWSER_MISSION_PREFIX + mission,
377
+ mission: BROWSER_MISSION_PREFIX + mission,
378
+ workspace_id: workspace.id || workspace._id,
379
+ agent_id: agentId,
380
+ project_id: options.project,
381
+ },
382
+ authHeaders,
383
+ );
384
+ } catch (error) {
385
+ const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
386
+ throw new Error(`Failed to start AI Browser mission: ${message}`, { cause: error });
387
+ }
388
+
389
+ const result = response.data ?? {};
390
+ if (result.success === false) {
391
+ throw new Error(result.message || 'Failed to start AI Browser mission');
392
+ }
393
+ const threadId = result.data?.thread_id;
394
+ console.log(chalk.gray(` Thread: ${threadId || 'unknown'}`));
395
+
396
+ // Same cooperative-cancel wiring as the local-mode path above (requestBrowserCancel is
397
+ // tenant-scoped, not session/thread-scoped, so it applies here unchanged) - without this, Ctrl+C
398
+ // only stopped streamBrowserMissionLog's own SIGINT handler, which just disconnects the log
399
+ // socket and returns; the mission itself kept running server-side with nothing telling it to stop.
400
+ let interrupted = false;
401
+ const onSigint = () => {
402
+ if (interrupted) return;
403
+ interrupted = true;
404
+ console.log(chalk.yellow('\n\nā¹ Stopping... (requesting cancellation - may take a moment, one agentic step at a time)'));
405
+ requestBrowserCancel(serverUrl, authHeaders, { threadId }).catch((e) =>
406
+ console.log(chalk.red(` āš ļø Cancellation request failed to send (${e.message}) - the mission may keep running.`)),
407
+ );
408
+ };
409
+ process.on('SIGINT', onSigint);
410
+
411
+ try {
412
+ if (options.watch !== false && threadId) {
413
+ await watchBrowserMission(serverUrl, apiKey, threadId, tenantClient, { threadId });
414
+ }
415
+ } finally {
416
+ process.off('SIGINT', onSigint);
417
+ }
418
+ }