@aivin-labs/cli 1.0.3 → 1.0.4

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/bin/cli.mjs CHANGED
@@ -25,7 +25,7 @@ import { initInteractive, makePluginFromDescription, convertExistingProject } fr
25
25
  import { searchPlugins, showPluginInfo, askPlugin, streamPluginLogs, triggerPlugin, deletePluginCmd } from './lib/pluginTrigger.mjs';
26
26
  import { connectorAuthHeaders, connectorBaseUrl, listConnectors, registerConnector, searchConnectors } from './lib/connectors.mjs';
27
27
  import { attachStore, createStore, deleteStore, detachStore, listStores, removeNode, setStoreEnabled } from './lib/store.mjs';
28
- import { buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName, createMcpProxyPlugin, scanAndPublishMcp } from './lib/mcpProxy.mjs';
28
+ import { buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName, createMcpProxyPlugin, scanAndPublishMcp, registerMcpWatch, unwatchMcp, listMcpWatches } from './lib/mcpProxy.mjs';
29
29
  import {
30
30
  saveGlobalApiKey,
31
31
  browserLogin,
@@ -723,6 +723,41 @@ mcpCommand
723
723
  }
724
724
  });
725
725
 
726
+ mcpCommand
727
+ .command('watch [url]')
728
+ .description('Watch a GitHub repo/branch and auto-rescan+resync its plugins when the branch updates (checked server-side every ~5 min, no CLI process needs to stay running)')
729
+ .option('--branch <name>', "Branch to watch (default: the repo's default branch)")
730
+ .option('--list', 'List your watched repos instead of registering a new one')
731
+ .action(async (url, options) => {
732
+ try {
733
+ if (options.list) {
734
+ await listMcpWatches();
735
+ return;
736
+ }
737
+ url = await requireArg(url, {
738
+ prompt: 'GitHub repo URL to watch:',
739
+ usage: 'Usage: aivin mcp watch <url> [--branch <name>] | aivin mcp watch --list',
740
+ });
741
+ await registerMcpWatch(url, options);
742
+ } catch (error) {
743
+ console.error(chalk.red('❌'), error.message);
744
+ process.exit(1);
745
+ }
746
+ });
747
+
748
+ mcpCommand
749
+ .command('unwatch <url>')
750
+ .description('Stop auto-resyncing a previously watched repo')
751
+ .option('--branch <name>', 'Branch to unwatch (default: all watched branches for this repo)')
752
+ .action(async (url, options) => {
753
+ try {
754
+ await unwatchMcp(url, options);
755
+ } catch (error) {
756
+ console.error(chalk.red('❌'), error.message);
757
+ process.exit(1);
758
+ }
759
+ });
760
+
726
761
  program
727
762
  .command('login')
728
763
  .argument('[baseUrl]', 'Server to log into (REST API base) - defaults to production (api.aivin.cloud). Pass a staging/self-hosted host to switch the machine\'s active context to it, e.g. `aivin login beta-api.aivin.vn`.')
@@ -8,7 +8,8 @@ import { randomUUID } from 'crypto';
8
8
  import WSClient from 'ws';
9
9
  import { missionServerUrl, missionAuthHeaders, resolveWorkspace, resolveAgentInteractive, createAgent, pullAgentIntoWorkspace } from './workspace.mjs';
10
10
  import { parseApiKeyClient } from './auth.mjs';
11
- import { guessStartUrl, streamBrowserMissionLog, BROWSER_MISSION_PREFIX } from './missionStream.mjs';
11
+ import { guessStartUrl, BROWSER_MISSION_PREFIX } from './missionStream.mjs';
12
+ import { watchBrowserMission } from './browserTui.mjs';
12
13
 
13
14
  // ── `aivin browser` default mode: drive the user's OWN local, already-running browser ──────────
14
15
  //
