@aivin-labs/cli 1.0.5 ā 1.0.11
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +288 -216
- package/bin/assets/aivin-mascot.png +0 -0
- package/bin/cli.mjs +551 -5
- package/bin/lib/browserAutomation.mjs +384 -614
- package/bin/lib/browserTui.mjs +276 -251
- package/bin/lib/cancellation.mjs +61 -0
- package/bin/lib/localBrowser.mjs +345 -0
- package/bin/lib/mcpProxy.mjs +869 -837
- package/bin/lib/missionStream.mjs +696 -691
- package/bin/lib/releaseKeys.mjs +9 -0
- package/bin/lib/remote/activityLog.mjs +68 -0
- package/bin/lib/remote/autoStart.mjs +617 -0
- package/bin/lib/remote/autoUpdate.mjs +129 -0
- package/bin/lib/remote/brand.mjs +60 -0
- package/bin/lib/remote/browserTunnel.mjs +403 -0
- package/bin/lib/remote/callLedger.mjs +134 -0
- package/bin/lib/remote/cdpPolicy.mjs +79 -0
- package/bin/lib/remote/client.mjs +808 -0
- package/bin/lib/remote/clipboard.mjs +138 -0
- package/bin/lib/remote/codingAgents.mjs +293 -0
- package/bin/lib/remote/constants.mjs +234 -0
- package/bin/lib/remote/credentials.mjs +208 -0
- package/bin/lib/remote/daemonLock.mjs +86 -0
- package/bin/lib/remote/dailyBrowser.mjs +371 -0
- package/bin/lib/remote/desktop/index.mjs +272 -0
- package/bin/lib/remote/desktop/linux.mjs +144 -0
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
- package/bin/lib/remote/desktop/mac.mjs +187 -0
- package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
- package/bin/lib/remote/desktop/strings.mjs +74 -0
- package/bin/lib/remote/desktop/traySource.mjs +527 -0
- package/bin/lib/remote/deviceMemory.mjs +246 -0
- package/bin/lib/remote/deviceProfile.mjs +142 -0
- package/bin/lib/remote/deviceWatches.mjs +138 -0
- package/bin/lib/remote/docText.mjs +117 -0
- package/bin/lib/remote/fileIndexer.mjs +399 -0
- package/bin/lib/remote/gui/index.mjs +326 -0
- package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
- package/bin/lib/remote/gui/windowsHost.mjs +109 -0
- package/bin/lib/remote/gui/windowsHostSource.mjs +1156 -0
- package/bin/lib/remote/httpTransfer.mjs +89 -0
- package/bin/lib/remote/idempotency.mjs +135 -0
- package/bin/lib/remote/keepAwake.mjs +100 -0
- package/bin/lib/remote/localConfirm.mjs +268 -0
- package/bin/lib/remote/localPolicy.mjs +256 -0
- package/bin/lib/remote/mascot/adpcm.mjs +70 -0
- package/bin/lib/remote/mascot/ask.mjs +768 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
- package/bin/lib/remote/mascot/assets.mjs +827 -0
- package/bin/lib/remote/mascot/bot.mjs +372 -0
- package/bin/lib/remote/mascot/hostSource.mjs +759 -0
- package/bin/lib/remote/mascot/hotkey.mjs +66 -0
- package/bin/lib/remote/mascot/index.mjs +493 -0
- package/bin/lib/remote/mascot/labels.mjs +82 -0
- package/bin/lib/remote/mascot/rigSource.mjs +609 -0
- package/bin/lib/remote/mascot/strings.mjs +375 -0
- package/bin/lib/remote/mascot/ui.mjs +104 -0
- package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
- package/bin/lib/remote/meeting/index.mjs +415 -0
- package/bin/lib/remote/meeting/recorder.mjs +109 -0
- package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
- package/bin/lib/remote/meeting/transcribe.mjs +259 -0
- package/bin/lib/remote/memberFsPool.mjs +134 -0
- package/bin/lib/remote/memberFsWorker.mjs +60 -0
- package/bin/lib/remote/mission.mjs +156 -0
- package/bin/lib/remote/missionQuestion.mjs +63 -0
- package/bin/lib/remote/multiUser.mjs +344 -0
- package/bin/lib/remote/netProxy.mjs +145 -0
- package/bin/lib/remote/notify.mjs +58 -0
- package/bin/lib/remote/office/index.mjs +90 -0
- package/bin/lib/remote/policyCommand.mjs +93 -0
- package/bin/lib/remote/processes.mjs +217 -0
- package/bin/lib/remote/sandbox.mjs +221 -0
- package/bin/lib/remote/schedule.mjs +213 -0
- package/bin/lib/remote/scheduler.mjs +124 -0
- package/bin/lib/remote/tabGroups.mjs +209 -0
- package/bin/lib/remote/textIndex.mjs +131 -0
- package/bin/lib/remote/tokenStore.mjs +77 -0
- package/bin/lib/remote/toolHandlers.mjs +741 -0
- package/bin/lib/remote/undoStore.mjs +242 -0
- package/bin/lib/remoteControl.mjs +26 -0
- package/bin/lib/scaffold.mjs +654 -653
- package/bin/lib/selfUpdate.mjs +71 -0
- package/bin/lib/update/binarySwap.mjs +63 -0
- package/bin/lib/update/constants.mjs +56 -0
- package/bin/lib/update/download.mjs +145 -0
- package/bin/lib/update/signature.mjs +42 -0
- package/bin/lib/update/state.mjs +205 -0
- package/bin/lib/update/versions.mjs +60 -0
- package/docs/AIVIN_MASCOT.md +116 -0
- package/docs/CLI.md +1484 -1299
- package/docs/media/aivin-mascot-states.mp4 +0 -0
- package/package.json +71 -62
|
@@ -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 {
|
|
7
|
-
import {
|
|
8
|
-
import
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
//
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
//
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
//
|
|
26
|
-
//
|
|
27
|
-
//
|
|
28
|
-
//
|
|
29
|
-
//
|
|
30
|
-
//
|
|
31
|
-
//
|
|
32
|
-
//
|
|
33
|
-
//
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
*
|
|
58
|
-
*
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
.
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
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
|
|
410
|
-
throw new Error(`--browser must be
|
|
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
|
|
414
|
-
//
|
|
415
|
-
//
|
|
416
|
-
// probeLocalChromeDebugger's comment)
|
|
417
|
-
//
|
|
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
|
|
420
|
-
|
|
421
|
-
|
|
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
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
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
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
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
|
-
|
|
190
|
+
found = await ensureAivinBrowser(preferredId || browser.id, { ports, launch: launchAllowed, log: (m) => console.log(chalk.gray(m)) });
|
|
454
191
|
} catch (error) {
|
|
455
|
-
printChromeLaunchHelp(
|
|
192
|
+
if (launchAllowed) printChromeLaunchHelp(ports[0], preferredId);
|
|
193
|
+
error.browserSetup = true;
|
|
456
194
|
throw error;
|
|
457
195
|
}
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
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
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
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
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
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
|
-
|
|
505
|
-
|
|
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
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
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
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
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
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
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
|
-
|
|
585
|
-
|
|
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
|
-
|
|
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
|
+
}
|