@aivin-labs/cli 1.0.64 → 1.0.66

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.
@@ -55,6 +55,10 @@ import {
55
55
  import { CastConsentDecision, createCastConsent } from './desktop/castConsent.mjs';
56
56
  import { castViewerInfo, castViewerLabel, createCastTrust, createDeviceProver } from './desktop/castTrust.mjs';
57
57
  import { createCastTouchViewers, shouldDrawCursorInFrame } from './desktop/castTouchViewers.mjs';
58
+ import { prepareHumanIdle, readHumanIdleMs } from './desktop/humanIdle.mjs';
59
+ import { prepareIdentify, showIdentify } from './desktop/identifyOverlay.mjs';
60
+ import { findWindowTitle, prepareWindowProbe } from './desktop/windowProbe.mjs';
61
+ import { isOwnAddress } from './desktop/desktopWebRtc.mjs';
58
62
  import { createConfirmBarrier } from './confirmBarrier.mjs';
59
63
  import { newInputTag } from './humanInput.mjs';
60
64
  import {
@@ -1198,6 +1202,8 @@ export async function startRemoteClient(options = {}) {
1198
1202
  // Chưa nối thì thôi: lần chào khi nối mang theo hồ sơ mới.
1199
1203
  announceProfile = () => (socket.connected ? announce() : undefined);
1200
1204
  socket.on('connect', guarded('connect', async () => {
1205
+ // Dựng sẵn exe đọc thời gian rảnh tay + exe hiện tên máy (lần đầu ~1–2 s csc) để lần máy chủ hỏi đầu tiên không quá hạn.
1206
+ void prepareHumanIdle().then(() => prepareIdentify()).then(() => prepareWindowProbe());
1201
1207
  confirmServerCredentialMigration(serverUrl);
1202
1208
  await announce();
1203
1209
  flushUnsent();
@@ -1407,6 +1413,27 @@ export async function startRemoteClient(options = {}) {
1407
1413
  if (!payload?.session_id || payload.session_id !== desktopCast.sessionId()) return;
1408
1414
  castGate.setHumanTakeover(payload.active === true ? { idleMs: Number(payload.idle_ms), maxWaitMs: Number(payload.max_wait_ms) } : null);
1409
1415
  }));
1416
+ // Máy chủ hỏi máy rảnh tay bao lâu để biết trình duyệt có đang mở ngay trên máy này không (chỉ trả con số, không lộ gì khác).
1417
+ socket.on(DeviceEvent.HUMAN_IDLE, guarded(DeviceEvent.HUMAN_IDLE, async (_payload, ack) => {
1418
+ if (typeof ack !== 'function') return;
1419
+ const idleMs = await readHumanIdleMs();
1420
+ ack(idleMs === null ? { ok: false } : { ok: true, idle_ms: idleMs });
1421
+ }));
1422
+ // Máy chủ hỏi trình duyệt xem màn hình có đang mở ngay trên máy này không (chỉ trả có / không): (1) có cửa sổ mang mã trang vừa gắn vào tiêu
1423
+ // đề tab; (2) IP trình duyệt (máy chủ thấy) đang gắn trên card mạng của máy — IPv6 công cộng là của riêng từng máy, Windows giữ cùng lúc
1424
+ // nhiều địa chỉ tạm nên so ở đây đúng cả khi địa chỉ vừa đổi (máy chủ so với IP lúc máy nối thì trượt).
1425
+ socket.on(DeviceEvent.WINDOW_PROBE, guarded(DeviceEvent.WINDOW_PROBE, async (payload, ack) => {
1426
+ if (typeof ack !== 'function') return;
1427
+ const ips = (Array.isArray(payload?.viewer_ips) ? payload.viewer_ips : []).slice(0, 8).filter((ip) => typeof ip === 'string');
1428
+ const ownIp = ips.some((ip) => isOwnAddress(ip));
1429
+ const found = payload?.nonce ? await findWindowTitle(payload.nonce) : null;
1430
+ ack({ ok: true, found: found === true, own_ip: ownIp, ...(payload?.nonce && found === null ? { title_unknown: true } : {}) });
1431
+ }));
1432
+ // Chủ máy rê chuột lên dòng máy này trên web → hiện tên máy to trên màn hình vài giây (không lấy tiêu điểm, bấm xuyên qua được).
1433
+ socket.on(DeviceEvent.IDENTIFY, guarded(DeviceEvent.IDENTIFY, async (payload) => {
1434
+ if (isRemotePaused()) return;
1435
+ await showIdentify({ name: payload?.name, durationMs: payload?.duration_ms, lang: mascotLang() });
1436
+ }));
1410
1437
  socket.on(DeviceEvent.DESKTOP_CAST_SIGNAL, guarded(DeviceEvent.DESKTOP_CAST_SIGNAL, (payload) => {
1411
1438
  if (payload?.type === 'device_proof') return castProver.answer(payload);
1412
1439
  void desktopWebRtc.signal(payload).catch(() => undefined);
@@ -107,6 +107,22 @@ export const DeviceEvent = Object.freeze({
107
107
  DESKTOP_CAST_INPUT_FOCUS: 'device:desktop_cast_input_focus',
108
108
  /** BE → CLI: người xem tạm cầm lái khi AI đang chạy / trả lại — `{ session_id, active, idle_ms, max_wait_ms }`. */
109
109
  DESKTOP_CAST_TAKEOVER: 'device:desktop_cast_takeover',
110
+ /**
111
+ * BE → CLI (16/11/2026): máy rảnh tay bao lâu — ack `{ ok, idle_ms }`. Máy chủ dùng để biết trình duyệt có đang mở ngay trên máy này không
112
+ * (hai PC cùng mạng trùng IP công cộng). Chỉ máy khai `cast_features: ['human_idle']` mới được hỏi.
113
+ */
114
+ HUMAN_IDLE: 'device:human_idle',
115
+ /**
116
+ * BE → CLI (16/11/2026): trình duyệt xem màn hình có đang mở ngay trên máy này không — `{ nonce?, viewer_ips? }`, ack `{ ok, found, own_ip }`:
117
+ * có cửa sổ mang mã trang gắn vào tiêu đề tab / IP trình duyệt đang gắn trên card mạng của máy. Có ⇒ xem sẽ thành hình lặp. Chỉ máy khai
118
+ * `cast_features: ['window_probe']` mới được hỏi.
119
+ */
120
+ WINDOW_PROBE: 'device:window_probe',
121
+ /**
122
+ * BE → CLI (16/11/2026): hiện tên máy to giữa mọi màn hình `{ name, duration_ms }` — người dùng rê chuột lên dòng máy này trong menu chọn
123
+ * máy trên web. Chỉ máy khai `cast_features: ['identify']` mới nhận.
124
+ */
125
+ IDENTIFY: 'device:identify',
110
126
  });
111
127
 
112
128
  /** Trạng thái phiên xem màn hình gửi BE (`device:desktop_cast_status`) — khớp BE `DesktopCastState`. */
@@ -0,0 +1,72 @@
1
+ import { createHash } from 'crypto';
2
+ import { execFile } from 'child_process';
3
+ import fs from 'fs';
4
+ import path from 'path';
5
+ import { REMOTE_CONFIG_DIR } from '../constants.mjs';
6
+
7
+ /**
8
+ * Tệp exe nhỏ biên dịch MỘT lần bằng csc của .NET Framework có sẵn trong Windows (16/11/2026, cùng cách dpapiHelper): chạy ~30 ms thay vì
9
+ * 1–2 s biên dịch Add-Type của PowerShell mỗi lần. Đặt trong `~/.aivin/bin` (thư mục bị chặn với mọi công cụ từ xa), tên mang dấu vân tay mã
10
+ * nguồn nên đổi mã là dựng bản mới. Không dựng được (không phải Windows, máy chặn csc, diệt virus xoá tệp) → `null`, không thử lại trong 24 h.
11
+ */
12
+
13
+ const BIN_DIR = path.join(REMOTE_CONFIG_DIR, 'bin');
14
+ const RETRY_AFTER_FAIL_MS = 24 * 3600_000;
15
+ const BUILD_TIMEOUT_MS = 60_000;
16
+
17
+ export const CscTarget = Object.freeze({ CONSOLE: 'exe', WINDOWS: 'winexe' });
18
+
19
+ export function runFile(file, args, { timeout, execFileImpl = execFile } = {}) {
20
+ return new Promise((resolve, reject) => {
21
+ execFileImpl(file, args, { timeout, windowsHide: true, encoding: 'utf8' }, (error, stdout) => (error ? reject(error) : resolve(String(stdout || ''))));
22
+ });
23
+ }
24
+
25
+ function cscPath(env = process.env) {
26
+ const windir = env.WINDIR || env.SystemRoot || 'C:\\Windows';
27
+ return ['Framework64', 'Framework'].map((d) => path.join(windir, 'Microsoft.NET', d, 'v4.0.30319', 'csc.exe')).find((p) => fs.existsSync(p)) || null;
28
+ }
29
+
30
+ /** @param {{ name: string, source: string, refs?: string[], target?: string }} spec */
31
+ export function createCscExe({ name, source, refs = [], target = CscTarget.CONSOLE }) {
32
+ const version = createHash('sha256').update(source).update(refs.join(',')).update(target).digest('hex').slice(0, 10);
33
+ const exePath = path.join(BIN_DIR, `${name}-${version}.exe`);
34
+ const failedMark = path.join(BIN_DIR, `${name}-${version}.failed`);
35
+ let building = null;
36
+
37
+ const recentlyFailed = () => {
38
+ try { return Date.now() - fs.statSync(failedMark).mtimeMs < RETRY_AFTER_FAIL_MS; } catch { return false; }
39
+ };
40
+
41
+ async function build() {
42
+ const csc = cscPath();
43
+ if (!csc) return null;
44
+ fs.mkdirSync(BIN_DIR, { recursive: true });
45
+ const src = path.join(BIN_DIR, `${name}-${version}.cs`);
46
+ const tmp = `${exePath}.${process.pid}.tmp`;
47
+ try {
48
+ fs.writeFileSync(src, source, 'utf8');
49
+ await runFile(csc, ['-nologo', `-target:${target}`, '-optimize+', ...refs.map((r) => `-r:${r}`), `-out:${tmp}`, src], { timeout: BUILD_TIMEOUT_MS });
50
+ fs.renameSync(tmp, exePath);
51
+ return exePath;
52
+ } catch {
53
+ try { fs.rmSync(tmp, { force: true }); } catch { /* không có thì thôi */ }
54
+ try { fs.writeFileSync(failedMark, new Date().toISOString()); } catch { /* chỉ là dấu */ }
55
+ return fs.existsSync(exePath) ? exePath : null;
56
+ } finally {
57
+ try { fs.rmSync(src, { force: true }); } catch { /* không có thì thôi */ }
58
+ }
59
+ }
60
+
61
+ /** Đường dẫn exe, dựng lần đầu nếu cần (không chặn vòng sự kiện); `null` khi không dựng được. */
62
+ function prepare({ platform = process.platform } = {}) {
63
+ if (platform !== 'win32') return Promise.resolve(null);
64
+ if (building) return building;
65
+ if (fs.existsSync(exePath)) return (building = Promise.resolve(exePath));
66
+ if (recentlyFailed()) return (building = Promise.resolve(null));
67
+ building = build().catch(() => null);
68
+ return building;
69
+ }
70
+
71
+ return { path: exePath, prepare, reset: () => { building = null; } };
72
+ }