@@ -345,8 +346,13 @@ export async function launchLocalChromeWithDebugging(port = CHROME_DEBUG_PORT, p
345
346
  * to the user's own local Chrome's real CDP endpoint - and pipes frames both directions verbatim.
346
347
  * `close()` disconnects both sides; the user's actual browser window is never touched beyond this
347
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()`.
348
354
  */
349
- export function openLocalTunnel(serverUrl, apiKey, chromeWsUrl) {
355
+ export function openLocalTunnel(serverUrl, apiKey, chromeWsUrl, { onUnexpectedClose } = {}) {
350
356
  const tunnelId = randomUUID();
351
357
  const relayUrl = `${serverUrl.replace(/^http/, 'ws')}/browser-tunnel/external?tunnel_id=${tunnelId}`;
352
358
 
@@ -355,19 +361,23 @@ export function openLocalTunnel(serverUrl, apiKey, chromeWsUrl) {
355
361
  const toBackend = new WSClient(relayUrl, { headers: { Authorization: `Bearer ${apiKey || ''}` } });
356
362
  const toChrome = new WSClient(chromeWsUrl);
357
363
 
358
- const relay = (from, to) => {
364
+ let deliberateClose = false;
365
+
366
+ const relay = (from, to, side) => {
359
367
  from.on('message', (data, isBinary) => {
360
368
  if (to.readyState === WSClient.OPEN) to.send(data, { binary: isBinary });
361
369
  });
362
370
  from.on('close', () => {
363
371
  if (to.readyState === WSClient.OPEN) to.close();
372
+ if (!deliberateClose) onUnexpectedClose?.(side);
364
373
  });
365
374
  from.on('error', () => {
366
375
  if (to.readyState === WSClient.OPEN) to.close();
376
+ if (!deliberateClose) onUnexpectedClose?.(side);
367
377
  });
368
378
  };
369
- relay(toBackend, toChrome);
370
- relay(toChrome, toBackend);
379
+ relay(toBackend, toChrome, 'backend');
380
+ relay(toChrome, toBackend, 'chrome');
371
381
 
372
382
  const ready = Promise.all([
373
383
  new Promise((resolve, reject) => {
@@ -381,6 +391,7 @@ export function openLocalTunnel(serverUrl, apiKey, chromeWsUrl) {
381
391
  ]);
382
392
 
383
393
  const close = () => {
394
+ deliberateClose = true;
384
395
  try { toBackend.close(); } catch { /* already closed */ }
385
396
  try { toChrome.close(); } catch { /* already closed */ }
386
397
  };
@@ -452,73 +463,114 @@ export async function runBrowserMissionLocal(mission, options) {
452
463
  console.log(chalk.blue('🌐 AI Browser (local - your own browser):'), mission);
453
464
  console.log(chalk.gray(` Workspace: ${workspace.name || workspace.id}`));
454
465
 
455
- const tunnel = openLocalTunnel(serverUrl, apiKey, chromeWsUrl);
456
- try {
457
- await tunnel.ready;
458
- } catch (error) {
459
- tunnel.close();
460
- throw new Error(`Could not open the local browser tunnel: ${error.message}`, { cause: error });
461
- }
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
+ }
462
490
 
463
- const sessionId = `browser-cli-${randomUUID()}`;
464
- console.log(chalk.gray(` Session: ${sessionId}`));
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
+ }
465
503
 
466
- // Ctrl+C: request cooperative cancellation (same mechanism sdk.browser.cancel() uses - checked
467
- // between agentic-loop steps, can't interrupt a step already in flight) AND close the tunnel.
468
- // Closing the tunnel alone isn't enough to stop a mission stuck in an LLM call that hasn't
469
- // touched the browser connection yet (confirmed while testing this) - the cancel request is what
470
- // actually gets it to stop at its next chance to check. The tab this mission was using stays open
471
- // either way - never force-closed, since local mode is explicitly "your own browser, your tabs".
472
- let interrupted = false;
473
- const onSigint = () => {
474
- if (interrupted) return;
475
- interrupted = true;
476
- console.log(chalk.yellow('\n\n⏹ Stopping... (requesting cancellation - may take a moment, one agentic step at a time)'));
477
- requestBrowserCancel(serverUrl, authHeaders).catch((e) =>
478
- console.log(chalk.red(` ⚠️ Cancellation request failed to send (${e.message}) - the mission may keep running.`)),
504
+ const sessionId = `browser-cli-${randomUUID()}`;
505
+ console.log(chalk.gray(` Session: ${sessionId}`));
506
+
507
+ // Ctrl+C: request cooperative cancellation (same mechanism sdk.browser.cancel() uses - checked
508
+ // between agentic-loop steps, can't interrupt a step already in flight) AND close the tunnel.
509
+ // Closing the tunnel alone isn't enough to stop a mission stuck in an LLM call that hasn't
510
+ // touched the browser connection yet (confirmed while testing this) - the cancel request is what
511
+ // actually gets it to stop at its next chance to check. The tab this mission was using stays open
512
+ // either way - never force-closed, since local mode is explicitly "your own browser, your tabs".
513
+ const onSigint = () => {
514
+ if (interrupted) return;
515
+ interrupted = true;
516
+ console.log(chalk.yellow('\n\n⏹ Stopping... (requesting cancellation - may take a moment, one agentic step at a time)'));
517
+ requestBrowserCancel(serverUrl, authHeaders).catch((e) =>
518
+ console.log(chalk.red(` ⚠️ Cancellation request failed to send (${e.message}) - the mission may keep running.`)),
519
+ );
520
+ tunnel.close();
521
+ console.log(chalk.gray(' The tab this mission was using is still open in your browser - close it yourself if you don\'t need it.'));
522
+ };
523
+ process.on('SIGINT', onSigint);
524
+
525
+ // Fired concurrently, not sequentially - execute-interactive is a SYNCHRONOUS call (blocks until
526
+ // the mission ends), so the log watcher has to already be listening before/as it fires, not after.
527
+ const missionPromise = axios.post(
528
+ // `/plugins/` prefix: OfficialPluginModules.ts registers every official plugin module (incl.
529
+ // AIBrowserModule) via RouterModule.register({ path: 'plugins', ... }) - easy to miss, confirmed
530
+ // by testing directly against the API (plain /ai-browser/... 404s, /plugins/ai-browser/... works).
531
+ `${serverUrl}/plugins/ai-browser/execute-interactive`,
532
+ {
533
+ mission,
534
+ workspace_id: workspace.id || workspace._id,
535
+ agent_id: agentId,
536
+ session_id: sessionId,
537
+ data: { __local_tunnel_id: tunnel.tunnelId, start_url: options.url || guessStartUrl(mission) },
538
+ },
539
+ authHeaders,
479
540
  );
480
- tunnel.close();
481
- 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.'));
482
- };
483
- process.on('SIGINT', onSigint);
541
+ const watchPromise = options.watch !== false
542
+ ? watchBrowserMission(serverUrl, apiKey, sessionId, tenantClient, { openViewerOnHIL: false })
543
+ : Promise.resolve(undefined);
484
544
 
485
- // Fired concurrently, not sequentially - execute-interactive is a SYNCHRONOUS call (blocks until
486
- // the mission ends), so the log watcher has to already be listening before/as it fires, not after.
487
- const missionPromise = axios.post(
488
- // `/plugins/` prefix: OfficialPluginModules.ts registers every official plugin module (incl.
489
- // AIBrowserModule) via RouterModule.register({ path: 'plugins', ... }) - easy to miss, confirmed
490
- // by testing directly against the API (plain /ai-browser/... 404s, /plugins/ai-browser/... works).
491
- `${serverUrl}/plugins/ai-browser/execute-interactive`,
492
- {
493
- mission,
494
- workspace_id: workspace.id || workspace._id,
495
- agent_id: agentId,
496
- session_id: sessionId,
497
- data: { __local_tunnel_id: tunnel.tunnelId, start_url: options.url || guessStartUrl(mission) },
498
- },
499
- authHeaders,
500
- );
501
- const watchPromise = options.watch !== false
502
- ? streamBrowserMissionLog(serverUrl, apiKey, sessionId, tenantClient, { openViewerOnHIL: false })
503
- : Promise.resolve();
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
+ }
504
561
 
505
- try {
506
- // execute-interactive responds immediately (fire-and-forget - see AIBrowserController.ts's
507
- // comment on why: a synchronous wait here would hit the same Cloudflare 524 the gRPC
508
- // browser.run() call did). The REAL outcome is whatever the log stream above already printed
509
- // (ai_browser.success/failed) - this Promise.all is just making sure both sides are done.
510
- await Promise.all([missionPromise, watchPromise]);
511
- } catch (error) {
512
- if (!interrupted) {
513
- const message = error.response?.data?.message || error.message || error.code || 'Unknown error';
514
- throw new Error(`AI Browser mission failed to start: ${message}`, { cause: error });
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;
515
570
  }
516
- } finally {
517
- process.off('SIGINT', onSigint);
518
- tunnel.close();
519
571
  }
520
572
 
521
- if (!interrupted) {
573
+ if (!interrupted && (terminalReason === 'success' || terminalReason === 'failed')) {
522
574
  console.log(chalk.gray('\n Done - see the log lines above for the outcome, and your own browser for the result.'));
523
575
  }
524
576
  }
@@ -588,7 +640,7 @@ export async function runBrowserMissionRemote(mission, options) {
588
640
 
589
641
  try {
590
642
  if (options.watch !== false && threadId) {
591
- await streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClient);
643
+ await watchBrowserMission(serverUrl, apiKey, threadId, tenantClient);
592
644
  }
593
645
  } finally {
594
646
  process.off('SIGINT', onSigint);
@@ -0,0 +1,245 @@
1
+ import React, { useState, useRef, useEffect } from 'react';
2
+ import { render, Box, Text, Static } from 'ink';
3
+ import TextInput from 'ink-text-input';
4
+ import { io } from 'socket.io-client';
5
+ import axios from 'axios';
6
+ import {
7
+ MISSION_LOG_EVENTS,
8
+ MISSION_DONE_EVENT_KEYS,
9
+ openBrowserViewer,
10
+ sendOSNotification,
11
+ streamBrowserMissionLog,
12
+ } from './missionStream.mjs';
13
+
14
+ // ── Claude-Code-style split view for `aivin browser`: log cuộn phía trên (Ink <Static>, append-only,
15
+ // không bao giờ re-render 1 dòng đã in — đúng thứ cần cho log liên tục), 1 dòng input cố định dưới
16
+ // cùng, luôn nhận gõ. Chỉ dùng khi có TTY thật (guard ở call site, browserAutomation.mjs) - Ink cần
17
+ // raw-mode stdin, không hoạt động khi output bị pipe/redirect. Không có bundler/JSX transform trong
18
+ // CLI này (chỉ publish .mjs thô) nên toàn bộ component viết bằng React.createElement thuần, không JSX.
19
+ const h = React.createElement;
20
+
21
+ const STEP_ICON = { planning: '📋', perceiving: '👁', executing: '▶', blocked: '🛡', recovering: '↺', auditing: '🔎', done: '✅', failed: '❌' };
22
+
23
+ let nextLineId = 0;
24
+ function line(text, color, dim) {
25
+ return { id: nextLineId++, text, color, dim };
26
+ }
27
+
28
+ function LogLine({ item }) {
29
+ return h(Text, { color: item.color, dimColor: item.dim }, item.text);
30
+ }
31
+
32
+ function MissionTuiApp({ serverUrl, apiKey, threadId, tenantClient, idleTimeoutMs, openViewerOnHIL, onSettle }) {
33
+ const [lines, setLines] = useState([]);
34
+ const [inputValue, setInputValue] = useState('');
35
+ // Khác `paused=false` (mission đang tự chạy, Enter -> steer) - khi có giá trị, Enter gửi
36
+ // browser:resolve nhắm đúng session HIL đang treo thay vì đi qua kênh steer.
37
+ const [pausedSessionKey, setPausedSessionKey] = useState(null);
38
+ const [sending, setSending] = useState(false);
39
+ const [done, setDone] = useState(false);
40
+
41
+ const socketRef = useRef(null);
42
+ const settledRef = useRef(false);
43
+ const viewerServerRef = useRef(null);
44
+ const idleTimerRef = useRef(null);
45
+ const viewerOpenedRef = useRef(false);
46
+
47
+ const appendLine = (text, color, dim) => setLines((prev) => [...prev, line(text, color, dim)]);
48
+
49
+ useEffect(() => {
50
+ const socket = io(serverUrl, { auth: { token: apiKey || 'dev-token' }, transports: ['websocket'], reconnection: true });
51
+ socketRef.current = socket;
52
+
53
+ // `reason` - cùng lý do với streamBrowserMissionLog's stop(reason): phân biệt kết quả mission
54
+ // thật ('success'/'failed') với "chỉ đơn giản là ngừng theo dõi" ('idle'/'connect_error') - CLI
55
+ // dùng để quyết định có nên retry tunnel hay không (chỉ retry ở nhóm sau).
56
+ const settle = (reason) => {
57
+ if (settledRef.current) return;
58
+ settledRef.current = true;
59
+ clearTimeout(idleTimerRef.current);
60
+ socket.disconnect();
61
+ viewerServerRef.current?.close();
62
+ setDone(true);
63
+ onSettle(reason);
64
+ };
65
+
66
+ const bumpIdle = () => {
67
+ clearTimeout(idleTimerRef.current);
68
+ idleTimerRef.current = setTimeout(() => {
69
+ appendLine(`\n(không có hoạt động ${Math.round(idleTimeoutMs / 1000)}s - dừng theo dõi; mission có thể vẫn đang chạy nền)`, 'gray');
70
+ settle('idle');
71
+ }, idleTimeoutMs);
72
+ };
73
+
74
+ socket.on('connect_error', (error) => {
75
+ appendLine(`⚠️ Không theo dõi được tiến độ trực tiếp (${error.message}) - mission vẫn tiếp tục.`, 'yellow');
76
+ settle('connect_error');
77
+ });
78
+
79
+ // Học đúng sessionKey (clientId) của phiên HIL hiện tại - browser:cast-start bắn vào room
80
+ // `client:<tenant>` (auto-join, cùng room browser:agent-step dùng - xem comment tại nơi emit
81
+ // trong AIBrowserService.ts), nhưng browser:resolved/cast-error lại bắn vào room
82
+ // `aibrowser:<sessionKey>` (chỉ join khi biết sessionKey, KHÔNG auto-join) - phải tự emit
83
+ // join-room ngay khi biết sessionKey, đúng như browserViewerHtml's script đã làm, nếu không 2
84
+ // event này không bao giờ tới được đây.
85
+ socket.on('browser:cast-start', (payload) => {
86
+ if (!payload?.clientId) return;
87
+ setPausedSessionKey(payload.clientId);
88
+ socket.emit('join-room', { name: 'aivin-cli-tui', rooms: [`aibrowser:${payload.clientId}`] });
89
+ });
90
+ socket.on('browser:resolved', () => setPausedSessionKey(null));
91
+ socket.on('browser:cast-error', (payload) => {
92
+ appendLine(`⚠️ ${payload?.reason || 'Mất kết nối phiên trình duyệt'}`, 'yellow');
93
+ });
94
+
95
+ for (const eventName of MISSION_LOG_EVENTS) {
96
+ socket.on(eventName, (payload) => {
97
+ if (!payload || payload.thread_id !== threadId) return;
98
+ bumpIdle();
99
+ const time = new Date(payload.timestamp || Date.now()).toLocaleTimeString();
100
+ const icon = payload.status === 'error' ? '✗' : payload.status === 'success' ? '✓' : payload.status === 'warning' ? '!' : '·';
101
+ const iconColor = payload.status === 'error' ? 'red' : payload.status === 'success' ? 'green' : payload.status === 'warning' ? 'yellow' : 'gray';
102
+ const label = payload.event_key || eventName;
103
+ appendLine(`[${time}] ${icon} ${label} ${payload.message || ''}`.trimEnd(), iconColor);
104
+
105
+ if (payload.event_key === 'ai_browser.hil_required' && !viewerOpenedRef.current) {
106
+ viewerOpenedRef.current = true;
107
+ sendOSNotification('AI Browser cần bạn hỗ trợ', payload.message || 'Mission đang chờ bạn tương tác');
108
+ if (openViewerOnHIL) {
109
+ appendLine('\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... (hoặc gõ "done" bên dưới sau khi xong)', 'magenta');
110
+ openBrowserViewer(serverUrl, apiKey, tenantClient)
111
+ .then((server) => {
112
+ if (settledRef.current) server.close();
113
+ else viewerServerRef.current = server;
114
+ })
115
+ .catch((e) => appendLine(`⚠️ Không mở được viewer tự động: ${e.message}`, 'yellow'));
116
+ } else {
117
+ appendLine(`\n👤 ${payload.message || 'Mission cần bạn hỗ trợ'} - kiểm tra cửa sổ trình duyệt (banner xanh ở đầu trang), hoặc gõ "done" bên dưới khi xong.`, 'magenta');
118
+ }
119
+ }
120
+ if (payload.event_key === 'ai_browser.success' || payload.event_key === 'ai_browser.failed' || MISSION_DONE_EVENT_KEYS.has(payload.event_key)) {
121
+ const ok = payload.event_key !== 'ai_browser.failed' && payload.status !== 'error';
122
+ sendOSNotification(ok ? '✅ AI Browser hoàn tất' : '❌ AI Browser thất bại', payload.message || '');
123
+ settle(ok ? 'success' : 'failed');
124
+ }
125
+ });
126
+ }
127
+
128
+ socket.on('browser:agent-step', (payload) => {
129
+ if (!payload) return;
130
+ bumpIdle();
131
+ const time = new Date().toLocaleTimeString();
132
+ const icon = STEP_ICON[payload.type] || '·';
133
+ appendLine(`[${time}] ${icon} step ${payload.step} ${payload.type} ${payload.summary || ''}`.trimEnd(), 'cyan');
134
+ if (payload.url) appendLine(` url: ${payload.url}`, 'gray');
135
+ const detail = payload.detail;
136
+ if (Array.isArray(detail)) {
137
+ for (const a of detail) {
138
+ appendLine(` - ${a.type}${a.detail ? ` (${a.detail})` : ''}`, 'gray');
139
+ if (a.reason) appendLine(` reason: ${a.reason}`, 'gray', true);
140
+ }
141
+ } else if (detail && typeof detail === 'object') {
142
+ if (detail.reason) appendLine(` reason: ${detail.reason}`, 'gray', true);
143
+ for (const a of detail.revisedActions || []) {
144
+ appendLine(` - ${a.type}${a.detail ? ` (${a.detail})` : ''}`, 'gray');
145
+ if (a.reason) appendLine(` reason: ${a.reason}`, 'gray', true);
146
+ }
147
+ }
148
+ });
149
+
150
+ appendLine(`📡 Đang theo dõi tiến độ cho ${threadId}... (gõ bên dưới để phản hồi/hướng dẫn, Ctrl+C để dừng theo dõi)\n`, 'gray');
151
+ bumpIdle();
152
+
153
+ return () => {
154
+ clearTimeout(idleTimerRef.current);
155
+ socket.disconnect();
156
+ };
157
+ // Chỉ setup socket 1 lần lúc mount ([] deps có chủ đích) - props (serverUrl/apiKey/threadId/...)
158
+ // không đổi trong suốt đời sống component này (1 lần chạy mission = 1 lần mount).
159
+ }, []);
160
+
161
+ const submit = async (value) => {
162
+ const message = value.trim();
163
+ setInputValue('');
164
+ if (!message || sending) return;
165
+ setSending(true);
166
+ try {
167
+ if (pausedSessionKey) {
168
+ // Đang pause chờ HIL (loại SCREENCAST - captcha/login/2FA, xem escalateToHIL) - kênh này CHỈ
169
+ // mang tín hiệu boolean "xong hay chưa" (resolveSession/escalateToHIL chỉ check
170
+ // hilResult !== 'cancel', KHÔNG đọc nội dung text) - đúng bản chất "user tự thao tác thẳng
171
+ // trên trang thật rồi", không phải "gõ câu trả lời ở đây thay việc thao tác". Enter ở đây
172
+ // tương đương bấm nút "✅ Xong" trên viewer/banner cũ; gõ đúng "cancel" mới có nghĩa khác
173
+ // (huỷ HIL). Bất kỳ text nào khác chỉ có tác dụng như 1 cú Enter trống.
174
+ socketRef.current?.emit('browser:resolve', { clientId: pausedSessionKey, option: message });
175
+ appendLine(`> ${message} (đã gửi tín hiệu hoàn tất HIL - gõ "cancel" nếu muốn huỷ thay vì tiếp tục)`, 'blue');
176
+ // Tự xoá ngay, không đợi round-trip browser:resolved - phòng trường hợp join-room (join lúc
177
+ // cast-start) chưa kịp có hiệu lực phía server khi broadcast resolved bắn ra, khiến state kẹt
178
+ // ở "vẫn đang pause" và mọi input sau đó bị hiểu nhầm là resolve cho session đã đóng.
179
+ setPausedSessionKey(null);
180
+ } else {
181
+ // Mission đang tự chạy - gửi làm hướng dẫn real-time cho vòng plan kế tiếp.
182
+ await axios.post(
183
+ `${serverUrl}/plugins/ai-browser/steer`,
184
+ { message },
185
+ { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } },
186
+ );
187
+ appendLine(`> ${message} (đã gửi làm hướng dẫn - áp dụng ở bước kế tiếp)`, 'blue');
188
+ }
189
+ } catch (e) {
190
+ appendLine(`⚠️ Gửi phản hồi thất bại: ${e.response?.data?.message || e.message}`, 'yellow');
191
+ } finally {
192
+ setSending(false);
193
+ }
194
+ };
195
+
196
+ return h(
197
+ Box,
198
+ { flexDirection: 'column' },
199
+ h(Static, { items: lines }, (item) => h(LogLine, { key: item.id, item })),
200
+ !done &&
201
+ h(
202
+ Box,
203
+ { borderStyle: 'round', borderColor: pausedSessionKey ? 'magenta' : 'blue', paddingX: 1, marginTop: 1 },
204
+ h(Text, { color: pausedSessionKey ? 'magenta' : 'blue' }, pausedSessionKey ? '👤 HIL > ' : '💬 > '),
205
+ h(TextInput, { value: inputValue, onChange: setInputValue, onSubmit: submit }),
206
+ ),
207
+ );
208
+ }
209
+
210
+ /**
211
+ * Thay thế `streamBrowserMissionLog` (missionStream.mjs) khi có TTY thật - cùng semantics resolve
212
+ * (event terminal / idle timeout / Ctrl+C), cùng logic parse event (log/HIL/notification), chỉ khác
213
+ * cách hiển thị (Ink split-view thay vì console.log tuần tự) và thêm được ô input nhận feedback.
214
+ */
215
+ export function runBrowserMissionTui(serverUrl, apiKey, threadId, tenantClient, { idleTimeoutMs = 120_000, openViewerOnHIL = true } = {}) {
216
+ return new Promise((resolve) => {
217
+ let settled = false;
218
+ const onSettle = (reason) => {
219
+ if (settled) return;
220
+ settled = true;
221
+ process.off('SIGINT', onSigint);
222
+ unmount();
223
+ resolve(reason);
224
+ };
225
+ const onSigint = () => onSettle('sigint');
226
+ process.on('SIGINT', onSigint);
227
+
228
+ const { unmount } = render(
229
+ h(MissionTuiApp, { serverUrl, apiKey, threadId, tenantClient, idleTimeoutMs, openViewerOnHIL, onSettle }),
230
+ );
231
+ });
232
+ }
233
+
234
+ /**
235
+ * Chọn đúng cách theo dõi mission: TUI Ink (log cuộn + input cố định) khi có TTY thật cả 2 chiều
236
+ * (stdout để vẽ, stdin để nhận raw-mode input); fallback về `streamBrowserMissionLog` (console.log
237
+ * tuần tự, không nhận input) cho môi trường không có TTY thật (CI, output bị pipe/redirect) - Ink
238
+ * throw ngay khi cố bật raw mode trên stdin không phải TTY.
239
+ */
240
+ export function watchBrowserMission(serverUrl, apiKey, threadId, tenantClient, opts = {}) {
241
+ if (process.stdout.isTTY && process.stdin.isTTY) {
242
+ return runBrowserMissionTui(serverUrl, apiKey, threadId, tenantClient, opts);
243
+ }
244
+ return streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClient, opts);
245
+ }
@@ -169,6 +169,7 @@ const MCP_SCAN_TIMEOUT_MS = 60000;
169
169
  const MCP_BUILD_TIMEOUT_MS = 30000;
170
170
  const MCP_DEPLOY_TIMEOUT_MS = 60000;
171
171
  const MCP_SUBMIT_TIMEOUT_MS = 30000;
172
+ const MCP_WATCH_TIMEOUT_MS = 15000;
172
173
 
173
174
  // ── MCP proxy plugins - wrap an external MCP server tool/resource/prompt, no code required ────
174
175
 
@@ -715,3 +716,58 @@ export async function scanAndPublishMcp(url, options) {
715
716
  }
716
717
  }
717
718
  }
719
+
720
+ function extractApiErrorMessage(error) {
721
+ return error.response?.data?.message?.message || error.response?.data?.message || error.message;
722
+ }
723
+
724
+ /**
725
+ * Register (or reactivate) a server-side watch on a GitHub repo+branch previously scanned via
726
+ * `aivin mcp <url>` - the backend cron-checks the branch's HEAD commit every ~5 min and
727
+ * auto-rescans+resyncs the plugins it owns when it changes. No CLI process needs to stay running;
728
+ * this call just registers the watch and returns.
729
+ */
730
+ export async function registerMcpWatch(url, options = {}) {
731
+ let watch;
732
+ try {
733
+ const res = await withSpinner('👀 Registering watch', () =>
734
+ axios.post(`${connectorBaseUrl()}/plugins/mcp-watch`, { url, branch: options.branch },
735
+ { ...connectorAuthHeaders(), timeout: MCP_WATCH_TIMEOUT_MS }));
736
+ watch = res.data;
737
+ } catch (error) {
738
+ throw new Error(`Watch registration failed: ${extractApiErrorMessage(error)}`, { cause: error });
739
+ }
740
+ console.log(chalk.green(`✅ Watching ${watch.repo_id} @ ${watch.branch}`));
741
+ console.log(chalk.gray(' Checked server-side every ~5 min - no need to keep this terminal open.'));
742
+ }
743
+
744
+ /** Stop auto-resyncing a previously watched repo. Does not touch already-deployed plugins. */
745
+ export async function unwatchMcp(url, options = {}) {
746
+ try {
747
+ await axios.delete(`${connectorBaseUrl()}/plugins/mcp-watch`,
748
+ { ...connectorAuthHeaders(), data: { url, branch: options.branch } });
749
+ } catch (error) {
750
+ throw new Error(`Unwatch failed: ${extractApiErrorMessage(error)}`, { cause: error });
751
+ }
752
+ console.log(chalk.green('✅ Watch removed - deployed plugins are untouched.'));
753
+ }
754
+
755
+ /** List the caller's watched repos. */
756
+ export async function listMcpWatches() {
757
+ let watches;
758
+ try {
759
+ const res = await axios.get(`${connectorBaseUrl()}/plugins/mcp-watch`, connectorAuthHeaders());
760
+ watches = res.data || [];
761
+ } catch (error) {
762
+ throw new Error(`Listing watches failed: ${extractApiErrorMessage(error)}`, { cause: error });
763
+ }
764
+ if (watches.length === 0) {
765
+ console.log(chalk.gray('No watched repos. Run `aivin mcp watch <url>` to add one.'));
766
+ return;
767
+ }
768
+ watches.forEach((w) => {
769
+ console.log(`${chalk.bold(w.repo_id)} @ ${w.branch} ${chalk.gray(`[${w.status}]`)}`);
770
+ console.log(chalk.gray(` sha: ${w.last_known_sha || '(not yet checked)'} last checked: ${w.last_checked_at || 'never'}`));
771
+ if (w.status === 'error') console.log(chalk.red(` ⚠ ${w.last_error}`));
772
+ });
773
+ }
@@ -328,31 +328,35 @@ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClien
328
328
  const statusIcon = (status) =>
329
329
  status === 'error' ? chalk.red('✗') : status === 'success' ? chalk.green('✓') : status === 'warning' ? chalk.yellow('!') : chalk.gray('·');
330
330
 
331
- const stop = () => {
331
+ // `reason` lets the caller (browserAutomation.mjs's tunnel-retry loop) tell a genuine mission
332
+ // outcome ('success'/'failed'/'cancelled') apart from "we just gave up watching"
333
+ // ('idle'/'sigint'/'connect_error') - only the latter group is worth retrying on tunnel drop.
334
+ const stop = (reason) => {
332
335
  if (settled) return;
333
336
  settled = true;
334
337
  clearTimeout(idleTimer);
335
338
  socket.disconnect();
336
- process.off('SIGINT', stop);
339
+ process.off('SIGINT', onSigint);
337
340
  // The auto-opened HIL viewer keeps a listening HTTP server alive (and with it the whole
338
341
  // process) past the point the mission actually finished - close it along with everything else.
339
342
  viewerServer?.close();
340
- resolve();
343
+ resolve(reason);
341
344
  };
342
345
 
343
346
  const bumpIdleTimer = () => {
344
347
  clearTimeout(idleTimer);
345
348
  idleTimer = setTimeout(() => {
346
349
  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();
350
+ stop('idle');
348
351
  }, idleTimeoutMs);
349
352
  };
350
353
 
351
- process.on('SIGINT', stop);
354
+ const onSigint = () => stop('sigint');
355
+ process.on('SIGINT', onSigint);
352
356
 
353
357
  socket.on('connect_error', (error) => {
354
358
  console.log(chalk.yellow(`⚠️ Couldn't watch live progress (${error.message}) - the run continues regardless.`));
355
- stop();
359
+ stop('connect_error');
356
360
  });
