@aivin-labs/cli 1.0.11 → 1.0.21

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.
Files changed (88) hide show
  1. package/README.md +325 -288
  2. package/bin/cli.mjs +163 -17
  3. package/bin/lib/localPreview.mjs +437 -0
  4. package/bin/lib/openFile.mjs +235 -0
  5. package/bin/lib/previewCache.mjs +71 -0
  6. package/bin/lib/remote/atomicFile.mjs +32 -0
  7. package/bin/lib/remote/autoStart.mjs +2 -1
  8. package/bin/lib/remote/autoUpdate.mjs +12 -0
  9. package/bin/lib/remote/browserTunnel.mjs +47 -8
  10. package/bin/lib/remote/callLedger.mjs +94 -14
  11. package/bin/lib/remote/cdpPolicy.mjs +14 -2
  12. package/bin/lib/remote/client.mjs +1024 -808
  13. package/bin/lib/remote/cloudFiles.mjs +53 -0
  14. package/bin/lib/remote/codingAgents.mjs +2 -2
  15. package/bin/lib/remote/constants.mjs +261 -234
  16. package/bin/lib/remote/credentials.mjs +81 -4
  17. package/bin/lib/remote/daemonLock.mjs +57 -17
  18. package/bin/lib/remote/dailyBrowser.mjs +8 -2
  19. package/bin/lib/remote/desktop/castInput.mjs +98 -0
  20. package/bin/lib/remote/desktop/desktopCast.mjs +334 -0
  21. package/bin/lib/remote/desktop/desktopCastCaptureSource.mjs +598 -0
  22. package/bin/lib/remote/desktop/desktopCastSource.mjs +798 -0
  23. package/bin/lib/remote/desktop/desktopWebRtc.mjs +242 -0
  24. package/bin/lib/remote/desktop/fileAssociation.mjs +108 -0
  25. package/bin/lib/remote/desktop/index.mjs +58 -7
  26. package/bin/lib/remote/desktop/linux.mjs +1 -1
  27. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -427
  28. package/bin/lib/remote/desktop/mac.mjs +2 -2
  29. package/bin/lib/remote/desktop/macTraySource.mjs +293 -292
  30. package/bin/lib/remote/desktop/strings.mjs +28 -2
  31. package/bin/lib/remote/desktop/traySource.mjs +905 -527
  32. package/bin/lib/remote/desktop/webrtcRuntime.mjs +137 -0
  33. package/bin/lib/remote/desktop/webrtcWorker.mjs +181 -0
  34. package/bin/lib/remote/deviceProfile.mjs +1 -0
  35. package/bin/lib/remote/docText.mjs +85 -0
  36. package/bin/lib/remote/fileIndexer.mjs +773 -399
  37. package/bin/lib/remote/folderRules.mjs +143 -0
  38. package/bin/lib/remote/gitSafe.mjs +31 -0
  39. package/bin/lib/remote/gui/index.mjs +170 -19
  40. package/bin/lib/remote/gui/officeHostSource.mjs +635 -393
  41. package/bin/lib/remote/gui/windowsHost.mjs +12 -3
  42. package/bin/lib/remote/gui/windowsHostSource.mjs +461 -87
  43. package/bin/lib/remote/httpTransfer.mjs +64 -3
  44. package/bin/lib/remote/idempotency.mjs +49 -20
  45. package/bin/lib/remote/localPolicy.mjs +81 -9
  46. package/bin/lib/remote/mascot/ask.mjs +207 -42
  47. package/bin/lib/remote/mascot/askBlocksSource.mjs +286 -0
  48. package/bin/lib/remote/mascot/askHostSource.mjs +658 -512
  49. package/bin/lib/remote/mascot/blocks.mjs +201 -0
  50. package/bin/lib/remote/mascot/bot.mjs +54 -5
  51. package/bin/lib/remote/mascot/chartLayout.mjs +382 -0
  52. package/bin/lib/remote/mascot/diagramRender.mjs +154 -0
  53. package/bin/lib/remote/mascot/emojiSource.mjs +273 -0
  54. package/bin/lib/remote/mascot/fileChips.mjs +62 -0
  55. package/bin/lib/remote/mascot/hostSource.mjs +331 -52
  56. package/bin/lib/remote/mascot/hotkey.mjs +31 -7
  57. package/bin/lib/remote/mascot/images.mjs +111 -0
  58. package/bin/lib/remote/mascot/index.mjs +663 -493
  59. package/bin/lib/remote/mascot/lucideIcons.mjs +32 -0
  60. package/bin/lib/remote/mascot/mermaidBundle.mjs +28 -0
  61. package/bin/lib/remote/mascot/mood.mjs +57 -0
  62. package/bin/lib/remote/mascot/rigSource.mjs +648 -609
  63. package/bin/lib/remote/mascot/safeUrl.mjs +29 -0
  64. package/bin/lib/remote/mascot/strings.mjs +456 -375
  65. package/bin/lib/remote/mascot/ui.mjs +27 -7
  66. package/bin/lib/remote/multiUser.mjs +7 -2
  67. package/bin/lib/remote/notify.mjs +4 -1
  68. package/bin/lib/remote/office/index.mjs +12 -6
  69. package/bin/lib/remote/osSearch.mjs +107 -0
  70. package/bin/lib/remote/processes.mjs +5 -2
  71. package/bin/lib/remote/sandbox.mjs +26 -0
  72. package/bin/lib/remote/secretPaths.mjs +21 -0
  73. package/bin/lib/remote/sqliteDb.mjs +51 -0
  74. package/bin/lib/remote/tokenRotation.mjs +28 -0
  75. package/bin/lib/remote/toolHandlers.mjs +852 -741
  76. package/bin/lib/remote/watchBatcher.mjs +56 -0
  77. package/bin/lib/remoteControl.mjs +26 -26
  78. package/bin/lib/selfUpdate.mjs +12 -2
  79. package/bin/lib/update/binarySwap.mjs +15 -1
  80. package/bin/lib/update/state.mjs +10 -0
  81. package/docs/AIVIN_MASCOT.md +14 -0
  82. package/docs/CLI.md +1545 -1484
  83. package/docs/media/aivin-ecosystem.jpg +0 -0
  84. package/docs/media/aivin-mascot-live.gif +0 -0
  85. package/docs/media/aivin-mascot-live.png +0 -0
  86. package/docs/media/aivin-remote-architecture.svg +102 -0
  87. package/package.json +75 -71
  88. package/docs/media/aivin-mascot-states.mp4 +0 -0
