@aivin-labs/cli 1.0.3 → 1.0.5

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
@@ -23,9 +23,9 @@ import { readStdin, createFromJSON, createInteractive, validatePluginConfig, val
23
23
  import { buildDeploymentPayload, deployPlugin, incrementVersion } from './lib/deploy.mjs';
24
24
  import { initInteractive, makePluginFromDescription, convertExistingProject } from './lib/codegen.mjs';
25
25
  import { searchPlugins, showPluginInfo, askPlugin, streamPluginLogs, triggerPlugin, deletePluginCmd } from './lib/pluginTrigger.mjs';
26
- import { connectorAuthHeaders, connectorBaseUrl, listConnectors, registerConnector, searchConnectors } from './lib/connectors.mjs';
26
+ import { connectorAuthHeaders, connectorBaseUrl, listConnectors, registerConnector, searchConnectors, buildRegisterConnectorDto } 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, setFieldConnector } from './lib/mcpProxy.mjs';
29
29
  import {
30
30
  saveGlobalApiKey,
31
31
  browserLogin,
@@ -58,6 +58,7 @@ import {
58
58
  updateTaskById,
59
59
  deleteTaskById,
60
60
  createTask,
61
+ buildCreateTaskPayload,
61
62
  pickWorkspaceAndProject,
62
63
  createProjectCmd,
63
64
  updateProjectCmd,
@@ -393,10 +394,11 @@ pluginCommand
393
394
  .command('ask [mission]')
394
395
  .description('One-shot: search for the best-matching plugin for a plain-language mission and trigger it right away, like an agent would')
395
396
  .option('--top <n>', 'How many candidates to consider/print as runner-up context (default 5) - only the top match is ever run')
396
- .option('-i, --input <json>', 'Force specific fields (as JSON) alongside the auto-mapped ones - explicit fields win')
397
+ .option('-i, --input <json>', 'Input fields as a JSON string - skips the interactive field-by-field prompt')
397
398
  .option('--workspace <id>', 'Workspace id to search/run against (default: auto-picks your first one)')
398
399
  .option('--agent <id>', 'Agent id to run as, if the plugin needs one for HIL/confirm behavior to be accurate')
399
400
  .option('--watch-logs', "Also stream the chosen plugin's own live console output inline")
401
+ .option('--no-auth-prompt', "Don't offer to connect/configure a missing connector interactively when the run comes back needing one - just print the result and exit")
400
402
  .option('--save', 'Write this run\'s result to .test/trigger/<timestamp>.json for later --compare')
401
403
  .option('--compare <file>', 'Diff this run\'s result against a previously --save\'d .test/trigger/*.json file')
402
404
  .action(async (mission, options) => {
@@ -441,12 +443,12 @@ pluginCommand
441
443
  pluginCommand
442
444
  .command('trigger [mission] [input]')
443
445
  .description('Invoke this deployed plugin for real and print the result - like the platform\'s Playground')
444
- .option('-a, --auto <prompt>', 'Natural-language prompt - the platform auto-maps it onto the input schema for you')
445
446
  .option('--id <pluginId>', 'Plugin id to trigger directly - skips the local manifest.json lookup (e.g. for `aivin mcp` plugins, which have no local project directory)')
446
447
  .option('--func <name>', 'Which function to trigger, for a multi-function plugin (matches name/func/id) - ignored when --id is given')
447
448
  .option('--workspace <id>', 'Workspace id to run against (default: auto-picks your first one)')
448
449
  .option('--agent <id>', 'Agent id to run as, if the plugin needs one for HIL/confirm behavior to be accurate')
449
450
  .option('--watch-logs', 'Also stream the plugin\'s own live console output inline (same feed as `aivin plugin logs`) instead of needing a second terminal - requires permission to view that plugin\'s logs (your own/org\'s deployments; most store plugins from other orgs will just skip this and fall back to the REST result only)')
451
+ .option('--no-auth-prompt', "Don't offer to connect/configure a missing connector interactively when the run comes back needing one - just print the result and exit")
450
452
  .option('--save', 'Write this run\'s result to .test/trigger/<timestamp>.json for later --compare')
451
453
  .option('--compare <file>', 'Diff this run\'s result against a previously --save\'d .test/trigger/*.json file')
452
454
  .action(async (mission, input, options) => {
@@ -681,6 +683,7 @@ mcpCommand
681
683
  .option('--private', 'Deploy to your org only - default')
682
684
  .option('--org', 'Alias of --private - there is no narrower per-workspace scope today')
683
685
  .option('--quiet', 'Skip live progress output while scanning (on by default otherwise)')
686
+ .option('-y, --yes', 'Skip the deploy confirmation prompt (required in non-TTY/CI contexts, which otherwise now refuse to deploy at all - see scanAndPublishMcp)')
684
687
  .action(async (url, options) => {
685
688
  try {
686
689
  url = await requireArg(url, {
@@ -723,6 +726,41 @@ mcpCommand
723
726
  }
724
727
  });
725
728
 
729
+ mcpCommand
730
+ .command('watch [url]')
731
+ .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)')
732
+ .option('--branch <name>', "Branch to watch (default: the repo's default branch)")
733
+ .option('--list', 'List your watched repos instead of registering a new one')
734
+ .action(async (url, options) => {
735
+ try {
736
+ if (options.list) {
737
+ await listMcpWatches();
738
+ return;
739
+ }
740
+ url = await requireArg(url, {
741
+ prompt: 'GitHub repo URL to watch:',
742
+ usage: 'Usage: aivin mcp watch <url> [--branch <name>] | aivin mcp watch --list',
743
+ });
744
+ await registerMcpWatch(url, options);
745
+ } catch (error) {
746
+ console.error(chalk.red('❌'), error.message);
747
+ process.exit(1);
748
+ }
749
+ });
750
+
751
+ mcpCommand
752
+ .command('unwatch <url>')
753
+ .description('Stop auto-resyncing a previously watched repo')
754
+ .option('--branch <name>', 'Branch to unwatch (default: all watched branches for this repo)')
755
+ .action(async (url, options) => {
756
+ try {
757
+ await unwatchMcp(url, options);
758
+ } catch (error) {
759
+ console.error(chalk.red('❌'), error.message);
760
+ process.exit(1);
761
+ }
762
+ });
763
+
726
764
  program
727
765
  .command('login')
728
766
  .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`.')
@@ -1050,10 +1088,11 @@ taskCommand
1050
1088
  taskCommand
1051
1089
  .command('delete [id]')
1052
1090
  .description('Delete a task')
1053
- .action(async (id) => {
1091
+ .option('-y, --yes', 'Skip the confirmation prompt (for scripts/CI)')
1092
+ .action(async (id, options) => {
1054
1093
  try {
1055
1094
  id = await requireArg(id, { prompt: 'Task id to delete:', usage: 'Usage: aivin task delete <id>' });
1056
- await deleteTaskById(id);
1095
+ await deleteTaskById(id, options);
1057
1096
  } catch (error) {
1058
1097
  console.error(chalk.red('❌'), error.message);
1059
1098
  process.exit(1);
@@ -1291,6 +1330,7 @@ projectCommand
1291
1330
  .command('delete [id]')
1292
1331
  .description('Delete a project')
1293
1332
  .option('--workspace <id>', 'Workspace id (default: your personal workspace)')
1333
+ .option('-y, --yes', 'Skip the confirmation prompt (for scripts/CI)')
1294
1334
  .action(async (id, options) => {
1295
1335
  try {
1296
1336
  id = await requireArg(id, { prompt: 'Project id to delete:', usage: 'Usage: aivin project delete <id>' });
@@ -1301,7 +1341,7 @@ projectCommand
1301
1341
  }
1302
1342
  });
1303
1343
 
1304
- export { validatePluginConfig, incrementVersion, validateMcpProxyConfig, buildDeploymentPayload, buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName };
1344
+ export { validatePluginConfig, incrementVersion, validateMcpProxyConfig, buildDeploymentPayload, buildMcpManifest, parseMcpArgs, guessConnectorQueryFromEnvVarName, setFieldConnector, buildRegisterConnectorDto, buildCreateTaskPayload };
1305
1345
 
1306
1346
  // Only parse argv when run directly (`aivin ...` / `node bin/cli.mjs ...`),
1307
1347
  // not when this module is imported (e.g. by tests) - otherwise Commander
@@ -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,251 @@
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
+ // ✅ FIX: chưa có listener 'error' nào ở đây - socket.io lỗi phía server (khác connect_error)
79
+ // trước đây sẽ throw và crash cả tiến trình CLI thay vì chỉ dừng theo dõi như connect_error.
80
+ socket.on('error', (error) => {
81
+ appendLine(`⚠️ Lỗi luồng tiến độ (${error?.message || error}) - mission vẫn tiếp tục.`, 'yellow');
82
+ settle('connect_error');
83
+ });
84
+
85
+ // Học đúng sessionKey (clientId) của phiên HIL hiện tại - browser:cast-start bắn vào room
86
+ // `client:<tenant>` (auto-join, cùng room browser:agent-step dùng - xem comment tại nơi emit
87
+ // trong AIBrowserService.ts), nhưng browser:resolved/cast-error lại bắn vào room
88
+ // `aibrowser:<sessionKey>` (chỉ join khi biết sessionKey, KHÔNG auto-join) - phải tự emit
89
+ // join-room ngay khi biết sessionKey, đúng như browserViewerHtml's script đã làm, nếu không 2
90
+ // event này không bao giờ tới được đây.
91
+ socket.on('browser:cast-start', (payload) => {
92
+ if (!payload?.clientId) return;
93
+ setPausedSessionKey(payload.clientId);
94
+ socket.emit('join-room', { name: 'aivin-cli-tui', rooms: [`aibrowser:${payload.clientId}`] });
95
+ });
96
+ socket.on('browser:resolved', () => setPausedSessionKey(null));
97
+ socket.on('browser:cast-error', (payload) => {
98
+ appendLine(`⚠️ ${payload?.reason || 'Mất kết nối phiên trình duyệt'}`, 'yellow');
99
+ });
100
+
101
+ for (const eventName of MISSION_LOG_EVENTS) {
102
+ socket.on(eventName, (payload) => {
103
+ if (!payload || payload.thread_id !== threadId) return;
104
+ bumpIdle();
105
+ const time = new Date(payload.timestamp || Date.now()).toLocaleTimeString();
106
+ const icon = payload.status === 'error' ? '✗' : payload.status === 'success' ? '✓' : payload.status === 'warning' ? '!' : '·';
107
+ const iconColor = payload.status === 'error' ? 'red' : payload.status === 'success' ? 'green' : payload.status === 'warning' ? 'yellow' : 'gray';
108
+ const label = payload.event_key || eventName;
109
+ appendLine(`[${time}] ${icon} ${label} ${payload.message || ''}`.trimEnd(), iconColor);
110
+
111
+ if (payload.event_key === 'ai_browser.hil_required' && !viewerOpenedRef.current) {
112
+ viewerOpenedRef.current = true;
113
+ sendOSNotification('AI Browser cần bạn hỗ trợ', payload.message || 'Mission đang chờ bạn tương tác');
114
+ if (openViewerOnHIL) {
115
+ 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');
116
+ openBrowserViewer(serverUrl, apiKey, tenantClient)
117
+ .then((server) => {
118
+ if (settledRef.current) server.close();
119
+ else viewerServerRef.current = server;
120
+ })
121
+ .catch((e) => appendLine(`⚠️ Không mở được viewer tự động: ${e.message}`, 'yellow'));
122
+ } else {
123
+ 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');
124
+ }
125
+ }
126
+ if (payload.event_key === 'ai_browser.success' || payload.event_key === 'ai_browser.failed' || MISSION_DONE_EVENT_KEYS.has(payload.event_key)) {
127
+ const ok = payload.event_key !== 'ai_browser.failed' && payload.status !== 'error';
128
+ sendOSNotification(ok ? '✅ AI Browser hoàn tất' : '❌ AI Browser thất bại', payload.message || '');
129
+ settle(ok ? 'success' : 'failed');
130
+ }
131
+ });
132
+ }
133
+
134
+ socket.on('browser:agent-step', (payload) => {
135
+ if (!payload) return;
136
+ bumpIdle();
137
+ const time = new Date().toLocaleTimeString();
138
+ const icon = STEP_ICON[payload.type] || '·';
139
+ appendLine(`[${time}] ${icon} step ${payload.step} ${payload.type} ${payload.summary || ''}`.trimEnd(), 'cyan');
140
+ if (payload.url) appendLine(` url: ${payload.url}`, 'gray');
141
+ const detail = payload.detail;
142
+ if (Array.isArray(detail)) {
143
+ for (const a of detail) {
144
+ appendLine(` - ${a.type}${a.detail ? ` (${a.detail})` : ''}`, 'gray');
145
+ if (a.reason) appendLine(` reason: ${a.reason}`, 'gray', true);
146
+ }
147
+ } else if (detail && typeof detail === 'object') {
148
+ if (detail.reason) appendLine(` reason: ${detail.reason}`, 'gray', true);
149
+ for (const a of detail.revisedActions || []) {
150
+ appendLine(` - ${a.type}${a.detail ? ` (${a.detail})` : ''}`, 'gray');
151
+ if (a.reason) appendLine(` reason: ${a.reason}`, 'gray', true);
152
+ }
153
+ }
154
+ });
155
+
156
+ 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');
157
+ bumpIdle();
158
+
159
+ return () => {
160
+ clearTimeout(idleTimerRef.current);
161
+ socket.disconnect();
162
+ };
163
+ // Chỉ setup socket 1 lần lúc mount ([] deps có chủ đích) - props (serverUrl/apiKey/threadId/...)
164
+ // không đổi trong suốt đời sống component này (1 lần chạy mission = 1 lần mount).
165
+ }, []);
166
+
167
+ const submit = async (value) => {
168
+ const message = value.trim();
169
+ setInputValue('');
170
+ if (!message || sending) return;
171
+ setSending(true);
172
+ try {
173
+ if (pausedSessionKey) {
174
+ // Đang pause chờ HIL (loại SCREENCAST - captcha/login/2FA, xem escalateToHIL) - kênh này CHỈ
175
+ // mang tín hiệu boolean "xong hay chưa" (resolveSession/escalateToHIL chỉ check
176
+ // hilResult !== 'cancel', KHÔNG đọc nội dung text) - đúng bản chất "user tự thao tác thẳng
177
+ // 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
178
+ // tương đương bấm nút "✅ Xong" trên viewer/banner cũ; gõ đúng "cancel" mới có nghĩa khác
179
+ // (huỷ HIL). Bất kỳ text nào khác chỉ có tác dụng như 1 cú Enter trống.
180
+ socketRef.current?.emit('browser:resolve', { clientId: pausedSessionKey, option: message });
181
+ 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');
182
+ // Tự xoá ngay, không đợi round-trip browser:resolved - phòng trường hợp join-room (join lúc
183
+ // 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
184
+ // ở "vẫn đang pause" và mọi input sau đó bị hiểu nhầm là resolve cho session đã đóng.
185
+ setPausedSessionKey(null);
186
+ } else {
187
+ // Mission đang tự chạy - gửi làm hướng dẫn real-time cho vòng plan kế tiếp.
188
+ await axios.post(
189
+ `${serverUrl}/plugins/ai-browser/steer`,
190
+ { message },
191
+ { headers: { Authorization: `Bearer ${apiKey || 'dev-token'}` } },
192
+ );
193
+ appendLine(`> ${message} (đã gửi làm hướng dẫn - áp dụng ở bước kế tiếp)`, 'blue');
194
+ }
195
+ } catch (e) {
196
+ appendLine(`⚠️ Gửi phản hồi thất bại: ${e.response?.data?.message || e.message}`, 'yellow');
197
+ } finally {
198
+ setSending(false);
199
+ }
200
+ };
201
+
202
+ return h(
203
+ Box,
204
+ { flexDirection: 'column' },
205
+ h(Static, { items: lines }, (item) => h(LogLine, { key: item.id, item })),
206
+ !done &&
207
+ h(
208
+ Box,
209
+ { borderStyle: 'round', borderColor: pausedSessionKey ? 'magenta' : 'blue', paddingX: 1, marginTop: 1 },
210
+ h(Text, { color: pausedSessionKey ? 'magenta' : 'blue' }, pausedSessionKey ? '👤 HIL > ' : '💬 > '),
211
+ h(TextInput, { value: inputValue, onChange: setInputValue, onSubmit: submit }),
212
+ ),
213
+ );
214
+ }
215
+
216
+ /**
217
+ * Thay thế `streamBrowserMissionLog` (missionStream.mjs) khi có TTY thật - cùng semantics resolve
218
+ * (event terminal / idle timeout / Ctrl+C), cùng logic parse event (log/HIL/notification), chỉ khác
219
+ * cách hiển thị (Ink split-view thay vì console.log tuần tự) và thêm được ô input nhận feedback.
220
+ */
221
+ export function runBrowserMissionTui(serverUrl, apiKey, threadId, tenantClient, { idleTimeoutMs = 120_000, openViewerOnHIL = true } = {}) {
222
+ return new Promise((resolve) => {
223
+ let settled = false;
224
+ const onSettle = (reason) => {
225
+ if (settled) return;
226
+ settled = true;
227
+ process.off('SIGINT', onSigint);
228
+ unmount();
229
+ resolve(reason);
230
+ };
231
+ const onSigint = () => onSettle('sigint');
232
+ process.on('SIGINT', onSigint);
233
+
234
+ const { unmount } = render(
235
+ h(MissionTuiApp, { serverUrl, apiKey, threadId, tenantClient, idleTimeoutMs, openViewerOnHIL, onSettle }),
236
+ );
237
+ });
238
+ }
239
+
240
+ /**
241
+ * 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
242
+ * (stdout để vẽ, stdin để nhận raw-mode input); fallback về `streamBrowserMissionLog` (console.log
243
+ * 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
244
+ * throw ngay khi cố bật raw mode trên stdin không phải TTY.
245
+ */
246
+ export function watchBrowserMission(serverUrl, apiKey, threadId, tenantClient, opts = {}) {
247
+ if (process.stdout.isTTY && process.stdin.isTTY) {
248
+ return runBrowserMissionTui(serverUrl, apiKey, threadId, tenantClient, opts);
249
+ }
250
+ return streamBrowserMissionLog(serverUrl, apiKey, threadId, tenantClient, opts);
251
+ }