357
361
 
358
362
  for (const eventName of MISSION_LOG_EVENTS) {
@@ -397,7 +401,7 @@ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClien
397
401
  if (payload.event_key === 'ai_browser.success' || payload.event_key === 'ai_browser.failed' || MISSION_DONE_EVENT_KEYS.has(payload.event_key)) {
398
402
  const ok = payload.event_key !== 'ai_browser.failed' && payload.status !== 'error';
399
403
  sendOSNotification(ok ? '✅ AI Browser hoàn tất' : '❌ AI Browser thất bại', payload.message || '');
400
- stop();
404
+ stop(ok ? 'success' : 'failed');
401
405
  }
402
406
  });
403
407
  }
@@ -409,7 +413,7 @@ export function streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClien
409
413
  // even though the backend was emitting a full trace the whole time. `detail` (when present)
410
414
  // carries the LLM's actual per-action reasoning (AIBrowserActionItem.reason), not just the
411
415
  // truncated one-line summary meant for a chat bubble.
412
- const STEP_ICON = { perceiving: '👁', executing: '▶', blocked: '🛡', recovering: '↺', auditing: '🔎', done: '✅', failed: '❌' };
416
+ const STEP_ICON = { planning: '📋', perceiving: '👁', executing: '▶', blocked: '🛡', recovering: '↺', auditing: '🔎', done: '✅', failed: '❌' };
413
417
  socket.on('browser:agent-step', (payload) => {
414
418
  if (!payload) return;
415
419
  bumpIdleTimer();
@@ -4,9 +4,10 @@ import fs from 'fs';
4
4
  import path from 'path';
5
5
  import axios from 'axios';
6
6
  import inquirer from 'inquirer';
7
+ import { randomUUID } from 'crypto';
7
8
  import { flattenManifestFile } from '@aivin-labs/sdk';
8
9
  import readline from 'readline';
9
- import { requireArg } from './util.mjs';
10
+ import { requireArg, withProgressSpinner } from './util.mjs';
10
11
 
11
12
  const DELETE_TIMEOUT_MS = 30000;
12
13
 
@@ -73,6 +74,30 @@ export async function watchPluginLogLines(pluginId, { serverUrl, apiKey, onLine
73
74
  return { subscribed, denyReason, stop: () => socket.disconnect() };
74
75
  }
75
76
 
77
+ /**
78
+ * Realtime stage/percent progress for a single `trigger` call — mirrors `withScanLog`/
79
+ * `scanAndPublishMcp` (`mcpProxy.mjs`, used for `aivin mcp <url>`'s scan step): join the Socket.IO
80
+ * room BEFORE the caller sends its POST (so no early progress events are missed), then track the
81
+ * latest `plugin-execute-progress` payload for a spinner to poll. Useful for the same reason as
82
+ * `--watch-logs` — a cold-start Docker install can take 60-150s+ with zero feedback otherwise —
83
+ * but this is on by default (no flag needed) since it's cheap and doesn't require log-view
84
+ * permission the way `--watch-logs` does.
85
+ */
86
+ async function withExecuteProgress(executeSessionId, { serverUrl, apiKey }) {
87
+ const socket = io(serverUrl, { auth: { token: apiKey || 'dev-token' }, transports: ['websocket'], reconnection: true, timeout: 8000 });
88
+ const room = `plugin-execute:${executeSessionId}`;
89
+ let current = { stage: 'starting', percent: 0, message: 'Đang gửi yêu cầu...' };
90
+ await new Promise((resolve) => {
91
+ const giveUp = setTimeout(resolve, 8000);
92
+ socket.on('connect_error', () => { clearTimeout(giveUp); resolve(); });
93
+ socket.on('connect', () => {
94
+ socket.emit('join-room', { name: 'plugin-execute', rooms: [room] }, () => { clearTimeout(giveUp); resolve(); });
95
+ });
96
+ });
97
+ socket.on('plugin-execute-progress', (payload) => { current = payload; });
98
+ return { getCurrent: () => current, stop: () => socket.disconnect() };
99
+ }
100
+
76
101
  /**
77
102
  * `aivin plugin trigger` - invokes an already-deployed plugin for real via the same
78
103
  * `POST /plugins/execute` the platform's own Playground uses (PluginExecutionService.executePlugin
@@ -207,17 +232,22 @@ export async function triggerPlugin(mission, inputJson, options) {
207
232
  }
208
233
  }
209
234
 
210
- console.log(chalk.blue(`🚀 Triggering ${entryLabel || entryId}...`));
235
+ const executeSessionId = randomUUID();
236
+ body.execute_session_id = executeSessionId;
237
+ const progress = await withExecuteProgress(executeSessionId, { serverUrl, apiKey });
211
238
 
212
239
  let response;
213
240
  try {
214
- response = await axios.post(`${serverUrl}/plugins/execute`, body, { ...authHeaders, timeout: EXECUTE_TIMEOUT_MS });
241
+ response = await withProgressSpinner(`🚀 Triggering ${entryLabel || entryId}`, progress.getCurrent, () =>
242
+ axios.post(`${serverUrl}/plugins/execute`, body, { ...authHeaders, timeout: EXECUTE_TIMEOUT_MS }),
243
+ );
215
244
  } catch (error) {
216
245
  if (logWatcher?.subscribed) {
217
246
  // Give trailing log lines from this failed call a moment to arrive before disconnecting.
218
247
  await new Promise((resolve) => setTimeout(resolve, 300));
219
248
  }
220
249
  logWatcher?.stop();
250
+ progress.stop();
221
251
  const message = error.response?.data?.message || error.message;
222
252
  throw new Error(`Trigger failed: ${message}`, { cause: error });
223
253
  }
@@ -226,6 +256,7 @@ export async function triggerPlugin(mission, inputJson, options) {
226
256
  await new Promise((resolve) => setTimeout(resolve, 300));
227
257
  }
228
258
  logWatcher?.stop();
259
+ progress.stop();
229
260
 
230
261
  const result = response.data ?? {};
231
262
 
package/bin/lib/util.mjs CHANGED
@@ -25,6 +25,32 @@ export async function withSpinner(label, fn) {
25
25
  }
26
26
  }
27
27
 
28
+ // Same as withSpinner but also renders a stage/percent readout that changes over time — for calls
29
+ // where the backend publishes realtime progress (e.g. `plugin trigger`'s cold-start Docker install,
30
+ // which can take 60-150s+ with zero feedback otherwise). `getCurrent()` is polled every tick and
31
+ // should return the latest `{ stage, percent, message }` received (or null before anything arrives).
32
+ export async function withProgressSpinner(label, getCurrent, fn) {
33
+ if (!process.stdout.isTTY) {
34
+ console.log(chalk.blue(`${label}...`));
35
+ return fn();
36
+ }
37
+ const frames = ['⠋', '⠙', '⠹', '⠸', '⠼', '⠴', '⠦', '⠧', '⠇', '⠏'];
38
+ let i = 0;
39
+ const timer = setInterval(() => {
40
+ const current = getCurrent?.();
41
+ const suffix = current?.percent != null ? ` ${current.message || current.stage} ${current.percent}%` : '...';
42
+ process.stdout.write(`\r${chalk.cyan(frames[i])} ${label}${suffix}`);
43
+ i = (i + 1) % frames.length;
44
+ }, 100);
45
+ try {
46
+ return await fn();
47
+ } finally {
48
+ clearInterval(timer);
49
+ readline.cursorTo(process.stdout, 0);
50
+ readline.clearLine(process.stdout, 0);
51
+ }
52
+ }
53
+
28
54
  // Positional CLI args are declared optional ([arg]) everywhere, not required (<arg>), so Commander
29
55
  // never hard-fails before the action() runs - every command instead calls this to fill a missing
30
56
  // value interactively. Falls back to throwing `usage` when there's no TTY to prompt on (scripts/
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aivin-labs/cli",
3
- "version": "1.0.3",
3
+ "version": "1.0.4",
4
4
  "description": "aivin CLI - scaffold, run, and deploy Aivin plugins built on @aivin-labs/sdk",
5
5
  "type": "module",
6
6
  "bin": {
@@ -21,12 +21,15 @@
21
21
  "author": "Aivin Team",
22
22
  "license": "MIT",
23
23
  "dependencies": {
24
- "@aivin-labs/sdk": "^1.1.0",
24
+ "@aivin-labs/sdk": "^1.1.2",
25
25
  "axios": "^1.18.1",
26
26
  "chalk": "^5.6.2",
27
27
  "commander": "^15.0.0",
28
28
  "dotenv": "^17.4.2",
29
+ "ink": "^7.1.1",
30
+ "ink-text-input": "^6.0.0",
29
31
  "inquirer": "^14.0.2",
32
+ "react": "^19.2.8",
30
33
  "socket.io-client": "^4.8.3",
31
34
  "ws": "^8.18.0"
32
35
  },