@@ -6,6 +6,7 @@ import { randomUUID } from 'crypto';
6
6
  import { DEVICE_API_PREFIX, DEVICE_CREDENTIALS_FILE, DEVICE_ID_FILE, REMOTE_CONFIG_DIR } from './constants.mjs';
7
7
  import { parseApiKeyClient } from '../auth.mjs';
8
8
  import { TokenStoreKind, forgetToken, openToken, preferredTokenStore, sealToken } from './tokenStore.mjs';
9
+ import { writeFileAtomic } from './atomicFile.mjs';
9
10
 
10
11
  /** Mã máy ổn định (~/.aivin/device-id.json), giữ qua các lần chạy. */
11
12
  export function getOrCreateDeviceId() {
@@ -43,14 +44,33 @@ function readRecord() {
43
44
  }
44
45
  }
45
46
 
47
+ /** Ghi nguyên tử (02/11/2026 — trước đây ghi thẳng, máy tắt / daemon bị giết giữa lúc ghi là tệp cụt → mất ghép máy). */
46
48
  function writeRecord(record) {
47
- fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
48
49
  const raw = JSON.stringify(record, null, 2) + '\n';
49
- fs.writeFileSync(DEVICE_CREDENTIALS_FILE, raw, { mode: 0o600 });
50
+ writeFileAtomic(DEVICE_CREDENTIALS_FILE, raw);
50
51
  try { fs.chmodSync(DEVICE_CREDENTIALS_FILE, 0o600); } catch { /* Windows: quyền theo ACL hồ sơ người dùng */ }
51
52
  return raw;
52
53
  }
