@aivin-labs/cli 1.0.4 → 1.0.8
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +263 -216
- package/bin/cli.mjs +1780 -1361
- package/bin/lib/browserAutomation.mjs +655 -648
- package/bin/lib/browserTui.mjs +276 -245
- package/bin/lib/cancellation.mjs +61 -0
- package/bin/lib/codegen.mjs +61 -5
- package/bin/lib/connectors.mjs +55 -21
- package/bin/lib/deploy.mjs +25 -2
- package/bin/lib/mcpProxy.mjs +869 -773
- package/bin/lib/mission.mjs +13 -1
- package/bin/lib/missionStream.mjs +696 -660
- package/bin/lib/pluginAuthResolve.mjs +127 -0
- package/bin/lib/pluginTrigger.mjs +207 -90
- package/bin/lib/releaseKeys.mjs +9 -0
- package/bin/lib/remote/activityLog.mjs +68 -0
- package/bin/lib/remote/autoStart.mjs +457 -0
- package/bin/lib/remote/autoUpdate.mjs +129 -0
- package/bin/lib/remote/brand.mjs +60 -0
- package/bin/lib/remote/browserTunnel.mjs +292 -0
- package/bin/lib/remote/callLedger.mjs +134 -0
- package/bin/lib/remote/cdpPolicy.mjs +66 -0
- package/bin/lib/remote/client.mjs +726 -0
- package/bin/lib/remote/constants.mjs +173 -0
- package/bin/lib/remote/credentials.mjs +208 -0
- package/bin/lib/remote/daemonLock.mjs +86 -0
- package/bin/lib/remote/dailyBrowser.mjs +371 -0
- package/bin/lib/remote/deviceMemory.mjs +246 -0
- package/bin/lib/remote/deviceProfile.mjs +142 -0
- package/bin/lib/remote/deviceWatches.mjs +138 -0
- package/bin/lib/remote/docText.mjs +117 -0
- package/bin/lib/remote/fileIndexer.mjs +399 -0
- package/bin/lib/remote/gui/index.mjs +245 -0
- package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
- package/bin/lib/remote/gui/windowsHost.mjs +109 -0
- package/bin/lib/remote/gui/windowsHostSource.mjs +904 -0
- package/bin/lib/remote/httpTransfer.mjs +89 -0
- package/bin/lib/remote/idempotency.mjs +135 -0
- package/bin/lib/remote/keepAwake.mjs +100 -0
- package/bin/lib/remote/localConfirm.mjs +268 -0
- package/bin/lib/remote/localPolicy.mjs +249 -0
- package/bin/lib/remote/mascot/assets.mjs +218 -0
- package/bin/lib/remote/mascot/hostSource.mjs +362 -0
- package/bin/lib/remote/mascot/index.mjs +322 -0
- package/bin/lib/remote/mascot/labels.mjs +83 -0
- package/bin/lib/remote/mascot/strings.mjs +189 -0
- package/bin/lib/remote/memberFsPool.mjs +134 -0
- package/bin/lib/remote/memberFsWorker.mjs +60 -0
- package/bin/lib/remote/mission.mjs +156 -0
- package/bin/lib/remote/missionQuestion.mjs +63 -0
- package/bin/lib/remote/multiUser.mjs +344 -0
- package/bin/lib/remote/netProxy.mjs +145 -0
- package/bin/lib/remote/notify.mjs +58 -0
- package/bin/lib/remote/office/index.mjs +90 -0
- package/bin/lib/remote/policyCommand.mjs +93 -0
- package/bin/lib/remote/processes.mjs +217 -0
- package/bin/lib/remote/sandbox.mjs +221 -0
- package/bin/lib/remote/schedule.mjs +213 -0
- package/bin/lib/remote/scheduler.mjs +124 -0
- package/bin/lib/remote/textIndex.mjs +131 -0
- package/bin/lib/remote/tokenStore.mjs +77 -0
- package/bin/lib/remote/toolHandlers.mjs +726 -0
- package/bin/lib/remote/undoStore.mjs +242 -0
- package/bin/lib/remoteControl.mjs +26 -0
- package/bin/lib/scaffold.mjs +654 -653
- package/bin/lib/selfUpdate.mjs +71 -0
- package/bin/lib/store.mjs +16 -2
- package/bin/lib/tasks.mjs +52 -8
- package/bin/lib/update/binarySwap.mjs +63 -0
- package/bin/lib/update/constants.mjs +56 -0
- package/bin/lib/update/download.mjs +145 -0
- package/bin/lib/update/signature.mjs +42 -0
- package/bin/lib/update/state.mjs +205 -0
- package/bin/lib/update/versions.mjs +60 -0
- package/bin/lib/util.mjs +8 -0
- package/docs/CLI.md +1353 -1274
- package/package.json +71 -62
|
@@ -1,648 +1,655 @@
|
|
|
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
|
-
}
|
|
340
|
-
}
|
|
341
|
-
throw new Error(`${browser.name} launched but its debug port never came up in time.`);
|
|
342
|
-
}
|
|
343
|
-
|
|
344
|
-
/**
|
|
345
|
-
* Opens 2 raw WebSocket connections - one to the backend's relay (authenticated by API key), one
|
|
346
|
-
* to the user's own local Chrome's real CDP endpoint - and pipes frames both directions verbatim.
|
|
347
|
-
* `close()` disconnects both sides; the user's actual browser window is never touched beyond this
|
|
348
|
-
* one CDP connection, closing the tunnel just detaches Puppeteer server-side.
|
|
349
|
-
*
|
|
350
|
-
* `onUnexpectedClose(side)` fires when either leg drops WITHOUT `close()` having been called first
|
|
351
|
-
* (side is 'backend' or 'chrome') - lets the caller distinguish "network/tunnel died mid-mission"
|
|
352
|
-
* from "we're done, tearing down deliberately" (Ctrl+C, mission finished) without guessing from
|
|
353
|
-
* timing alone. Never fires after a deliberate `close()`.
|
|
354
|
-
*/
|
|
355
|
-
export function openLocalTunnel(serverUrl, apiKey, chromeWsUrl, { onUnexpectedClose } = {}) {
|
|
356
|
-
const tunnelId = randomUUID();
|
|
357
|
-
const relayUrl = `${serverUrl.replace(/^http/, 'ws')}/browser-tunnel/external?tunnel_id=${tunnelId}`;
|
|
358
|
-
|
|
359
|
-
// API key goes in a header, NOT a `?token=` query param - WS upgrade URLs are exactly the kind
|
|
360
|
-
// of thing that ends up verbatim in reverse-proxy/CDN/access logs, unlike headers.
|
|
361
|
-
const toBackend = new WSClient(relayUrl, { headers: { Authorization: `Bearer ${apiKey || ''}` } });
|
|
362
|
-
const toChrome = new WSClient(chromeWsUrl);
|
|
363
|
-
|
|
364
|
-
let deliberateClose = false;
|
|
365
|
-
|
|
366
|
-
const relay = (from, to, side) => {
|
|
367
|
-
from.on('message', (data, isBinary) => {
|
|
368
|
-
if (to.readyState === WSClient.OPEN) to.send(data, { binary: isBinary });
|
|
369
|
-
});
|
|
370
|
-
from.on('close', () => {
|
|
371
|
-
if (to.readyState === WSClient.OPEN) to.close();
|
|
372
|
-
if (!deliberateClose) onUnexpectedClose?.(side);
|
|
373
|
-
});
|
|
374
|
-
from.on('error', () => {
|
|
375
|
-
if (to.readyState === WSClient.OPEN) to.close();
|
|
376
|
-
if (!deliberateClose) onUnexpectedClose?.(side);
|
|
377
|
-
});
|
|
378
|
-
};
|
|
379
|
-
relay(toBackend, toChrome, 'backend');
|
|
380
|
-
relay(toChrome, toBackend, 'chrome');
|
|
381
|
-
|
|
382
|
-
const ready = Promise.all([
|
|
383
|
-
new Promise((resolve, reject) => {
|
|
384
|
-
toBackend.once('open', resolve);
|
|
385
|
-
toBackend.once('error', reject);
|
|
386
|
-
}),
|
|
387
|
-
new Promise((resolve, reject) => {
|
|
388
|
-
toChrome.once('open', resolve);
|
|
389
|
-
toChrome.once('error', reject);
|
|
390
|
-
}),
|
|
391
|
-
]);
|
|
392
|
-
|
|
393
|
-
const close = () => {
|
|
394
|
-
deliberateClose = true;
|
|
395
|
-
try { toBackend.close(); } catch { /* already closed */ }
|
|
396
|
-
try { toChrome.close(); } catch { /* already closed */ }
|
|
397
|
-
};
|
|
398
|
-
|
|
399
|
-
return { tunnelId, ready, close };
|
|
400
|
-
}
|
|
401
|
-
|
|
402
|
-
export async function runBrowserMissionLocal(mission, options) {
|
|
403
|
-
const serverUrl = missionServerUrl();
|
|
404
|
-
const apiKey = process.env.API_KEY;
|
|
405
|
-
const authHeaders = missionAuthHeaders();
|
|
406
|
-
const tenantClient = parseApiKeyClient(apiKey || '') || 'unknown';
|
|
407
|
-
|
|
408
|
-
const preferredId = options.browser ? String(options.browser).toLowerCase() : undefined;
|
|
409
|
-
if (preferredId && preferredId !== 'edge' && preferredId !== 'chrome') {
|
|
410
|
-
throw new Error(`--browser must be "edge" or "chrome", got "${options.browser}".`);
|
|
411
|
-
}
|
|
412
|
-
|
|
413
|
-
// --debug-port pins an exact port (strict - errors immediately if it's taken by something else).
|
|
414
|
-
// Without it, try the conventional 9222 first, then a few neighbors - confirmed needed for real:
|
|
415
|
-
// this project's OWN local dev stack publishes an unrelated container on 9222 (see
|
|
416
|
-
// probeLocalChromeDebugger's comment), so erroring out on the very first conflict there would make
|
|
417
|
-
// `aivin browser` unusable out of the box for anyone running that stack, every single time.
|
|
418
|
-
const explicitPort = options.debugPort !== undefined;
|
|
419
|
-
const candidatePorts = explicitPort ? [Number(options.debugPort)] : [CHROME_DEBUG_PORT, 9223, 9224, 9225];
|
|
420
|
-
|
|
421
|
-
let debugPort;
|
|
422
|
-
let chromeWsUrl;
|
|
423
|
-
const triedConflicts = [];
|
|
424
|
-
for (const port of candidatePorts) {
|
|
425
|
-
const probed = await probeLocalChromeDebugger(port);
|
|
426
|
-
if (probed.wsUrl && preferredId && probed.browserId !== preferredId) {
|
|
427
|
-
// Something's already listening, but it's the OTHER browser than what --browser asked for -
|
|
428
|
-
// using it silently would drive the wrong profile (wrong cookies/logins), so this has to be a
|
|
429
|
-
// hard error rather than a best-effort fallback, even mid auto-retry.
|
|
430
|
-
throw new Error(
|
|
431
|
-
`--browser ${preferredId} was requested, but the browser already listening on port ${port} is ${probed.browserId} instead. ` +
|
|
432
|
-
`Close it and relaunch ${preferredId} with --remote-debugging-port=${port}, or use --debug-port to point at a different port.`,
|
|
433
|
-
);
|
|
434
|
-
}
|
|
435
|
-
if (probed.wsUrl) { debugPort = port; chromeWsUrl = probed.wsUrl; break; }
|
|
436
|
-
if (probed.conflict) { triedConflicts.push(`${port} (${probed.conflict})`); continue; }
|
|
437
|
-
debugPort = port; // free port, nothing answering at all - safe to launch here
|
|
438
|
-
break;
|
|
439
|
-
}
|
|
440
|
-
if (debugPort === undefined) {
|
|
441
|
-
throw new Error(
|
|
442
|
-
`${explicitPort ? 'Requested' : 'All of the usual'} debug port${candidatePorts.length > 1 ? 's are' : ' is'} already in use by something else, not Chrome/Edge: ${triedConflicts.join(', ')}. ` +
|
|
443
|
-
`Free one of them, or pass --debug-port <port> to use a specific one.`,
|
|
444
|
-
);
|
|
445
|
-
}
|
|
446
|
-
|
|
447
|
-
if (!chromeWsUrl) {
|
|
448
|
-
// Safe to always auto-launch now (unlike an earlier version of this): this opens AIVIN_BROWSER_
|
|
449
|
-
// PROFILE_DIR, a profile dedicated to `aivin browser` that's never the user's real daily-driver
|
|
450
|
-
// browser, so there's no risk of colliding with (or having to close) whatever they're already
|
|
451
|
-
// running elsewhere.
|
|
452
|
-
try {
|
|
453
|
-
chromeWsUrl = await launchLocalChromeWithDebugging(debugPort, preferredId);
|
|
454
|
-
} catch (error) {
|
|
455
|
-
printChromeLaunchHelp(debugPort, preferredId);
|
|
456
|
-
throw error;
|
|
457
|
-
}
|
|
458
|
-
}
|
|
459
|
-
|
|
460
|
-
const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
|
|
461
|
-
const agentId = options.agent || (await resolveOrCreateBrowserAgent(serverUrl, authHeaders, workspace));
|
|
462
|
-
|
|
463
|
-
console.log(chalk.blue('🌐 AI Browser (local - your own browser):'), mission);
|
|
464
|
-
console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
|
|
465
|
-
|
|
466
|
-
// Retry the local tunnel on an UNEXPECTED drop (flaky WiFi) - checkpoint-resume already exists
|
|
467
|
-
// server-side (AIBrowserCheckpointService, matches on tenant + exact mission text), so re-firing
|
|
468
|
-
// the SAME mission through a fresh tunnel just continues where it left off instead of restarting.
|
|
469
|
-
// Only worth doing when we're actually watching (options.watch !== false) - without the log
|
|
470
|
-
// stream there's no reliable signal for "did the mission already finish" vs "tunnel just dropped",
|
|
471
|
-
// so a single un-retried attempt (old behavior) is what happens when watch is disabled.
|
|
472
|
-
const MAX_TUNNEL_RETRIES = 3;
|
|
473
|
-
let interrupted = false;
|
|
474
|
-
let terminalReason; // 'success' | 'failed' | undefined (still unresolved / gave up watching)
|
|
475
|
-
let attempt = 0;
|
|
476
|
-
|
|
477
|
-
while (!interrupted) {
|
|
478
|
-
attempt++;
|
|
479
|
-
if (attempt > 1) {
|
|
480
|
-
// Chrome's CDP websocket URL can go stale after a drop, and the browser itself may have
|
|
481
|
-
// closed too (user closed the window) - re-probe rather than blindly reusing the old URL.
|
|
482
|
-
const reprobe = await probeLocalChromeDebugger(debugPort);
|
|
483
|
-
if (!reprobe.wsUrl) {
|
|
484
|
-
console.log(chalk.red(`\n❌ Mất kết nối và không tìm lại được ${preferredId || 'Chrome/Edge'} đang chạy ở cổng ${debugPort} - trình duyệt có thể đã bị đóng. Dừng lại đây (mission có thể vẫn đang chạy trên server - kiểm tra lại bằng \`aivin browser --view\` hoặc chạy lại lệnh này).`));
|
|
485
|
-
break;
|
|
486
|
-
}
|
|
487
|
-
chromeWsUrl = reprobe.wsUrl;
|
|
488
|
-
console.log(chalk.yellow(`\n🔄 Tunnel bị rớt kết nối bất ngờ - đang thử lại (lần ${attempt - 1}/${MAX_TUNNEL_RETRIES})...`));
|
|
489
|
-
}
|
|
490
|
-
|
|
491
|
-
let unexpectedDrop = false;
|
|
492
|
-
const tunnel = openLocalTunnel(serverUrl, apiKey, chromeWsUrl, {
|
|
493
|
-
onUnexpectedClose: () => { unexpectedDrop = true; },
|
|
494
|
-
});
|
|
495
|
-
try {
|
|
496
|
-
await tunnel.ready;
|
|
497
|
-
} catch (error) {
|
|
498
|
-
tunnel.close();
|
|
499
|
-
if (attempt > MAX_TUNNEL_RETRIES) throw new Error(`Could not open the local browser tunnel: ${error.message}`, { cause: error });
|
|
500
|
-
console.log(chalk.yellow(`\n⚠️ Không mở được tunnel (${error.message}) - đang thử lại (lần ${attempt}/${MAX_TUNNEL_RETRIES})...`));
|
|
501
|
-
continue;
|
|
502
|
-
}
|
|
503
|
-
|
|
504
|
-
const sessionId = `browser-cli-${randomUUID()}`;
|
|
505
|
-
console.log(chalk.gray(` Session: ${sessionId}`));
|
|
506
|
-
|
|
507
|
-
// Ctrl+C: request cooperative cancellation (same mechanism sdk.browser.cancel() uses - checked
|
|
508
|
-
// between agentic-loop steps, can't interrupt a step already in flight) AND close the tunnel.
|
|
509
|
-
// Closing the tunnel alone isn't enough to stop a mission stuck in an LLM call that hasn't
|
|
510
|
-
// touched the browser connection yet (confirmed while testing this) - the cancel request is what
|
|
511
|
-
// actually gets it to stop at its next chance to check. The tab this mission was using stays open
|
|
512
|
-
// either way - never force-closed, since local mode is explicitly "your own browser, your tabs".
|
|
513
|
-
const onSigint = () => {
|
|
514
|
-
if (interrupted) return;
|
|
515
|
-
interrupted = true;
|
|
516
|
-
console.log(chalk.yellow('\n\n⏹ Stopping... (requesting cancellation - may take a moment, one agentic step at a time)'));
|
|
517
|
-
requestBrowserCancel(serverUrl, authHeaders).catch((e) =>
|
|
518
|
-
console.log(chalk.red(` ⚠️ Cancellation request failed to send (${e.message}) - the mission may keep running.`)),
|
|
519
|
-
);
|
|
520
|
-
tunnel.close();
|
|
521
|
-
console.log(chalk.gray(' The tab this mission was using is still open in your browser - close it yourself if you don\'t need it.'));
|
|
522
|
-
};
|
|
523
|
-
process.on('SIGINT', onSigint);
|
|
524
|
-
|
|
525
|
-
// Fired concurrently, not sequentially - execute-interactive is a SYNCHRONOUS call (blocks until
|
|
526
|
-
// the mission ends), so the log watcher has to already be listening before/as it fires, not after.
|
|
527
|
-
const missionPromise = axios.post(
|
|
528
|
-
// `/plugins/` prefix: OfficialPluginModules.ts registers every official plugin module (incl.
|
|
529
|
-
// AIBrowserModule) via RouterModule.register({ path: 'plugins', ... }) - easy to miss, confirmed
|
|
530
|
-
// by testing directly against the API (plain /ai-browser/... 404s, /plugins/ai-browser/... works).
|
|
531
|
-
`${serverUrl}/plugins/ai-browser/execute-interactive`,
|
|
532
|
-
{
|
|
533
|
-
mission,
|
|
534
|
-
workspace_id: workspace.id || workspace._id,
|
|
535
|
-
agent_id: agentId,
|
|
536
|
-
session_id: sessionId,
|
|
537
|
-
data: { __local_tunnel_id: tunnel.tunnelId, start_url: options.url || guessStartUrl(mission) },
|
|
538
|
-
},
|
|
539
|
-
authHeaders,
|
|
540
|
-
);
|
|
541
|
-
const watchPromise = options.watch !== false
|
|
542
|
-
? watchBrowserMission(serverUrl, apiKey, sessionId, tenantClient, { openViewerOnHIL: false })
|
|
543
|
-
: Promise.resolve(undefined);
|
|
544
|
-
|
|
545
|
-
try {
|
|
546
|
-
// execute-interactive responds immediately (fire-and-forget - see AIBrowserController.ts's
|
|
547
|
-
// comment on why: a synchronous wait here would hit the same Cloudflare 524 the gRPC
|
|
548
|
-
// browser.run() call did). The REAL outcome is whatever the log stream above already printed
|
|
549
|
-
// (ai_browser.success/failed) - this Promise.all is just making sure both sides are done.
|
|
550
|
-
const [, watchReason] = await Promise.all([missionPromise, watchPromise]);
|
|
551
|
-
terminalReason = watchReason;
|
|
552
|
-
} catch (error) {
|
|
553
|
-
if (!interrupted) {
|
|
554
|
-
const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
|
|
555
|
-
throw new Error(`AI Browser mission failed to start: ${message}`, { cause: error });
|
|
556
|
-
}
|
|
557
|
-
} finally {
|
|
558
|
-
process.off('SIGINT', onSigint);
|
|
559
|
-
tunnel.close();
|
|
560
|
-
}
|
|
561
|
-
|
|
562
|
-
if (interrupted) break;
|
|
563
|
-
if (terminalReason === 'success' || terminalReason === 'failed') break; // genuine mission outcome - done
|
|
564
|
-
// options.watch === false (no signal at all) or watch gave up on its own (idle/connect_error,
|
|
565
|
-
// NOT a tunnel drop) - neither is worth blindly retrying; only retry on a confirmed tunnel drop.
|
|
566
|
-
if (!unexpectedDrop) break;
|
|
567
|
-
if (attempt > MAX_TUNNEL_RETRIES) {
|
|
568
|
-
console.log(chalk.red(`\n❌ Đã thử lại ${MAX_TUNNEL_RETRIES} lần nhưng tunnel vẫn liên tục rớt kết nối - dừng theo dõi. Mission có thể vẫn đang chạy trên server.`));
|
|
569
|
-
break;
|
|
570
|
-
}
|
|
571
|
-
}
|
|
572
|
-
|
|
573
|
-
if (!interrupted && (terminalReason === 'success' || terminalReason === 'failed')) {
|
|
574
|
-
console.log(chalk.gray('\n Done - see the log lines above for the outcome, and your own browser for the result.'));
|
|
575
|
-
}
|
|
576
|
-
}
|
|
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(
|
|
582
|
-
}
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
const
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
}
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
|
|
645
|
-
}
|
|
646
|
-
|
|
647
|
-
|
|
648
|
-
|
|
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
|
+
}
|
|
340
|
+
}
|
|
341
|
+
throw new Error(`${browser.name} launched but its debug port never came up in time.`);
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
/**
|
|
345
|
+
* Opens 2 raw WebSocket connections - one to the backend's relay (authenticated by API key), one
|
|
346
|
+
* to the user's own local Chrome's real CDP endpoint - and pipes frames both directions verbatim.
|
|
347
|
+
* `close()` disconnects both sides; the user's actual browser window is never touched beyond this
|
|
348
|
+
* one CDP connection, closing the tunnel just detaches Puppeteer server-side.
|
|
349
|
+
*
|
|
350
|
+
* `onUnexpectedClose(side)` fires when either leg drops WITHOUT `close()` having been called first
|
|
351
|
+
* (side is 'backend' or 'chrome') - lets the caller distinguish "network/tunnel died mid-mission"
|
|
352
|
+
* from "we're done, tearing down deliberately" (Ctrl+C, mission finished) without guessing from
|
|
353
|
+
* timing alone. Never fires after a deliberate `close()`.
|
|
354
|
+
*/
|
|
355
|
+
export function openLocalTunnel(serverUrl, apiKey, chromeWsUrl, { onUnexpectedClose } = {}) {
|
|
356
|
+
const tunnelId = randomUUID();
|
|
357
|
+
const relayUrl = `${serverUrl.replace(/^http/, 'ws')}/browser-tunnel/external?tunnel_id=${tunnelId}`;
|
|
358
|
+
|
|
359
|
+
// API key goes in a header, NOT a `?token=` query param - WS upgrade URLs are exactly the kind
|
|
360
|
+
// of thing that ends up verbatim in reverse-proxy/CDN/access logs, unlike headers.
|
|
361
|
+
const toBackend = new WSClient(relayUrl, { headers: { Authorization: `Bearer ${apiKey || ''}` } });
|
|
362
|
+
const toChrome = new WSClient(chromeWsUrl);
|
|
363
|
+
|
|
364
|
+
let deliberateClose = false;
|
|
365
|
+
|
|
366
|
+
const relay = (from, to, side) => {
|
|
367
|
+
from.on('message', (data, isBinary) => {
|
|
368
|
+
if (to.readyState === WSClient.OPEN) to.send(data, { binary: isBinary });
|
|
369
|
+
});
|
|
370
|
+
from.on('close', () => {
|
|
371
|
+
if (to.readyState === WSClient.OPEN) to.close();
|
|
372
|
+
if (!deliberateClose) onUnexpectedClose?.(side);
|
|
373
|
+
});
|
|
374
|
+
from.on('error', () => {
|
|
375
|
+
if (to.readyState === WSClient.OPEN) to.close();
|
|
376
|
+
if (!deliberateClose) onUnexpectedClose?.(side);
|
|
377
|
+
});
|
|
378
|
+
};
|
|
379
|
+
relay(toBackend, toChrome, 'backend');
|
|
380
|
+
relay(toChrome, toBackend, 'chrome');
|
|
381
|
+
|
|
382
|
+
const ready = Promise.all([
|
|
383
|
+
new Promise((resolve, reject) => {
|
|
384
|
+
toBackend.once('open', resolve);
|
|
385
|
+
toBackend.once('error', reject);
|
|
386
|
+
}),
|
|
387
|
+
new Promise((resolve, reject) => {
|
|
388
|
+
toChrome.once('open', resolve);
|
|
389
|
+
toChrome.once('error', reject);
|
|
390
|
+
}),
|
|
391
|
+
]);
|
|
392
|
+
|
|
393
|
+
const close = () => {
|
|
394
|
+
deliberateClose = true;
|
|
395
|
+
try { toBackend.close(); } catch { /* already closed */ }
|
|
396
|
+
try { toChrome.close(); } catch { /* already closed */ }
|
|
397
|
+
};
|
|
398
|
+
|
|
399
|
+
return { tunnelId, ready, close };
|
|
400
|
+
}
|
|
401
|
+
|
|
402
|
+
export async function runBrowserMissionLocal(mission, options) {
|
|
403
|
+
const serverUrl = missionServerUrl();
|
|
404
|
+
const apiKey = process.env.API_KEY;
|
|
405
|
+
const authHeaders = missionAuthHeaders();
|
|
406
|
+
const tenantClient = parseApiKeyClient(apiKey || '') || 'unknown';
|
|
407
|
+
|
|
408
|
+
const preferredId = options.browser ? String(options.browser).toLowerCase() : undefined;
|
|
409
|
+
if (preferredId && preferredId !== 'edge' && preferredId !== 'chrome') {
|
|
410
|
+
throw new Error(`--browser must be "edge" or "chrome", got "${options.browser}".`);
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// --debug-port pins an exact port (strict - errors immediately if it's taken by something else).
|
|
414
|
+
// Without it, try the conventional 9222 first, then a few neighbors - confirmed needed for real:
|
|
415
|
+
// this project's OWN local dev stack publishes an unrelated container on 9222 (see
|
|
416
|
+
// probeLocalChromeDebugger's comment), so erroring out on the very first conflict there would make
|
|
417
|
+
// `aivin browser` unusable out of the box for anyone running that stack, every single time.
|
|
418
|
+
const explicitPort = options.debugPort !== undefined;
|
|
419
|
+
const candidatePorts = explicitPort ? [Number(options.debugPort)] : [CHROME_DEBUG_PORT, 9223, 9224, 9225];
|
|
420
|
+
|
|
421
|
+
let debugPort;
|
|
422
|
+
let chromeWsUrl;
|
|
423
|
+
const triedConflicts = [];
|
|
424
|
+
for (const port of candidatePorts) {
|
|
425
|
+
const probed = await probeLocalChromeDebugger(port);
|
|
426
|
+
if (probed.wsUrl && preferredId && probed.browserId !== preferredId) {
|
|
427
|
+
// Something's already listening, but it's the OTHER browser than what --browser asked for -
|
|
428
|
+
// using it silently would drive the wrong profile (wrong cookies/logins), so this has to be a
|
|
429
|
+
// hard error rather than a best-effort fallback, even mid auto-retry.
|
|
430
|
+
throw new Error(
|
|
431
|
+
`--browser ${preferredId} was requested, but the browser already listening on port ${port} is ${probed.browserId} instead. ` +
|
|
432
|
+
`Close it and relaunch ${preferredId} with --remote-debugging-port=${port}, or use --debug-port to point at a different port.`,
|
|
433
|
+
);
|
|
434
|
+
}
|
|
435
|
+
if (probed.wsUrl) { debugPort = port; chromeWsUrl = probed.wsUrl; break; }
|
|
436
|
+
if (probed.conflict) { triedConflicts.push(`${port} (${probed.conflict})`); continue; }
|
|
437
|
+
debugPort = port; // free port, nothing answering at all - safe to launch here
|
|
438
|
+
break;
|
|
439
|
+
}
|
|
440
|
+
if (debugPort === undefined) {
|
|
441
|
+
throw new Error(
|
|
442
|
+
`${explicitPort ? 'Requested' : 'All of the usual'} debug port${candidatePorts.length > 1 ? 's are' : ' is'} already in use by something else, not Chrome/Edge: ${triedConflicts.join(', ')}. ` +
|
|
443
|
+
`Free one of them, or pass --debug-port <port> to use a specific one.`,
|
|
444
|
+
);
|
|
445
|
+
}
|
|
446
|
+
|
|
447
|
+
if (!chromeWsUrl) {
|
|
448
|
+
// Safe to always auto-launch now (unlike an earlier version of this): this opens AIVIN_BROWSER_
|
|
449
|
+
// PROFILE_DIR, a profile dedicated to `aivin browser` that's never the user's real daily-driver
|
|
450
|
+
// browser, so there's no risk of colliding with (or having to close) whatever they're already
|
|
451
|
+
// running elsewhere.
|
|
452
|
+
try {
|
|
453
|
+
chromeWsUrl = await launchLocalChromeWithDebugging(debugPort, preferredId);
|
|
454
|
+
} catch (error) {
|
|
455
|
+
printChromeLaunchHelp(debugPort, preferredId);
|
|
456
|
+
throw error;
|
|
457
|
+
}
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
|
|
461
|
+
const agentId = options.agent || (await resolveOrCreateBrowserAgent(serverUrl, authHeaders, workspace));
|
|
462
|
+
|
|
463
|
+
console.log(chalk.blue('🌐 AI Browser (local - your own browser):'), mission);
|
|
464
|
+
console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
|
|
465
|
+
|
|
466
|
+
// Retry the local tunnel on an UNEXPECTED drop (flaky WiFi) - checkpoint-resume already exists
|
|
467
|
+
// server-side (AIBrowserCheckpointService, matches on tenant + exact mission text), so re-firing
|
|
468
|
+
// the SAME mission through a fresh tunnel just continues where it left off instead of restarting.
|
|
469
|
+
// Only worth doing when we're actually watching (options.watch !== false) - without the log
|
|
470
|
+
// stream there's no reliable signal for "did the mission already finish" vs "tunnel just dropped",
|
|
471
|
+
// so a single un-retried attempt (old behavior) is what happens when watch is disabled.
|
|
472
|
+
const MAX_TUNNEL_RETRIES = 3;
|
|
473
|
+
let interrupted = false;
|
|
474
|
+
let terminalReason; // 'success' | 'failed' | undefined (still unresolved / gave up watching)
|
|
475
|
+
let attempt = 0;
|
|
476
|
+
|
|
477
|
+
while (!interrupted) {
|
|
478
|
+
attempt++;
|
|
479
|
+
if (attempt > 1) {
|
|
480
|
+
// Chrome's CDP websocket URL can go stale after a drop, and the browser itself may have
|
|
481
|
+
// closed too (user closed the window) - re-probe rather than blindly reusing the old URL.
|
|
482
|
+
const reprobe = await probeLocalChromeDebugger(debugPort);
|
|
483
|
+
if (!reprobe.wsUrl) {
|
|
484
|
+
console.log(chalk.red(`\n❌ Mất kết nối và không tìm lại được ${preferredId || 'Chrome/Edge'} đang chạy ở cổng ${debugPort} - trình duyệt có thể đã bị đóng. Dừng lại đây (mission có thể vẫn đang chạy trên server - kiểm tra lại bằng \`aivin browser --view\` hoặc chạy lại lệnh này).`));
|
|
485
|
+
break;
|
|
486
|
+
}
|
|
487
|
+
chromeWsUrl = reprobe.wsUrl;
|
|
488
|
+
console.log(chalk.yellow(`\n🔄 Tunnel bị rớt kết nối bất ngờ - đang thử lại (lần ${attempt - 1}/${MAX_TUNNEL_RETRIES})...`));
|
|
489
|
+
}
|
|
490
|
+
|
|
491
|
+
let unexpectedDrop = false;
|
|
492
|
+
const tunnel = openLocalTunnel(serverUrl, apiKey, chromeWsUrl, {
|
|
493
|
+
onUnexpectedClose: () => { unexpectedDrop = true; },
|
|
494
|
+
});
|
|
495
|
+
try {
|
|
496
|
+
await tunnel.ready;
|
|
497
|
+
} catch (error) {
|
|
498
|
+
tunnel.close();
|
|
499
|
+
if (attempt > MAX_TUNNEL_RETRIES) throw new Error(`Could not open the local browser tunnel: ${error.message}`, { cause: error });
|
|
500
|
+
console.log(chalk.yellow(`\n⚠️ Không mở được tunnel (${error.message}) - đang thử lại (lần ${attempt}/${MAX_TUNNEL_RETRIES})...`));
|
|
501
|
+
continue;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
const sessionId = `browser-cli-${randomUUID()}`;
|
|
505
|
+
console.log(chalk.gray(` Session: ${sessionId}`));
|
|
506
|
+
|
|
507
|
+
// Ctrl+C: request cooperative cancellation (same mechanism sdk.browser.cancel() uses - checked
|
|
508
|
+
// between agentic-loop steps, can't interrupt a step already in flight) AND close the tunnel.
|
|
509
|
+
// Closing the tunnel alone isn't enough to stop a mission stuck in an LLM call that hasn't
|
|
510
|
+
// touched the browser connection yet (confirmed while testing this) - the cancel request is what
|
|
511
|
+
// actually gets it to stop at its next chance to check. The tab this mission was using stays open
|
|
512
|
+
// either way - never force-closed, since local mode is explicitly "your own browser, your tabs".
|
|
513
|
+
const onSigint = () => {
|
|
514
|
+
if (interrupted) return;
|
|
515
|
+
interrupted = true;
|
|
516
|
+
console.log(chalk.yellow('\n\n⏹ Stopping... (requesting cancellation - may take a moment, one agentic step at a time)'));
|
|
517
|
+
requestBrowserCancel(serverUrl, authHeaders, { sessionId }).catch((e) =>
|
|
518
|
+
console.log(chalk.red(` ⚠️ Cancellation request failed to send (${e.message}) - the mission may keep running.`)),
|
|
519
|
+
);
|
|
520
|
+
tunnel.close();
|
|
521
|
+
console.log(chalk.gray(' The tab this mission was using is still open in your browser - close it yourself if you don\'t need it.'));
|
|
522
|
+
};
|
|
523
|
+
process.on('SIGINT', onSigint);
|
|
524
|
+
|
|
525
|
+
// Fired concurrently, not sequentially - execute-interactive is a SYNCHRONOUS call (blocks until
|
|
526
|
+
// the mission ends), so the log watcher has to already be listening before/as it fires, not after.
|
|
527
|
+
const missionPromise = axios.post(
|
|
528
|
+
// `/plugins/` prefix: OfficialPluginModules.ts registers every official plugin module (incl.
|
|
529
|
+
// AIBrowserModule) via RouterModule.register({ path: 'plugins', ... }) - easy to miss, confirmed
|
|
530
|
+
// by testing directly against the API (plain /ai-browser/... 404s, /plugins/ai-browser/... works).
|
|
531
|
+
`${serverUrl}/plugins/ai-browser/execute-interactive`,
|
|
532
|
+
{
|
|
533
|
+
mission,
|
|
534
|
+
workspace_id: workspace.id || workspace._id,
|
|
535
|
+
agent_id: agentId,
|
|
536
|
+
session_id: sessionId,
|
|
537
|
+
data: { __local_tunnel_id: tunnel.tunnelId, start_url: options.url || guessStartUrl(mission) },
|
|
538
|
+
},
|
|
539
|
+
authHeaders,
|
|
540
|
+
);
|
|
541
|
+
const watchPromise = options.watch !== false
|
|
542
|
+
? watchBrowserMission(serverUrl, apiKey, sessionId, tenantClient, { openViewerOnHIL: false, sessionId })
|
|
543
|
+
: Promise.resolve(undefined);
|
|
544
|
+
|
|
545
|
+
try {
|
|
546
|
+
// execute-interactive responds immediately (fire-and-forget - see AIBrowserController.ts's
|
|
547
|
+
// comment on why: a synchronous wait here would hit the same Cloudflare 524 the gRPC
|
|
548
|
+
// browser.run() call did). The REAL outcome is whatever the log stream above already printed
|
|
549
|
+
// (ai_browser.success/failed) - this Promise.all is just making sure both sides are done.
|
|
550
|
+
const [, watchReason] = await Promise.all([missionPromise, watchPromise]);
|
|
551
|
+
terminalReason = watchReason;
|
|
552
|
+
} catch (error) {
|
|
553
|
+
if (!interrupted) {
|
|
554
|
+
const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
|
|
555
|
+
throw new Error(`AI Browser mission failed to start: ${message}`, { cause: error });
|
|
556
|
+
}
|
|
557
|
+
} finally {
|
|
558
|
+
process.off('SIGINT', onSigint);
|
|
559
|
+
tunnel.close();
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
if (interrupted) break;
|
|
563
|
+
if (terminalReason === 'success' || terminalReason === 'failed') break; // genuine mission outcome - done
|
|
564
|
+
// options.watch === false (no signal at all) or watch gave up on its own (idle/connect_error,
|
|
565
|
+
// NOT a tunnel drop) - neither is worth blindly retrying; only retry on a confirmed tunnel drop.
|
|
566
|
+
if (!unexpectedDrop) break;
|
|
567
|
+
if (attempt > MAX_TUNNEL_RETRIES) {
|
|
568
|
+
console.log(chalk.red(`\n❌ Đã thử lại ${MAX_TUNNEL_RETRIES} lần nhưng tunnel vẫn liên tục rớt kết nối - dừng theo dõi. Mission có thể vẫn đang chạy trên server.`));
|
|
569
|
+
break;
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
|
|
573
|
+
if (!interrupted && (terminalReason === 'success' || terminalReason === 'failed')) {
|
|
574
|
+
console.log(chalk.gray('\n Done - see the log lines above for the outcome, and your own browser for the result.'));
|
|
575
|
+
}
|
|
576
|
+
}
|
|
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, { sessionId, threadId } = {}) {
|
|
581
|
+
await axios.post(
|
|
582
|
+
`${serverUrl}/plugins/ai-browser/cancel`,
|
|
583
|
+
{
|
|
584
|
+
...(sessionId ? { session_id: sessionId } : {}),
|
|
585
|
+
...(threadId ? { thread_id: threadId } : {}),
|
|
586
|
+
},
|
|
587
|
+
authHeaders,
|
|
588
|
+
);
|
|
589
|
+
}
|
|
590
|
+
|
|
591
|
+
export async function runBrowserMissionRemote(mission, options) {
|
|
592
|
+
const serverUrl = missionServerUrl();
|
|
593
|
+
const apiKey = process.env.API_KEY;
|
|
594
|
+
const authHeaders = missionAuthHeaders();
|
|
595
|
+
const tenantClient = parseApiKeyClient(apiKey || '') || 'unknown';
|
|
596
|
+
|
|
597
|
+
const workspace = await resolveWorkspace(serverUrl, authHeaders, options.workspace);
|
|
598
|
+
// Same interactive resolver `aivin do` uses (not the throw-if-missing resolveAgentId) - a fresh
|
|
599
|
+
// workspace commonly has zero agents installed yet, and this offers to search/install/create one
|
|
600
|
+
// instead of just failing. AI Browser itself is always used as the TOOL; the agent is only the
|
|
601
|
+
// identity/session context the mission (and HIL suspend/resume) runs under.
|
|
602
|
+
const agent = await resolveAgentInteractive(serverUrl, authHeaders, workspace, options.agent);
|
|
603
|
+
const agentId = agent.id || agent.agent_id;
|
|
604
|
+
|
|
605
|
+
console.log(chalk.blue('🌐 AI Browser (remote - server-side browser):'), mission);
|
|
606
|
+
console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id} Agent: ${agent.nickname || agent.name || agentId}`));
|
|
607
|
+
|
|
608
|
+
let response;
|
|
609
|
+
try {
|
|
610
|
+
response = await axios.post(
|
|
611
|
+
`${serverUrl}/agent/start-work`,
|
|
612
|
+
{
|
|
613
|
+
prompt: BROWSER_MISSION_PREFIX + mission,
|
|
614
|
+
mission: BROWSER_MISSION_PREFIX + mission,
|
|
615
|
+
workspace_id: workspace.id || workspace._id,
|
|
616
|
+
agent_id: agentId,
|
|
617
|
+
project_id: options.project,
|
|
618
|
+
},
|
|
619
|
+
authHeaders,
|
|
620
|
+
);
|
|
621
|
+
} catch (error) {
|
|
622
|
+
const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
|
|
623
|
+
throw new Error(`Failed to start AI Browser mission: ${message}`, { cause: error });
|
|
624
|
+
}
|
|
625
|
+
|
|
626
|
+
const result = response.data ?? {};
|
|
627
|
+
if (result.success === false) {
|
|
628
|
+
throw new Error(result.message || 'Failed to start AI Browser mission');
|
|
629
|
+
}
|
|
630
|
+
const threadId = result.data?.thread_id;
|
|
631
|
+
console.log(chalk.gray(` Thread: ${threadId || 'unknown'}`));
|
|
632
|
+
|
|
633
|
+
// Same cooperative-cancel wiring as the local-mode path above (requestBrowserCancel is
|
|
634
|
+
// tenant-scoped, not session/thread-scoped, so it applies here unchanged) - without this, Ctrl+C
|
|
635
|
+
// only stopped streamBrowserMissionLog's own SIGINT handler, which just disconnects the log
|
|
636
|
+
// socket and returns; the mission itself kept running server-side with nothing telling it to stop.
|
|
637
|
+
let interrupted = false;
|
|
638
|
+
const onSigint = () => {
|
|
639
|
+
if (interrupted) return;
|
|
640
|
+
interrupted = true;
|
|
641
|
+
console.log(chalk.yellow('\n\n⏹ Stopping... (requesting cancellation - may take a moment, one agentic step at a time)'));
|
|
642
|
+
requestBrowserCancel(serverUrl, authHeaders, { threadId }).catch((e) =>
|
|
643
|
+
console.log(chalk.red(` ⚠️ Cancellation request failed to send (${e.message}) - the mission may keep running.`)),
|
|
644
|
+
);
|
|
645
|
+
};
|
|
646
|
+
process.on('SIGINT', onSigint);
|
|
647
|
+
|
|
648
|
+
try {
|
|
649
|
+
if (options.watch !== false && threadId) {
|
|
650
|
+
await watchBrowserMission(serverUrl, apiKey, threadId, tenantClient, { threadId });
|
|
651
|
+
}
|
|
652
|
+
} finally {
|
|
653
|
+
process.off('SIGINT', onSigint);
|
|
654
|
+
}
|
|
655
|
+
}
|