@aivin-labs/cli 1.0.0 → 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.
@@ -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
+ }
@@ -210,6 +210,7 @@ export async function registerConnector() {
210
210
  );
211
211
  console.log(chalk.green(`\n✅ Registered connector "${res.data.connector.id}"`));
212
212
  console.log(chalk.gray(` Reference it from a plugin manifest's connection_id: "${res.data.connector.id}"`));
213
+ return res.data.connector;
213
214
  } catch (error) {
214
215
  const message = error.response?.data?.message?.message || error.response?.data?.message || error.message;
215
216
  throw new Error(`Register failed: ${message}`, { cause: error });
@@ -146,13 +146,51 @@ export async function smokeTestEntry(serverUrl, authHeaders, entry, workspaceId)
146
146
  return result;
147
147
  }
148
148
 
149
+ /**
150
+ * Invokes a proxy entry with empty input - `--verify-proxy` opt-in only counterpart to
151
+ * `smokeTestEntry`. Unlike code plugins, there's no AI-generated sample input to fall back on (a
152
+ * proxy's `input` schema is the generic `{ data: object }` passthrough - `generate-sample-data`
153
+ * has nothing meaningful to infer from that), so this sends an empty `arguments: {}` instead:
154
+ * enough to prove the MCP server is reachable and the tool/resource/prompt name resolves, without
155
+ * pretending to know what a "realistic" call looks like for an arbitrary external server.
156
+ */
157
+ export async function smokeTestProxyEntry(serverUrl, authHeaders, entry, workspaceId) {
158
+ const result = { plugin_id: entry.id, name: entry.name, func: entry.func || undefined };
159
+
160
+ const start = Date.now();
161
+ try {
162
+ const execRes = await axios.post(
163
+ `${serverUrl}/plugins/execute`,
164
+ { plugin_id: entry.id, arguments: {}, workspace_id: workspaceId, purpose: 'aivin test --verify-proxy - automated smoke test' },
165
+ authHeaders,
166
+ );
167
+ result.duration_ms = Date.now() - start;
168
+ result.response = execRes.data;
169
+ const status = String(execRes.data?.status || '').toLowerCase();
170
+ result.passed = ['success', 'waiting', 'needs_auth', 'hil_timeout'].includes(status) || execRes.data?.status === undefined;
171
+ } catch (error) {
172
+ result.duration_ms = Date.now() - start;
173
+ result.passed = false;
174
+ result.error = error.response?.data?.message || error.message;
175
+ }
176
+ return result;
177
+ }
178
+
149
179
  /**
150
180
  * Runs `smokeTestEntry` for every non-proxy entry and writes a JSON report to `.test/` in the
151
181
  * current project - one file per `aivin test` run, so you can diff/compare across runs.
182
+ *
183
+ * Proxy entries are skipped by default - calling an arbitrary external MCP server automatically,
184
+ * with no way to know whether that call is safe to repeat (an email-sending tool isn't idempotent
185
+ * the way a read-only one is), isn't something to do without the developer explicitly asking for
186
+ * it. `verifyProxy: true` (`aivin test --verify-proxy`) opts into `smokeTestProxyEntry` for those
187
+ * entries instead of skipping them - only pass it if you know what the underlying tool(s) do.
152
188
  */