53
54
 
55
+ /**
56
+ * Trường do TỆP làm chủ (02/11/2026) — bản trong bộ nhớ của người gọi có thể đã cũ (daemon nạp lúc khởi động), nên khi lưu luôn lấy theo
57
+ * tệp trên đĩa, trừ khi đổi tường minh qua tham số:
58
+ * - `previous_sealed`: token CŨ (cất vào kho bí mật như token chính) giữ tới khi máy chủ xác nhận token xoay vòng mới;
59
+ * - `policy_sealed_at`: máy này đã từng có luật tại máy CÓ CHỮ KÝ (localPolicy.mjs) — xoá cả tệp luật lẫn tệp khoá không đưa được luật về
60
+ * mặc định một cách lặng lẽ.
61
+ */
62
+ const DISK_OWNED_FIELDS = ['previous_sealed', 'policy_sealed_at'];
63
+ const PREVIOUS_SUFFIX = ':previous';
64
+
65
+ function sealPrevious(token, deviceId) {
66
+ const account = `${deviceId}${PREVIOUS_SUFFIX}`;
67
+ const { fallback_reason: _why, ...sealed } = sealToken(token, { account });
68
+ return { ...sealed, account };
69
+ }
70
+
71
+ const openPrevious = (rec) => (rec && typeof rec === 'object' ? openToken({ ...rec, device_id: rec.account }) : null);
72
+ const forgetPrevious = (rec) => { if (rec && typeof rec === 'object') forgetToken({ ...rec, device_id: rec.account }); };
73
+
54
74
  /** Cất vào kho bí mật hỏng gần đây → không thử lại mỗi lần đọc (mỗi lần thử là một tiến trình PowerShell). */
55
75
  const SEAL_RETRY_MS = 24 * 3600_000;
56
76
 
