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