153
- export async function runSmokeTest({ currentDir, serverUrl, apiKey, entries, isProxyPlugin, workspaceOverride }) {
154
- if (isProxyPlugin) {
155
- console.log(chalk.gray(' Proxy plugin - no generic smoke test to run (calls an external system, not your code).'));
189
+ export async function runSmokeTest({ currentDir, serverUrl, apiKey, entries, isProxyPlugin, workspaceOverride, verifyProxy }) {
190
+ const hasProxyEntries = entries.some((e) => e.proxy_config);
191
+
192
+ if (isProxyPlugin && !verifyProxy) {
193
+ console.log(chalk.gray(' Proxy plugin - no generic smoke test to run (calls an external system, not your code). Pass --verify-proxy to invoke it for real instead.'));
156
194
  return;
157
195
  }
158
196
 
@@ -175,6 +213,9 @@ export async function runSmokeTest({ currentDir, serverUrl, apiKey, entries, isP
175
213
  }
176
214
 
177
215
  console.log(chalk.blue('🧪 Running smoke test (generated input, real invoke)...'));
216
+ if (hasProxyEntries && verifyProxy) {
217
+ console.log(chalk.yellow('⚠️ --verify-proxy: invoking the real external MCP server(s) below with empty input - only use this if you know calling them has no meaningful side effects.'));
218
+ }
178
219
  // Give the container a moment to finish binding its gRPC server after the build/up completed.
179
220
  await new Promise((resolve) => setTimeout(resolve, 3000));
180
221
 
@@ -182,10 +223,27 @@ export async function runSmokeTest({ currentDir, serverUrl, apiKey, entries, isP
182
223
  for (const entry of entries) {
183
224
  // A mixed multi-function batch can have some proxy entries and some real-code entries (see
184
225
  // buildDeploymentPayload's doc comment) - the batch-level `isProxyPlugin` check above only
185
- // catches the all-proxy case, so skip proxy entries individually here too: they call an
186
- // external system, not your code, same reasoning as the early-return above.
226
+ // catches the all-proxy case, so every proxy entry is handled here individually too: they call
227
+ // an external system, not your code, same reasoning as the early-return above.
187
228
  if (entry.proxy_config) {
188
- console.log(chalk.gray(` ${entry.name} - proxy plugin, no generic smoke test to run`));
229
+ if (!verifyProxy) {
230
+ console.log(chalk.gray(` ${entry.name} - proxy plugin, no generic smoke test to run`));
231
+ continue;
232
+ }
233
+ // `request_hil` is set when the MCP server itself declared this tool destructive/non-readonly
234
+ // (see the backend's McpAdapter.annotationsSuggestHil, sourced from the MCP spec's own
235
+ // readOnlyHint/destructiveHint annotations) - a real signal from the tool's own author, not a
236
+ // guess. `--verify-proxy` already only exists for tools the caller has vetted as safe to call
237
+ // automatically; skip the ones the server itself flagged as NOT safe to call blind, even under
238
+ // that flag, rather than trusting the caller to have known this too.
239
+ if (entry.request_hil) {
240
+ console.log(chalk.yellow(` ${entry.name} - skipped: this tool is flagged destructive/non-readonly by the MCP server itself (request_hil) - verify it manually instead`));
241
+ continue;
242
+ }
243
+ const proxyResult = await smokeTestProxyEntry(serverUrl, authHeaders, entry, workspaceId);
244
+ results.push(proxyResult);
245
+ const proxyIcon = proxyResult.passed ? chalk.green('✅') : chalk.red('❌');
246
+ console.log(` ${proxyIcon} ${entry.name} (proxy) - ${proxyResult.passed ? `passed (${proxyResult.duration_ms}ms)` : `failed: ${proxyResult.error || 'unexpected status'}`}`);
189
247
  continue;
190
248
  }
191
249
  const result = await smokeTestEntry(serverUrl, authHeaders, entry, workspaceId);
@@ -211,7 +269,7 @@ export async function runSmokeTest({ currentDir, serverUrl, apiKey, entries, isP
211
269
  }
212
270
  }
213
271
 
214
- export async function deployPlugin({ endpointPath, label, smokeTest, workspaceOverride }) {
272
+ export async function deployPlugin({ endpointPath, label, smokeTest, workspaceOverride, verifyProxy }) {
215
273
  console.log(chalk.blue(`🚀 ${label}...`));
216
274
 
217
275
  const currentDir = process.cwd();
@@ -325,7 +383,7 @@ export async function deployPlugin({ endpointPath, label, smokeTest, workspaceOv
325
383
  }
326
384
 
327
385
  if (smokeTest) {
328
- await runSmokeTest({ currentDir, serverUrl, apiKey, entries, isProxyPlugin, workspaceOverride });
386
+ await runSmokeTest({ currentDir, serverUrl, apiKey, entries, isProxyPlugin, workspaceOverride, verifyProxy });
329
387
  }
330
388
  } catch (error) {
331
389
  clearInterval(loadingInterval);