@@ -79,15 +99,70 @@ export function loadDeviceCredentials() {
79
99
  * Ghi token (kho bí mật của hệ điều hành; hỏng → tệp thường kèm `seal_failed` có lý do để báo người dùng, không lặng lẽ). Trả lý do hỏng
80
100
  * (`null` khi cất được hoặc máy vốn không có kho).
81
101
  */
82
- export function saveDeviceCredentials(creds) {
102
+ export function saveDeviceCredentials(creds, { previousToken } = {}) {
83
103
  const { device_token: token, token_store: _s, token_enc: _e, seal_failed: _f, ...rest } = creds;
104
+ for (const f of DISK_OWNED_FIELDS) delete rest[f];
105
+ const disk = readRecord()?.data || {};
106
+ // Cùng mã máy → giữ trường của tệp; ghép máy khác thì token cũ không còn nghĩa.
107
+ const kept = {};
108
+ if (disk.device_id === creds.device_id && disk.previous_sealed) kept.previous_sealed = disk.previous_sealed;
109
+ if (disk.policy_sealed_at) kept.policy_sealed_at = disk.policy_sealed_at;
110
+ if (previousToken !== undefined) {
111
+ if (kept.previous_sealed) forgetPrevious(kept.previous_sealed);
112
+ delete kept.previous_sealed;
113
+ if (previousToken) kept.previous_sealed = sealPrevious(previousToken, creds.device_id);
114
+ }
84
115
  const sealed = sealToken(token, { account: creds.device_id });
85
116
  const { fallback_reason: reason, ...stored } = sealed;
86
- const raw = writeRecord({ ...rest, ...stored, ...(reason ? { seal_failed: { at: Date.now(), reason } } : {}) });
117
+ const raw = writeRecord({ ...rest, ...stored, ...kept, ...(reason ? { seal_failed: { at: Date.now(), reason } } : {}) });
87
118
  opened = { raw, token };
88
119
  return reason || null;
89
120
  }
90
121
 
122
+ /**
123
+ * Xoay vòng token (02/11/2026): token cũ giữ trong `previous_sealed` tới khi máy chủ xác nhận token mới. Trước đây ack ROTATED lỡ mất mà máy
124
+ * chủ không chốt được token mới → lần nối sau `DEVICE_UNAUTHORIZED` → xoá sạch ghép máy dù token cũ vẫn còn hiệu lực.
125
+ */
126
+ export function pendingPreviousToken() {
127
+ return openPrevious(readRecord()?.data?.previous_sealed);
128
+ }
129
+
130
+ /** Máy chủ đã nhận token mới (ack ROTATED đúng / chào thành công bằng token mới) → bỏ token cũ. Trả true khi có bỏ. */
131
+ export function confirmTokenRotation(currentToken) {
132
+ if (!readRecord()?.data?.previous_sealed) return false;
133
+ const creds = loadDeviceCredentials();
134
+ if (!creds || (currentToken && creds.device_token !== currentToken)) return false;
135
+ saveDeviceCredentials(creds, { previousToken: null });
136
+ return true;
137
+ }
138
+
139
+ /**
140
+ * Token `failedToken` bị máy chủ từ chối mà còn token cũ chưa bỏ (xoay vòng chưa chốt) → quay về token cũ, trả nó; không có → null (người
141
+ * gọi mới được xoá ghép máy).
142
+ */
143
+ export function revertTokenRotation(failedToken) {
144
+ const creds = loadDeviceCredentials();
145
+ if (!creds || (failedToken && creds.device_token !== failedToken)) return null;
146
+ const previous = pendingPreviousToken();
147
+ if (!previous || previous === creds.device_token) return null;
148
+ saveDeviceCredentials({ ...creds, device_token: previous }, { previousToken: null });
149
+ return readStoredTokenFresh() === previous ? previous : null;
150
+ }
151
+
152
+ /** Dấu bền "máy đã từng có luật tại máy có chữ ký" (xem DISK_OWNED_FIELDS) — chỉ ghi khi đã ghép máy (có tệp thông tin ghép). */
153
+ export function notePolicySealed() {
154
+ const rec = readRecord();
155
+ if (!rec?.data || rec.data.policy_sealed_at) return;
156
+ try {
157
+ const raw = writeRecord({ ...rec.data, policy_sealed_at: new Date().toISOString() });
158
+ if (opened.raw === rec.raw) opened = { raw, token: opened.token };
159
+ } catch { /* không ghi được: daemon vẫn nhớ trong bộ nhớ */ }
160
+ }
161
+
162
+ export function policySealedNoted() {
163
+ return !!readRecord()?.data?.policy_sealed_at;
164
+ }
165
+
91
166
  /** Đọc lại token từ tệp + kho bí mật thật (không qua bộ nhớ đệm) — kiểm sau khi ghi token mới. */
92
167
  export function readStoredTokenFresh() {
93
168
  const data = readRecord()?.data;
@@ -183,6 +258,8 @@ function savePairResult(res, { serverUrl, deviceId, roots, name }) {
183
258
  name: data.device?.name || name || os.hostname(),
184
259
  roots: roots.map((r) => path.resolve(r)),
185
260
  paired_at: new Date().toISOString(),
261
+ account: data.account || undefined,
262
+ lang: data.user_lang || data.lang || undefined,
186
263
  };
187
264
  saveDeviceCredentials(creds);
188
265
  return creds;
@@ -1,5 +1,7 @@
1
1
  import fs from 'fs';
2
- import { DAEMON_LOCK_FILE, REMOTE_CONFIG_DIR } from './constants.mjs';
2
+ import path from 'path';
3
+ import { DAEMON_LOCK_FILE } from './constants.mjs';
4
+ import { writeFileAtomic } from './atomicFile.mjs';
3
5
 
4
6
  /**
5
7
  * Một tiến trình `aivin remote start` cho mỗi thư mục cấu hình. Hai tiến trình cùng token máy (mở ở hai cửa sổ, hoặc tự khởi động
@@ -20,19 +22,41 @@ function isAlive(pid) {
20
22
  export const LOCK_STALE_MS = 90_000;
21
23
  export const LOCK_BEAT_MS = 30_000;
22
24
 
23
- /** PID đang giữ khoá (còn sống, khác tiến trình này, khoá còn được làm mới) — `null` nếu không ai giữ. */
24
- export function lockHolder(lockFile = DAEMON_LOCK_FILE) {
25
+ /** Tệp khoá đọc không ra JSON mà vừa được ghi trong chừng này → coi là đang có tiến trình giữ (đang ghi dở), không chiếm. */
26
+ export const LOCK_UNREADABLE_GRACE_MS = 10_000;
27
+
28
+ /** Đọc tệp khoá: `{ pid }` hợp lệ / `{ unreadable: true, recent }` (có tệp mà không ra JSON) / `null` (không có tệp). */
29
+ function readLock(lockFile) {
30
+ let raw;
31
+ try { raw = fs.readFileSync(lockFile, 'utf8'); } catch { return null; }
25
32
  try {
26
- const data = JSON.parse(fs.readFileSync(lockFile, 'utf8')) || {};
27
- const pid = Number(data.pid);
28
- const beatAt = Date.parse(data.beat_at || data.started_at || '');
29
- const fresh = !Number.isFinite(beatAt) || Date.now() - beatAt < LOCK_STALE_MS;
30
- return pid !== process.pid && isAlive(pid) && fresh ? pid : null;
33
+ const data = JSON.parse(raw) || {};
34
+ return { pid: Number(data.pid), beatAt: Date.parse(data.beat_at || data.started_at || '') };
31
35
  } catch {
32
- return null;
36
+ let recent = false;
37
+ try { recent = Date.now() - fs.statSync(lockFile).mtimeMs < LOCK_UNREADABLE_GRACE_MS; } catch { /* vừa bị xoá */ }
38
+ return { unreadable: true, recent };
33
39
  }
34
40
  }
35
41
 
42
+ /** PID đang giữ khoá (còn sống, khác tiến trình này, khoá còn được làm mới) — `null` nếu không ai giữ. */
43
+ export function lockHolder(lockFile = DAEMON_LOCK_FILE) {
44
+ const lock = readLock(lockFile);
45
+ if (!lock || lock.unreadable) return null;
46
+ const fresh = !Number.isFinite(lock.beatAt) || Date.now() - lock.beatAt < LOCK_STALE_MS;
47
+ return lock.pid !== process.pid && isAlive(lock.pid) && fresh ? lock.pid : null;
48
+ }
49
+
50
+ /**
51
+ * Lúc lấy khoá: như `lockHolder`, thêm tệp khoá đọc không ra JSON mà mtime còn mới → coi là ĐANG GIỮ (`'?'`), không chiếm (02/11/2026 —
52
+ * trước đây đọc trúng tệp đang ghi dở là coi như không ai giữ, hai daemon cùng chạy). Không trả PID giả cho người gọi `process.kill`.
53
+ */
54
+ function holderForAcquire(lockFile) {
55
+ const lock = readLock(lockFile);
56
+ if (lock?.unreadable) return lock.recent ? '?' : null;
57
+ return lockHolder(lockFile);
58
+ }
59
+
36
60
  /** Đã có tiến trình khác nhận việc — `code` để lệnh tự khởi động thoát 0 (không phải lỗi, trình giữ chạy không chạy lại). */
37
61
  export const DAEMON_RUNNING = 'DAEMON_RUNNING';
38
62
 
@@ -42,9 +66,25 @@ function daemonRunningError(pid) {
42
66
  return err;
43
67
  }
44
68
 
45
- function writeLock(lockFile, flag) {
69
+ /**
70
+ * Ghi khoá với nội dung trọn vẹn ngay từ đầu (02/11/2026). `exclusive`: tạo nguyên tử chỉ khi chưa có — ghi tệp tạm rồi `link` (link lỗi
71
+ * EEXIST nếu đã có tệp; người đọc không bao giờ thấy tệp rỗng như với `wx`); ổ không hỗ trợ link cứng → `wx` như cũ. Không exclusive: tạm +
72
+ * đổi tên đè.
73
+ */
74
+ function writeLock(lockFile, exclusive) {
46
75
  const now = new Date().toISOString();
47
- fs.writeFileSync(lockFile, JSON.stringify({ pid: process.pid, started_at: now, beat_at: now }), { flag });
76
+ const body = JSON.stringify({ pid: process.pid, started_at: now, beat_at: now });
77
+ if (!exclusive) return writeFileAtomic(lockFile, body, { mode: 0o644 });
78
+ const tmp = `${lockFile}.${process.pid}.${Date.now().toString(36)}.tmp`;
79
+ fs.writeFileSync(tmp, body);
80
+ try {
81
+ fs.linkSync(tmp, lockFile);
82
+ } catch (e) {
83
+ if (e?.code === 'EEXIST') throw e;
84
+ fs.writeFileSync(lockFile, body, { flag: 'wx' });
85
+ } finally {
86
+ try { fs.rmSync(tmp, { force: true }); } catch { /* bỏ */ }
87
+ }
48
88
  }
49
89
 
50
90
  /**
@@ -52,19 +92,19 @@ function writeLock(lockFile, flag) {
52
92
  * hết hiệu lực / bị thay rồi tự dừng). Trả hàm nhả khoá (chỉ nhả khi khoá còn là của tiến trình này).
53
93
  */
54
94
  export function acquireDaemonLock({ takeOver = false, lockFile = DAEMON_LOCK_FILE } = {}) {
55
- const holder = lockHolder(lockFile);
95
+ const holder = holderForAcquire(lockFile);
56
96
  if (holder && !takeOver) {
57
97
  throw daemonRunningError(holder);
58
98
  }
59
- fs.mkdirSync(REMOTE_CONFIG_DIR, { recursive: true });
99
+ fs.mkdirSync(path.dirname(lockFile), { recursive: true });
60
100
  // Tạo nguyên tử: hai tiến trình khởi động cùng lúc (systemd + .desktop lúc đăng nhập) chỉ một bên tạo được tệp.
61
101
  try {
62
- writeLock(lockFile, takeOver ? 'w' : 'wx');
102
+ writeLock(lockFile, !takeOver);
63
103
  } catch (e) {
64
104
  if (e?.code !== 'EEXIST') throw e;
65
- const again = lockHolder(lockFile);
105
+ const again = holderForAcquire(lockFile);
66
106
  if (again) throw daemonRunningError(again);
67
- writeLock(lockFile, 'w'); // khoá cũ của tiến trình đã chết
107
+ writeLock(lockFile, false); // khoá cũ của tiến trình đã chết
68
108
  }
69
109
  const mine = () => {
70
110
  try { return Number(JSON.parse(fs.readFileSync(lockFile, 'utf8'))?.pid) === process.pid; } catch { return false; }
@@ -73,7 +113,7 @@ export function acquireDaemonLock({ takeOver = false, lockFile = DAEMON_LOCK_FIL
73
113
  if (!mine()) return;
74
114
  try {
75
115
  const data = JSON.parse(fs.readFileSync(lockFile, 'utf8'));
76
- fs.writeFileSync(lockFile, JSON.stringify({ ...data, beat_at: new Date().toISOString() }));
116
+ writeFileAtomic(lockFile, JSON.stringify({ ...data, beat_at: new Date().toISOString() }), { mode: 0o644 });
77
117
  } catch { /* tệp khoá bị xoá — lần sau tạo lại */ }
78
118
  }, LOCK_BEAT_MS);
79
119
  beat.unref?.();
@@ -256,7 +256,11 @@ export function createCdpMux({ wsUrl, downloadsDir, consentTimeoutMs = CONSENT_T
256
256
  sessions.set(params.sessionId, { client, targetId, type: params.targetInfo?.type, parent, aivin });
257
257
  if (aivin) markTabAivin(params.targetInfo?.type === 'tab' ? params.sessionId : parent);
258
258
  }
259
- if (msg.method === 'Target.detachedFromTarget' && params.sessionId) sessions.delete(params.sessionId);
259
+ if (msg.method === 'Target.detachedFromTarget' && params.sessionId) {
260
+ sessions.delete(params.sessionId);
261
+ for (const [sid, s] of [...sessions]) if (s.parent === params.sessionId) sessions.delete(sid);
262
+ for (const k of [...client.requests.keys()]) if (k.startsWith(`${params.sessionId}:`)) client.requests.delete(k);
263
+ }
260
264
  if (msg.method === 'Target.targetDestroyed' && params.targetId) aivinTargets.delete(params.targetId);
261
265
  };
262
266
 
@@ -332,7 +336,9 @@ export function createCdpMux({ wsUrl, downloadsDir, consentTimeoutMs = CONSENT_T
332
336
  if (msg.id !== undefined) toClient(JSON.stringify({ id: msg.id, ...(msg.sessionId ? { sessionId: msg.sessionId } : {}), error: { code: -32000, message: reason } }));
333
337
  return;
334
338
  }
335
- if (msg.id !== undefined) client.requests.set(`${sid}:${msg.id}`, { method: msg.method, targetId: params.targetId });
339
+ if (msg.id !== undefined && (msg.method === 'Target.createTarget' || msg.method === 'Target.attachToTarget')) {
340
+ client.requests.set(`${sid}:${msg.id}`, { method: msg.method, targetId: params.targetId });
341
+ }
336
342
  // Thư mục tải đặt qua một trang áp cho cả hồ sơ: nhớ để trả về mặc định khi đường hầm cuối cùng đóng (tệp người dùng tự tải về đúng chỗ cũ).
337
343
  if (msg.method === 'Page.setDownloadBehavior') client.setDownloads = true;
338
344
  // Tab mới mở ở nền: không giật tiêu điểm khỏi cửa sổ người dùng đang làm việc.
@@ -0,0 +1,98 @@
1
+ /**
2
+ * Cổng thao tác chuột / phím từ xa (Desktop Scenecast) — lớp chặn cuối trên máy, không tin BE / trình duyệt: chỉ nhận action đã biết,
3
+ * chỉ chép trường đã biết (trường lạ như `op` không bao giờ xuống tiến trình điều khiển), bỏ khi chủ máy đã tạm dừng, khi AI đang thao tác
4
+ * giao diện, hoặc gửi quá dồn. Thao tác qua kênh WebRTC cũng đi qua đây.
5
+ */
6
+
7
+ export const CAST_INPUT_ACTIONS = Object.freeze(['move', 'click', 'dblclick', 'rightclick', 'mousedown', 'mouseup', 'scroll', 'type', 'key', 'hotkey']);
8
+
9
+ export const CastInputRejection = Object.freeze({
10
+ INVALID: 'invalid',
11
+ PAUSED: 'paused',
12
+ AI_ACTIVE: 'ai_active',
13
+ RATE_LIMITED: 'rate_limited',
14
+ });
15
+
16
+ const ACTIONS = new Set(CAST_INPUT_ACTIONS);
17
+ const MAX_COORD = 100_000;
18
+ const MAX_SCROLL = 10_000;
19
+ /** Toạ độ theo tỷ lệ (rx, ry): 0 = mép trái / trên, 65535 = mép phải / dưới. */
20
+ const RATIO_SCALE = 65_535;
21
+ const MAX_KEY_CHARS = 24;
22
+
23
+ function finiteIn(value, limit) {
24
+ const n = Number(value);
25
+ return Number.isFinite(n) && Math.abs(n) <= limit ? n : undefined;
26
+ }
27
+
28
+ function shortStrings(value, maxCount) {
29
+ if (!Array.isArray(value)) return undefined;
30
+ const out = value.filter((k) => typeof k === 'string' && k && k.length <= MAX_KEY_CHARS).slice(0, maxCount);
31
+ return out.length ? out : undefined;
32
+ }
33
+
34
+ /** Lọc một thao tác thành lệnh hợp lệ (cùng luật với BE `sanitizeCastInput`); không hợp lệ → null. */
35
+ export function sanitizeCastInput(raw, maxTypeChars = 2000) {
36
+ if (!raw || typeof raw !== 'object') return null;
37
+ const action = String(raw.action || '');
38
+ if (!ACTIONS.has(action)) return null;
39
+ const cmd = { action };
40
+ const x = finiteIn(raw.x, MAX_COORD);
41
+ const y = finiteIn(raw.y, MAX_COORD);
42
+ if (x !== undefined && y !== undefined) { cmd.x = Math.round(x); cmd.y = Math.round(y); }
43
+ const rx = finiteIn(raw.rx, RATIO_SCALE);
44
+ const ry = finiteIn(raw.ry, RATIO_SCALE);
45
+ if (rx >= 0 && ry >= 0) { cmd.rx = Math.round(rx); cmd.ry = Math.round(ry); }
46
+ const button = Number(raw.button);
47
+ if (button === 0 || button === 1 || button === 2) cmd.button = button;
48
+ const deltaX = finiteIn(raw.deltaX, MAX_SCROLL);
49
+ const deltaY = finiteIn(raw.deltaY, MAX_SCROLL);
50
+ if (deltaX !== undefined) cmd.deltaX = Math.round(deltaX);
51
+ if (deltaY !== undefined) cmd.deltaY = Math.round(deltaY);
52
+ if (typeof raw.text === 'string' && raw.text) cmd.text = raw.text.slice(0, maxTypeChars);
53
+ if (typeof raw.key === 'string' && raw.key && raw.key.length <= MAX_KEY_CHARS) cmd.key = raw.key;
54
+ const keys = shortStrings(raw.keys, 6);
55
+ if (keys) cmd.keys = keys;
56
+ const modifiers = shortStrings(raw.modifiers, 4);
57
+ if (modifiers) cmd.modifiers = modifiers;
58
+ if (action === 'type' && !cmd.text) return null;
59
+ if (action === 'key' && !cmd.key) return null;
60
+ if (action === 'hotkey' && !cmd.keys) return null;
61
+ return cmd;
62
+ }
63
+
64
+ /**
65
+ * `isPaused()`: công tắc ngắt của chủ máy. `isAiBusy()`: AI đang chạy công cụ GUI ghi. `accept(raw)` → `{ ok, cmd }` hoặc `{ ok: false, reason }`.
66
+ * `waitHumanIdle()`: công cụ GUI của AI chờ người thôi thao tác (tối đa `maxWaitMs`) trước khi bấm — hai bên không giành chuột cùng lúc.
67
+ */
68
+ export function createCastInputGate({ isPaused = () => false, isAiBusy = () => false, maxPerSec = 120, now = Date.now, sleep } = {}) {
69
+ let lastHumanAt = null;
70
+ let accepted = 0;
71
+ let window = { start: 0, count: 0 };
72
+ const wait = sleep || ((ms) => new Promise((r) => setTimeout(r, ms)));
73
+
74
+ function accept(raw) {
75
+ if (isPaused()) return { ok: false, reason: CastInputRejection.PAUSED };
76
+ if (isAiBusy()) return { ok: false, reason: CastInputRejection.AI_ACTIVE };
77
+ const t = now();
78
+ if (t - window.start >= 1000) window = { start: t, count: 0 };
79
+ if (++window.count > maxPerSec) return { ok: false, reason: CastInputRejection.RATE_LIMITED };
80
+ const cmd = sanitizeCastInput(raw);
81
+ if (!cmd) return { ok: false, reason: CastInputRejection.INVALID };
82
+ lastHumanAt = t;
83
+ accepted++;
84
+ return { ok: true, cmd };
85
+ }
86
+
87
+ async function waitHumanIdle({ idleMs = 1500, maxWaitMs = 3000 } = {}) {
88
+ const deadline = now() + maxWaitMs;
89
+ while (lastHumanAt !== null && now() - lastHumanAt < idleMs && now() < deadline) {
90
+ await wait(Math.min(250, Math.max(10, idleMs - (now() - lastHumanAt))));
91
+ }
92
+ }
93
+
94
+ /** Số thao tác đã nhận từ lần gọi trước (nhật ký phiên trên máy) — đọc xong đặt lại 0. */
95
+ function takeAcceptedCount() { const n = accepted; accepted = 0; return n; }
96
+
97
+ return { accept, waitHumanIdle, takeAcceptedCount, lastHumanInputAt: () => lastHumanAt };
98
+ }