@aivin-labs/cli 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,656 @@
1
+ import chalk from 'chalk';
2
+ import { io } from 'socket.io-client';
3
+ import path from 'path';
4
+ import http from 'http';
5
+ import os from 'os';
6
+ import fs from 'fs';
7
+ import { execSync, spawn } from 'child_process';
8
+ import { fileURLToPath } from 'url';
9
+ import { dirname } from 'path';
10
+ import { openBrowser } from './auth.mjs';
11
+
12
+ const __filename = fileURLToPath(import.meta.url);
13
+ const __dirname = path.join(dirname(__filename), '..');
14
+
15
+ // Every mission/job/task run logs its progress over the same clientLog() Socket.IO channel the
16
+ // web app's chat/automation/task panels already listen on - the event name depends on which
17
+ // `execution_channel` the run is on, so we just listen on all of them and filter by thread_id.
18
+ export const MISSION_LOG_EVENTS = ['chat-log', 'agent-log', 'automation-log', 'task-agent-log'];
19
+
20
+ // The only two event_keys FlowService emits for a *whole* run finishing (not just one stage) -
21
+ // see docs/sdk/automation.md's caveats section for why there's no generic "job succeeded" signal
22
+ // beyond this on the wire.
23
+ export const MISSION_DONE_EVENT_KEYS = new Set(['flow.completed', 'flow.error', 'runner.start_failed']);
24
+
25
+ /**
26
+ * Streams realtime progress for a running mission/job/task, for a nicer `aivin do` experience than
27
+ * a bare HTTP response - connects to the same Socket.IO channel `aivin plugin logs` already uses
28
+ * (see streamPluginLogs above), no explicit subscribe call needed since clientLog() emits to the
29
+ * caller's own user room automatically. Resolves on a recognized terminal event_key, on idle
30
+ * timeout, or on Ctrl+C - whichever comes first. Never throws: a log-streaming hiccup shouldn't
31
+ * fail a command whose HTTP call already succeeded.
32
+ */
33
+ export function streamMissionLog(serverUrl, apiKey, threadId, { idleTimeoutMs = 120_000 } = {}) {
34
+ return new Promise((resolve) => {
35
+ const socket = io(serverUrl, {
36
+ auth: { token: apiKey || 'dev-token' },
37
+ transports: ['websocket'],
38
+ reconnection: true,
39
+ });
40
+
41
+ let idleTimer;
42
+ let settled = false;
43
+ const statusIcon = (status) =>
44
+ status === 'error'
45
+ ? chalk.red('✗')
46
+ : status === 'success'
47
+ ? chalk.green('✓')
48
+ : status === 'warning'
49
+ ? chalk.yellow('!')
50
+ : chalk.gray('·');
51
+
52
+ const stop = () => {
53
+ if (settled) return;
54
+ settled = true;
55
+ clearTimeout(idleTimer);
56
+ socket.disconnect();
57
+ process.off('SIGINT', stop);
58
+ resolve();
59
+ };
60
+
61
+ const bumpIdleTimer = () => {
62
+ clearTimeout(idleTimer);
63
+ idleTimer = setTimeout(() => {
64
+ console.log(
65
+ chalk.gray(
66
+ `\n(no activity for ${Math.round(idleTimeoutMs / 1000)}s - stopped watching; the run may still be going in the background)`,
67
+ ),
68
+ );
69
+ stop();
70
+ }, idleTimeoutMs);
71
+ };
72
+
73
+ process.on('SIGINT', stop);
74
+
75
+ socket.on('connect_error', (error) => {
76
+ console.log(chalk.yellow(`⚠️ Couldn't watch live progress (${error.message}) - the run continues regardless.`));
77
+ stop();
78
+ });
79
+
80
+ for (const eventName of MISSION_LOG_EVENTS) {
81
+ socket.on(eventName, (payload) => {
82
+ if (!payload || payload.thread_id !== threadId) return;
83
+ bumpIdleTimer();
84
+ const time = new Date(payload.timestamp || Date.now()).toLocaleTimeString();
85
+ const label = payload.event_key || eventName;
86
+ console.log(
87
+ `${chalk.gray(`[${time}]`)} ${statusIcon(payload.status)} ${chalk.gray(label)} ${payload.message || ''}`.trimEnd(),
88
+ );
89
+ if (MISSION_DONE_EVENT_KEYS.has(payload.event_key)) stop();
90
+ });
91
+ }
92
+
93
+ console.log(chalk.gray(`📡 Watching live progress for ${threadId}... (Ctrl+C to stop watching - the run keeps going either way)\n`));
94
+ bumpIdleTimer();
95
+ });
96
+ }
97
+
98
+ // ── `aivin browser` - dedicated AI Browser trigger with a real interactive viewer for HIL ──────
99
+ //
100
+ // Unlike `sdk.browser.run()`/`runStream()` (code-plugin escape hatch, deliberately refuses to
101
+ // suspend on HIL - see docs/sdk/browser.md), this goes through the SAME `/agent/start-work` path
102
+ // `aivin do` uses, because that's the only trigger path wired to the real BullMQ suspend/resume
103
+ // plumbing (`PluginBridge.trigger()`) - `/plugins/execute` (what `aivin plugin trigger` calls)
104
+ // does NOT catch HilSuspendSignal at all and would just 500 on a mission that needs a human.
105
+ // The mission prompt is prefixed to bias the agent's own NLU tool-selection toward AI Browser
106
+ // specifically (not a hard guarantee - there's no "force this exact tool" param exposed on
107
+ // start-work today - but reliable in practice for an unambiguous browser-shaped mission).
108
+ export const BROWSER_MISSION_PREFIX =
109
+ 'Use the AI Browser tool (official.ai_browser) to accomplish the following mission directly - do not just describe how, actually browse: ';
110
+
111
+ /**
112
+ * Self-contained viewer page: connects to the SAME Socket.IO channel the web app's HIL screencast
113
+ * panel uses (AIBrowserGateway/AIBrowserScreencastService), renders the live CDP frame stream
114
+ * fullscreen on a <canvas>, and relays mouse/keyboard back as `browser:click`/`type`/`scroll`/...
115
+ * - the exact same wire protocol, just a purpose-built fullscreen client instead of the chat UI's
116
+ * embedded panel. `token`/`client` are injected server-side (this file is generated fresh per
117
+ * `aivin browser` run, never written to disk) - not exposed via query string, which would leak
118
+ * into shell history/proxy logs/browser history.
119
+ */
120
+ export function browserViewerHtml({ serverUrl, apiKey, tenantClient }) {
121
+ return `<!doctype html>
122
+ <html>
123
+ <head>
124
+ <meta charset="utf-8">
125
+ <title>aivin browser - live session</title>
126
+ <style>
127
+ html, body { margin: 0; padding: 0; width: 100%; height: 100%; background: #111; overflow: hidden; }
128
+ #status { position: fixed; top: 0; left: 0; right: 0; padding: 8px 14px; background: rgba(0,0,0,.7);
129
+ color: #eee; font: 13px/1.4 -apple-system, Segoe UI, sans-serif; z-index: 10; display: flex;
130
+ justify-content: space-between; align-items: center; }
131
+ #status button { background: #2563eb; color: #fff; border: none; padding: 6px 14px; border-radius: 6px;
132
+ font-size: 13px; cursor: pointer; }
133
+ #status button:hover { background: #1d4ed8; }
134
+ #stage { position: fixed; top: 0; left: 0; width: 100%; height: 100%; display: flex;
135
+ align-items: center; justify-content: center; }
136
+ canvas { cursor: default; box-shadow: 0 0 40px rgba(0,0,0,.6); }
137
+ #waiting { color: #888; font: 15px -apple-system, Segoe UI, sans-serif; text-align: center; }
138
+ </style>
139
+ </head>
140
+ <body>
141
+ <div id="status">
142
+ <span id="statusText">Đang kết nối...</span>
143
+ <button id="doneBtn" style="display:none">✅ Xong - tiếp tục mission</button>
144
+ </div>
145
+ <div id="stage"><div id="waiting">Đang chờ mission mở phiên tương tác (HIL)...</div></div>
146
+ <script src="https://cdn.socket.io/4.7.5/socket.io.min.js"></script>
147
+ <script>
148
+ (function () {
149
+ const serverUrl = ${JSON.stringify(serverUrl)};
150
+ const apiKey = ${JSON.stringify(apiKey)};
151
+ const tenantClient = ${JSON.stringify(tenantClient)};
152
+ const statusText = document.getElementById('statusText');
153
+ const doneBtn = document.getElementById('doneBtn');
154
+ const stage = document.getElementById('stage');
155
+
156
+ let sessionKey = null;
157
+ let canvas = null, ctx = null;
158
+ let viewportW = 1280, viewportH = 800;
159
+
160
+ const socket = io(serverUrl, { auth: { token: apiKey }, transports: ['websocket'], reconnection: true });
161
+
162
+ socket.on('connect_error', (e) => { statusText.textContent = 'Lỗi kết nối: ' + e.message; });
163
+ socket.on('connect', () => { statusText.textContent = 'Đã kết nối - chờ phiên tương tác cho ' + tenantClient + '...'; });
164
+
165
+ function ensureCanvas() {
166
+ if (canvas) return;
167
+ stage.innerHTML = '';
168
+ canvas = document.createElement('canvas');
169
+ canvas.width = viewportW;
170
+ canvas.height = viewportH;
171
+ fitCanvas();
172
+ stage.appendChild(canvas);
173
+ ctx = canvas.getContext('2d');
174
+ wireInput();
175
+ }
176
+
177
+ function fitCanvas() {
178
+ if (!canvas) return;
179
+ const availW = window.innerWidth, availH = window.innerHeight - 40;
180
+ const scale = Math.min(availW / viewportW, availH / viewportH, 1);
181
+ canvas.style.width = Math.round(viewportW * scale) + 'px';
182
+ canvas.style.height = Math.round(viewportH * scale) + 'px';
183
+ }
184
+ window.addEventListener('resize', fitCanvas);
185
+
186
+ socket.on('browser:cast-start', (payload) => {
187
+ sessionKey = payload.clientId;
188
+ viewportW = payload.viewportWidth || 1280;
189
+ viewportH = payload.viewportHeight || 800;
190
+ statusText.textContent = 'Phiên tương tác: ' + sessionKey + ' (' + (payload.url || '') + ')';
191
+ doneBtn.style.display = 'inline-block';
192
+ socket.emit('join-room', { name: 'aivin-cli', rooms: ['aibrowser:' + sessionKey] });
193
+ ensureCanvas();
194
+ });
195
+
196
+ socket.on('browser:screenshot', (payload) => {
197
+ if (!payload || !payload.screenshot) return;
198
+ ensureCanvas();
199
+ const bytes = payload.screenshot instanceof ArrayBuffer ? new Uint8Array(payload.screenshot) : payload.screenshot;
200
+ const blob = new Blob([bytes], { type: 'image/jpeg' });
201
+ const url = URL.createObjectURL(blob);
202
+ const img = new Image();
203
+ img.onload = () => { ctx.drawImage(img, 0, 0, canvas.width, canvas.height); URL.revokeObjectURL(url); };
204
+ img.src = url;
205
+ if (payload.title) statusText.textContent = payload.title + ' — ' + (payload.url || '');
206
+ });
207
+
208
+ socket.on('browser:cast-error', (payload) => {
209
+ statusText.textContent = '⚠️ ' + (payload.reason || 'Mất kết nối phiên trình duyệt');
210
+ });
211
+
212
+ socket.on('browser:resolved', () => {
213
+ statusText.textContent = '✅ Đã gửi tín hiệu hoàn tất - mission đang tiếp tục...';
214
+ doneBtn.style.display = 'none';
215
+ });
216
+
217
+ doneBtn.addEventListener('click', () => {
218
+ if (!sessionKey) return;
219
+ socket.emit('browser:resolve', { clientId: sessionKey, option: 'approve' });
220
+ });
221
+
222
+ function toPageCoords(e) {
223
+ const rect = canvas.getBoundingClientRect();
224
+ const x = Math.round((e.clientX - rect.left) * (viewportW / rect.width));
225
+ const y = Math.round((e.clientY - rect.top) * (viewportH / rect.height));
226
+ return { x, y };
227
+ }
228
+
229
+ const SPECIAL_KEYS = {
230
+ Enter: '__ENTER__', Backspace: '__BACKSPACE__', Delete: '__DELETE__', Tab: '__TAB__',
231
+ Escape: '__ESCAPE__', ArrowUp: '__ARROW_UP__', ArrowDown: '__ARROW_DOWN__',
232
+ ArrowLeft: '__ARROW_LEFT__', ArrowRight: '__ARROW_RIGHT__', Home: '__HOME__', End: '__END__',
233
+ PageUp: '__PAGE_UP__', PageDown: '__PAGE_DOWN__', F5: '__F5__', F12: '__F12__',
234
+ };
235
+
236
+ function wireInput() {
237
+ canvas.addEventListener('click', (e) => {
238
+ if (!sessionKey) return;
239
+ const { x, y } = toPageCoords(e);
240
+ socket.emit('browser:click', { clientId: sessionKey, x, y });
241
+ });
242
+ canvas.addEventListener('contextmenu', (e) => {
243
+ e.preventDefault();
244
+ if (!sessionKey) return;
245
+ const { x, y } = toPageCoords(e);
246
+ socket.emit('browser:rightclick', { clientId: sessionKey, x, y });
247
+ });
248
+ canvas.addEventListener('dblclick', (e) => {
249
+ if (!sessionKey) return;
250
+ const { x, y } = toPageCoords(e);
251
+ socket.emit('browser:dblclick', { clientId: sessionKey, x, y });
252
+ });
253
+ let lastHover = 0;
254
+ canvas.addEventListener('mousemove', (e) => {
255
+ if (!sessionKey) return;
256
+ const now = Date.now();
257
+ if (now - lastHover < 50) return;
258
+ lastHover = now;
259
+ const { x, y } = toPageCoords(e);
260
+ socket.emit('browser:hover', { clientId: sessionKey, x, y });
261
+ });
262
+ canvas.addEventListener('wheel', (e) => {
263
+ if (!sessionKey) return;
264
+ e.preventDefault();
265
+ socket.emit('browser:scroll', { clientId: sessionKey, deltaY: e.deltaY });
266
+ }, { passive: false });
267
+ canvas.tabIndex = 0;
268
+ canvas.addEventListener('keydown', (e) => {
269
+ if (!sessionKey) return;
270
+ if (e.ctrlKey || e.metaKey) return; // let browser-level shortcuts (devtools, refresh...) through
271
+ const special = SPECIAL_KEYS[e.key];
272
+ if (special) {
273
+ e.preventDefault();
274
+ socket.emit('browser:type', { clientId: sessionKey, text: special });
275
+ return;
276
+ }
277
+ if (e.key.length === 1) {
278
+ e.preventDefault();
279
+ socket.emit('browser:type', { clientId: sessionKey, text: e.key });
280
+ }
281
+ });
282
+ canvas.addEventListener('mouseenter', () => canvas.focus());
283
+ }
284
+ })();
285
+ </script>
286
+ </body>
287
+ </html>`;
288
+ }
289
+
290
+ /**
291
+ * Serves the viewer page on a random local port (127.0.0.1 only - never exposed beyond this
292
+ * machine) and opens it in the default OS browser. The HTTP server is torn down when the CLI
293
+ * process exits (SIGINT/mission end) - it only needs to live for the duration of `aivin browser`.
294
+ */
295
+ export function openBrowserViewer(serverUrl, apiKey, tenantClient) {
296
+ return new Promise((resolve) => {
297
+ const html = browserViewerHtml({ serverUrl, apiKey, tenantClient });
298
+ const server = http.createServer((req, res) => {
299
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
300
+ res.end(html);
301
+ });
302
+ server.listen(0, '127.0.0.1', () => {
303
+ const port = server.address().port;
304
+ const url = `http://127.0.0.1:${port}/`;
305
+ console.log(chalk.cyan(`\n🖥️ Mở phiên tương tác trực tiếp: ${url}`));
306
+ openBrowser(url);
307
+ resolve(server);
308
+ });
309
+ });
310
+ }
311
+
312
+ /**
313
+ * Same live-progress watcher as `streamMissionLog`, plus: on the first `ai_browser.hil_required`
314
+ * event (mission hit a step that needs a human - captcha, login, free-text confirmation), opens
315
+ * the fullscreen viewer automatically instead of leaving the user to go find it. Only opens once
316
+ * per run even if HIL fires again later (e.g. a second captcha) - the SAME viewer page keeps
317
+ * working across multiple HIL rounds since it just reacts to whatever `browser:cast-start` fires
318
+ * next on this tenant's room.
319
+ */
320
+ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClient, { idleTimeoutMs = 120_000, openViewerOnHIL = true } = {}) {
321
+ return new Promise((resolve) => {
322
+ const socket = io(serverUrl, { auth: { token: apiKey || 'dev-token' }, transports: ['websocket'], reconnection: true });
323
+
324
+ let idleTimer;
325
+ let settled = false;
326
+ let viewerOpened = false;
327
+ let viewerServer;
328
+ const statusIcon = (status) =>
329
+ status === 'error' ? chalk.red('✗') : status === 'success' ? chalk.green('✓') : status === 'warning' ? chalk.yellow('!') : chalk.gray('·');
330
+
331
+ const stop = () => {
332
+ if (settled) return;
333
+ settled = true;
334
+ clearTimeout(idleTimer);
335
+ socket.disconnect();
336
+ process.off('SIGINT', stop);
337
+ // The auto-opened HIL viewer keeps a listening HTTP server alive (and with it the whole
338
+ // process) past the point the mission actually finished - close it along with everything else.
339
+ viewerServer?.close();
340
+ resolve();
341
+ };
342
+
343
+ const bumpIdleTimer = () => {
344
+ clearTimeout(idleTimer);
345
+ idleTimer = setTimeout(() => {
346
+ console.log(chalk.gray(`\n(no activity for ${Math.round(idleTimeoutMs / 1000)}s - stopped watching; the run may still be going in the background)`));
347
+ stop();
348
+ }, idleTimeoutMs);
349
+ };
350
+
351
+ process.on('SIGINT', stop);
352
+
353
+ socket.on('connect_error', (error) => {
354
+ console.log(chalk.yellow(`⚠️ Couldn't watch live progress (${error.message}) - the run continues regardless.`));
355
+ stop();
356
+ });
357
+
358
+ for (const eventName of MISSION_LOG_EVENTS) {
359
+ socket.on(eventName, (payload) => {
360
+ if (!payload || payload.thread_id !== threadId) return;
361
+ bumpIdleTimer();
362
+ const time = new Date(payload.timestamp || Date.now()).toLocaleTimeString();
363
+ const label = payload.event_key || eventName;
364
+ console.log(`${chalk.gray(`[${time}]`)} ${statusIcon(payload.status)} ${chalk.gray(label)} ${payload.message || ''}`.trimEnd());
365
+
366
+ if (payload.event_key === 'ai_browser.hil_required' && !viewerOpened) {
367
+ viewerOpened = true;
368
+ // Most important moment for a notification: a mission can run for minutes with the
369
+ // terminal/browser out of focus, and this is the one point where it's actually STUCK until
370
+ // the user comes back - not just a progress update they can catch up on later.
371
+ sendOSNotification('AI Browser cần bạn hỗ trợ', payload.message || 'Mission đang chờ bạn tương tác');
372
+ if (openViewerOnHIL) {
373
+ console.log(chalk.magenta('\n👤 Mission cần bạn tương tác trực tiếp (captcha/đăng nhập/xác nhận) - đang mở trình duyệt...'));
374
+ openBrowserViewer(serverUrl, apiKey, tenantClient)
375
+ .then((server) => {
376
+ // `stop()` may already have run by the time this resolves (mission finished right as
377
+ // the viewer was opening) - it can't close a server it never got a reference to, so
378
+ // close it here instead of leaking a listening HTTP server past the watcher's lifetime.
379
+ if (settled) server.close();
380
+ else viewerServer = server;
381
+ })
382
+ .catch((e) =>
383
+ console.log(chalk.yellow(`⚠️ Không mở được viewer tự động: ${e.message} - thử lại bằng \`aivin browser --view ${tenantClient}\`.`)),
384
+ );
385
+ } else {
386
+ // Local mode: no separate viewer needed at all - the message + a "Xong" button are
387
+ // injected directly onto the real tab the user is already looking at (AIBrowserService's
388
+ // showOnPageHILBanner). A screencast-based viewer here would just be a second, redundant,
389
+ // lower-fidelity copy of a page already fully visible natively.
390
+ console.log(chalk.magenta(`\n👤 ${payload.message || 'Mission cần bạn hỗ trợ'} - kiểm tra cửa sổ trình duyệt (có banner xanh ở đầu trang), bấm "Xong" ở đó khi hoàn tất.`));
391
+ }
392
+ }
393
+ // `execute-interactive` calls triggerMission directly (not the multi-step `flow.*` runner
394
+ // aivin do's missions go through), so its real terminal signal is ai_browser.success/failed,
395
+ // not anything in MISSION_DONE_EVENT_KEYS - checked in addition to (not instead of) that set
396
+ // since this function is also reused as a fallback for --remote missions triggered elsewhere.
397
+ if (payload.event_key === 'ai_browser.success' || payload.event_key === 'ai_browser.failed' || MISSION_DONE_EVENT_KEYS.has(payload.event_key)) {
398
+ const ok = payload.event_key !== 'ai_browser.failed' && payload.status !== 'error';
399
+ sendOSNotification(ok ? '✅ AI Browser hoàn tất' : '❌ AI Browser thất bại', payload.message || '');
400
+ stop();
401
+ }
402
+ });
403
+ }
404
+
405
+ // 🔍 Step-by-step agentic detail (perceive/plan/execute/audit/recover) - a SEPARATE Socket.IO
406
+ // room-broadcast event from the chat-log-shaped ones above (AIBrowserService.emitAgentStep,
407
+ // room `client:<tenant>`, joined automatically on auth per SocketIO.ts). Was previously never
408
+ // listened to here at all - the terminal only ever showed the bookend start/success/failed lines
409
+ // even though the backend was emitting a full trace the whole time. `detail` (when present)
410
+ // carries the LLM's actual per-action reasoning (AIBrowserActionItem.reason), not just the
411
+ // truncated one-line summary meant for a chat bubble.
412
+ const STEP_ICON = { perceiving: '👁', executing: '▶', blocked: '🛡', recovering: '↺', auditing: '🔎', done: '✅', failed: '❌' };
413
+ socket.on('browser:agent-step', (payload) => {
414
+ if (!payload) return;
415
+ bumpIdleTimer();
416
+ const time = new Date().toLocaleTimeString();
417
+ const icon = STEP_ICON[payload.type] || '·';
418
+ console.log(`${chalk.gray(`[${time}]`)} ${icon} ${chalk.cyan(`step ${payload.step}`)} ${chalk.gray(payload.type)} ${payload.summary || ''}`.trimEnd());
419
+ if (payload.url) console.log(chalk.gray(` url: ${payload.url}`));
420
+ const detail = payload.detail;
421
+ if (Array.isArray(detail)) {
422
+ // 'executing' - one or more planned actions, each with its own reasoning
423
+ for (const a of detail) {
424
+ console.log(chalk.gray(` - ${a.type}${a.detail ? ` (${a.detail})` : ''}`));
425
+ if (a.reason) console.log(chalk.dim(` reason: ${a.reason}`));
426
+ }
427
+ } else if (detail && typeof detail === 'object') {
428
+ // 'recovering' - { reason, revisedActions } from the audit/replan phase
429
+ if (detail.reason) console.log(chalk.dim(` reason: ${detail.reason}`));
430
+ for (const a of detail.revisedActions || []) {
431
+ console.log(chalk.gray(` - ${a.type}${a.detail ? ` (${a.detail})` : ''}`));
432
+ if (a.reason) console.log(chalk.dim(` reason: ${a.reason}`));
433
+ }
434
+ }
435
+ });
436
+
437
+ console.log(chalk.gray(`📡 Watching live progress for ${threadId}... (Ctrl+C to stop watching - the run keeps going either way)\n`));
438
+ bumpIdleTimer();
439
+ });
440
+ }
441
+
442
+ // Without a `start_url`, the mission's first step lands on a totally blank page - confirmed while
443
+ // testing this to cost real time (a full perceive+plan cycle wasted on a page with nothing to look
444
+ // at) AND to be a correctness risk: with nothing to navigate to, the planner reaches for the `search`
445
+ // action to find the target site itself, which does a REAL web search and goes wherever the top
446
+ // (reranked) result is - watched it once land on an unrelated w3schools tutorial page instead of
447
+ // facebook.com. A `start_url` sidesteps both: the mission opens directly on the real site via a plain
448
+ // `page.goto` before the agentic loop even starts, no guessing involved. Best-effort keyword match
449
+ // only (not NLU) - covers the common case from a mission mentioning a well-known site by name; falls
450
+ // back to no start_url (today's behavior) when nothing matches, and --url always wins outright.
451
+ export const KNOWN_SITE_HINTS = [
452
+ { re: /facebook|\bfb\b/i, url: 'https://www.facebook.com' },
453
+ { re: /instagram|\big\b/i, url: 'https://www.instagram.com' },
454
+ { re: /\btiktok\b/i, url: 'https://www.tiktok.com' },
455
+ { re: /\byoutube\b/i, url: 'https://www.youtube.com' },
456
+ { re: /\b(twitter|x\.com)\b/i, url: 'https://x.com' },
457
+ { re: /linkedin/i, url: 'https://www.linkedin.com' },
458
+ { re: /\bzalo\b/i, url: 'https://chat.zalo.me' },
459
+ { re: /\bgmail\b/i, url: 'https://mail.google.com' },
460
+ { re: /\boutlook\b/i, url: 'https://outlook.live.com' },
461
+ // Vietnamese e-commerce/social - the realistic mission targets for this CLI's actual audience,
462
+ // not just the generic global-site list above.
463
+ { re: /\bshopee\b/i, url: 'https://shopee.vn' },
464
+ { re: /\btiki\b/i, url: 'https://tiki.vn' },
465
+ { re: /\blazada\b/i, url: 'https://www.lazada.vn' },
466
+ { re: /\bsendo\b/i, url: 'https://www.sendo.vn' },
467
+ { re: /\bvnexpress\b/i, url: 'https://vnexpress.net' },
468
+ { re: /\bamazon\b/i, url: 'https://www.amazon.com' },
469
+ { re: /\bgithub\b/i, url: 'https://github.com' },
470
+ { re: /\breddit\b/i, url: 'https://www.reddit.com' },
471
+ { re: /\bpinterest\b/i, url: 'https://www.pinterest.com' },
472
+ { re: /\bthreads\b/i, url: 'https://www.threads.net' },
473
+ { re: /\bwhatsapp\b/i, url: 'https://web.whatsapp.com' },
474
+ { re: /\btelegram\b/i, url: 'https://web.telegram.org' },
475
+ { re: /\bdiscord\b/i, url: 'https://discord.com' },
476
+ { re: /\bspotify\b/i, url: 'https://open.spotify.com' },
477
+ { re: /\bnetflix\b/i, url: 'https://www.netflix.com' },
478
+ ];
479
+
480
+ // Fallback for a site NOT in the (necessarily always-incomplete) list above: if the mission text
481
+ // itself contains something that looks like an actual domain (e.g. "đăng nhập vào crm.mycompany.vn"),
482
+ // use that directly rather than leaving start_url unset - a hand-picked static list can never cover
483
+ // every real target, especially a mission naming an internal/niche/foreign site nobody thought to
484
+ // hardcode. Deliberately conservative: requires a real-looking TLD, not just any two words with a
485
+ // dot between them (avoids matching version numbers, decimals, "v1.2" etc.).
486
+ export const DOMAIN_IN_TEXT_RE = /\b((?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.)+(?:com|net|org|io|co|vn|dev|app|shop|store|biz|info|edu|gov|xyz)(?:\.[a-z]{2,3})?)\b/i;
487
+
488
+ export function guessStartUrl(mission) {
489
+ const known = KNOWN_SITE_HINTS.find((h) => h.re.test(mission))?.url;
490
+ if (known) return known;
491
+ const domainMatch = DOMAIN_IN_TEXT_RE.exec(mission);
492
+ return domainMatch ? `https://${domainMatch[1]}` : undefined;
493
+ }
494
+
495
+ // ── Windows toast identity: shows "AI Browser" + the real aivin icon instead of a bare, borrowed
496
+ // "File Explorer" notification ────────────────────────────────────────────────────────────────
497
+ //
498
+ // Confirmed by hand while building this: a plain AppUserModelId registry entry (DisplayName +
499
+ // IconUri, no shortcut) gets the NAME right but Windows silently ignores the IconUri for an
500
+ // unpackaged (non-MSIX) app - a known platform gap, not a bug in this setup. The icon only actually
501
+ // shows once a Start Menu shortcut exists whose System.AppUserModel.ID property (via IPropertyStore)
502
+ // matches the AUMID used in CreateToastNotifier - that requires COM interop (IShellLinkW +
503
+ // IPropertyStore), which plain PowerShell cmdlets don't expose, hence the embedded C# below compiled
504
+ // on demand via Add-Type. This whole block only ever runs ONCE per machine (skipped immediately if
505
+ // the shortcut already exists) - the compile is real but not a per-notification cost.
506
+ export const AIVIN_NOTIF_AUMID = 'AivinBrowser.CLI';
507
+
508
+ export const AIVIN_ICON_SOURCE_PNG = path.join(__dirname, 'assets', 'aivin-icon.png');
509
+
510
+ export const AIVIN_ICON_ICO = path.join(os.homedir(), '.aivin', 'notification-icon.ico');
511
+
512
+ export function windowsNotificationShortcutPath() {
513
+ // %APPDATA%\Microsoft\Windows\Start Menu\Programs - same folder Start Menu search indexes,
514
+ // matches what a real installer would use (this entry never needs to be launched by the user,
515
+ // it exists purely to carry the AUMID + icon association).
516
+ return path.join(os.homedir(), 'AppData', 'Roaming', 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'AI Browser.lnk');
517
+ }
518
+
519
+ /** One-time (per machine), best-effort setup - PNG→ICO conversion + registry DisplayName + a Start
520
+ * Menu shortcut carrying the AUMID via COM IPropertyStore. Every step independently best-effort:
521
+ * a failure partway (e.g. propsys.dll COM call blocked by policy) just means the toast falls back
522
+ * to a plain/unbranded appearance later, never something worth failing a mission over. Synchronous
523
+ * (blocks briefly on first-ever notification only) - acceptable since it's a one-time cost in the
524
+ * context of a multi-minute mission, and notifications aren't on any latency-sensitive path. */
525
+ export function ensureWindowsNotificationIdentity() {
526
+ const shortcutPath = windowsNotificationShortcutPath();
527
+ if (fs.existsSync(shortcutPath)) return; // already set up on this machine
528
+ try {
529
+ fs.mkdirSync(path.dirname(AIVIN_ICON_ICO), { recursive: true });
530
+ const csharpSource = `
531
+ using System;
532
+ using System.Runtime.InteropServices;
533
+ using System.Runtime.InteropServices.ComTypes;
534
+ public static class AivinShortcutAumid {
535
+ [ComImport, Guid("00021401-0000-0000-C000-000000000046")] internal class ShellLink { }
536
+ [ComImport, InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid("000214F9-0000-0000-C000-000000000046")]
537
+ internal interface IShellLinkW {
538
+ void GetPath([Out, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszFile, int cchMaxPath, IntPtr pfd, uint fFlags);
539
+ void GetIDList(out IntPtr ppidl); void SetIDList(IntPtr pidl);
540
+ void GetDescription([Out, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszName, int cchMaxName);
541
+ void SetDescription([MarshalAs(UnmanagedType.LPWStr)] string pszName);
542
+ void GetWorkingDirectory([Out, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszDir, int cchMaxPath);
543
+ void SetWorkingDirectory([MarshalAs(UnmanagedType.LPWStr)] string pszDir);
544
+ void GetArguments([Out, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszArgs, int cchMaxPath);
545
+ void SetArguments([MarshalAs(UnmanagedType.LPWStr)] string pszArgs);
546
+ void GetHotkey(out short pwHotkey); void SetHotkey(short wHotkey);
547
+ void GetShowCmd(out int piShowCmd); void SetShowCmd(int iShowCmd);
548
+ void GetIconLocation([Out, MarshalAs(UnmanagedType.LPWStr)] System.Text.StringBuilder pszIconPath, int cchIconPath, out int piIcon);
549
+ void SetIconLocation([MarshalAs(UnmanagedType.LPWStr)] string pszIconPath, int iIcon);
550
+ void SetRelativePath([MarshalAs(UnmanagedType.LPWStr)] string pszPathRel, uint dwReserved);
551
+ void Resolve(IntPtr hwnd, uint fFlags);
552
+ void SetPath([MarshalAs(UnmanagedType.LPWStr)] string pszFile);
553
+ }
554
+ [StructLayout(LayoutKind.Sequential)] internal struct PROPERTYKEY { public Guid fmtid; public int pid; }
555
+ [StructLayout(LayoutKind.Sequential)] internal struct PROPVARIANT { public ushort vt; public ushort r1, r2, r3; public IntPtr p; public int p2; }
556
+ [ComImport, Guid("886d8eeb-8cf2-4446-8d02-cdba1dbdcf99"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
557
+ internal interface IPropertyStore {
558
+ void GetCount(out uint cProps); void GetAt(uint iProp, out PROPERTYKEY pkey);
559
+ void GetValue(ref PROPERTYKEY key, out PROPVARIANT pv); void SetValue(ref PROPERTYKEY key, ref PROPVARIANT pv);
560
+ void Commit();
561
+ }
562
+ [DllImport("propsys.dll")] static extern int PSPropertyKeyFromString([MarshalAs(UnmanagedType.LPWStr)] string s, out PROPERTYKEY pkey);
563
+ [DllImport("ole32.dll")] static extern int PropVariantClear(ref PROPVARIANT pvar);
564
+ public static void CreateWithAumid(string shortcutPath, string targetPath, string iconPath, string aumid) {
565
+ var link = (IShellLinkW)new ShellLink();
566
+ link.SetPath(targetPath);
567
+ link.SetIconLocation(iconPath, 0);
568
+ link.SetShowCmd(7);
569
+ PROPERTYKEY pkey;
570
+ if (PSPropertyKeyFromString("{9F4C2855-9F79-4B39-A8D0-E1D42DE1D5F3} 5", out pkey) != 0) throw new Exception("PSPropertyKeyFromString failed");
571
+ var pv = new PROPVARIANT();
572
+ pv.vt = 31; // VT_LPWSTR
573
+ pv.p = Marshal.StringToCoTaskMemUni(aumid);
574
+ ((IPropertyStore)link).SetValue(ref pkey, ref pv);
575
+ ((IPropertyStore)link).Commit();
576
+ PropVariantClear(ref pv);
577
+ ((IPersistFile)link).Save(shortcutPath, true);
578
+ }
579
+ }`;
580
+ const setupScript = [
581
+ 'Add-Type -AssemblyName System.Drawing',
582
+ `if (-not (Test-Path $env:AIVIN_ICO_PATH)) {`,
583
+ ' $png = [System.Drawing.Image]::FromFile($env:AIVIN_PNG_PATH)',
584
+ ' $bmp = New-Object System.Drawing.Bitmap($png, 256, 256)',
585
+ ' $ico = [System.Drawing.Icon]::FromHandle($bmp.GetHicon())',
586
+ ' $fs = New-Object System.IO.FileStream($env:AIVIN_ICO_PATH, [System.IO.FileMode]::Create)',
587
+ ' $ico.Save($fs); $fs.Close(); $png.Dispose()',
588
+ '}',
589
+ `New-Item -Path "HKCU:\\Software\\Classes\\AppUserModelId\\${AIVIN_NOTIF_AUMID}" -Force | Out-Null`,
590
+ `Set-ItemProperty -Path "HKCU:\\Software\\Classes\\AppUserModelId\\${AIVIN_NOTIF_AUMID}" -Name DisplayName -Value "AI Browser"`,
591
+ `Add-Type -TypeDefinition @'\n${csharpSource}\n'@ -Language CSharp`,
592
+ `[AivinShortcutAumid]::CreateWithAumid($env:AIVIN_SHORTCUT_PATH, "$env:WINDIR\\System32\\cmd.exe", $env:AIVIN_ICO_PATH, "${AIVIN_NOTIF_AUMID}")`,
593
+ ].join('\n');
594
+ execSync(`powershell.exe -NoProfile -NonInteractive -Command -`, {
595
+ input: setupScript,
596
+ env: {
597
+ ...process.env,
598
+ AIVIN_PNG_PATH: AIVIN_ICON_SOURCE_PNG,
599
+ AIVIN_ICO_PATH: AIVIN_ICON_ICO,
600
+ AIVIN_SHORTCUT_PATH: shortcutPath,
601
+ },
602
+ stdio: ['pipe', 'ignore', 'ignore'],
603
+ timeout: 15_000,
604
+ });
605
+ } catch {
606
+ // best-effort only - toast still works via the Explorer-borrowed AppID fallback below,
607
+ // just without aivin's own name/icon.
608
+ }
609
+ }
610
+
611
+ /** Best-effort native OS notification - `aivin browser` (local mode) can run for minutes at a time
612
+ * with the user's attention elsewhere, and a HIL request in particular needs them to actually come
613
+ * back and look. Native per-OS command, no extra npm dependency (matches this file's existing
614
+ * pattern - registry reads, plutil, xdg-settings are all done the same way). Title/message passed
615
+ * via env vars (not string-interpolated into the script) specifically to avoid any shell/PowerShell/
616
+ * AppleScript quoting/injection concern - mission text and error messages both end up here and
617
+ * neither is trusted input. Never throws, never blocks - a failed notification is not worth
618
+ * interrupting a mission over. */
619
+ export function sendOSNotification(title, message) {
620
+ try {
621
+ if (process.platform === 'win32') {
622
+ ensureWindowsNotificationIdentity();
623
+ // Windows 10/11 toast via the WinRT API directly - no extra module (BurntToast etc.) needed.
624
+ // Uses the dedicated AUMID set up above once a shortcut backs it (falls back to Explorer's
625
+ // borrowed identity harmlessly if that setup didn't succeed - CreateToastNotifier doesn't
626
+ // validate the AUMID actually resolves to anything, it just shows less polished either way).
627
+ const script = [
628
+ "[Windows.UI.Notifications.ToastNotificationManager, Windows.UI.Notifications, ContentType = WindowsRuntime] | Out-Null",
629
+ "[Windows.Data.Xml.Dom.XmlDocument, Windows.Data.Xml.Dom.XmlDocument, ContentType = WindowsRuntime] | Out-Null",
630
+ "$t = [System.Security.SecurityElement]::Escape($env:AIVIN_NOTIF_TITLE)",
631
+ "$m = [System.Security.SecurityElement]::Escape($env:AIVIN_NOTIF_MSG)",
632
+ "$xml = New-Object Windows.Data.Xml.Dom.XmlDocument",
633
+ "$xml.LoadXml(\"<toast><visual><binding template='ToastGeneric'><text>$t</text><text>$m</text></binding></visual></toast>\")",
634
+ "$toast = New-Object Windows.UI.Notifications.ToastNotification($xml)",
635
+ `[Windows.UI.Notifications.ToastNotificationManager]::CreateToastNotifier('${AIVIN_NOTIF_AUMID}').Show($toast)`,
636
+ ].join('; ');
637
+ spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', script], {
638
+ env: { ...process.env, AIVIN_NOTIF_TITLE: title, AIVIN_NOTIF_MSG: message },
639
+ stdio: 'ignore', detached: true,
640
+ }).unref();
641
+ } else if (process.platform === 'darwin') {
642
+ // `system attribute` reads the env var directly in AppleScript - sidesteps needing to escape
643
+ // title/message into the script string at all.
644
+ spawn('osascript', ['-e', 'display notification (system attribute "AIVIN_NOTIF_MSG") with title (system attribute "AIVIN_NOTIF_TITLE")'], {
645
+ env: { ...process.env, AIVIN_NOTIF_TITLE: title, AIVIN_NOTIF_MSG: message },
646
+ stdio: 'ignore', detached: true,
647
+ }).unref();
648
+ } else {
649
+ // notify-send (freedesktop.org standard, most desktop distros ship it) - args array, not a
650
+ // shell string, so no quoting concern here either.
651
+ spawn('notify-send', [title, message], { stdio: 'ignore', detached: true }).unref();
652
+ }
653
+ } catch {
654
+ // best-effort only
655
+ }
656
+ }