@aivin-labs/cli 1.0.11 → 1.0.13

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 (41) hide show
  1. package/README.md +16 -0
  2. package/bin/cli.mjs +67 -0
  3. package/bin/lib/remote/browserTunnel.mjs +47 -8
  4. package/bin/lib/remote/callLedger.mjs +73 -14
  5. package/bin/lib/remote/client.mjs +89 -8
  6. package/bin/lib/remote/cloudFiles.mjs +53 -0
  7. package/bin/lib/remote/constants.mjs +17 -0
  8. package/bin/lib/remote/dailyBrowser.mjs +8 -2
  9. package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
  10. package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
  11. package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
  12. package/bin/lib/remote/desktop/index.mjs +44 -7
  13. package/bin/lib/remote/desktop/linux.mjs +1 -1
  14. package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -427
  15. package/bin/lib/remote/desktop/mac.mjs +2 -2
  16. package/bin/lib/remote/desktop/macTraySource.mjs +295 -292
  17. package/bin/lib/remote/desktop/traySource.mjs +541 -527
  18. package/bin/lib/remote/deviceProfile.mjs +1 -0
  19. package/bin/lib/remote/docText.mjs +85 -0
  20. package/bin/lib/remote/fileIndexer.mjs +757 -399
  21. package/bin/lib/remote/folderRules.mjs +140 -0
  22. package/bin/lib/remote/gui/index.mjs +126 -17
  23. package/bin/lib/remote/gui/windowsHost.mjs +9 -2
  24. package/bin/lib/remote/gui/windowsHostSource.mjs +194 -51
  25. package/bin/lib/remote/idempotency.mjs +49 -20
  26. package/bin/lib/remote/localPolicy.mjs +8 -2
  27. package/bin/lib/remote/mascot/askHostSource.mjs +18 -0
  28. package/bin/lib/remote/mascot/bot.mjs +29 -4
  29. package/bin/lib/remote/mascot/hostSource.mjs +4 -4
  30. package/bin/lib/remote/mascot/rigSource.mjs +12 -7
  31. package/bin/lib/remote/osSearch.mjs +107 -0
  32. package/bin/lib/remote/sqliteDb.mjs +51 -0
  33. package/bin/lib/remote/toolHandlers.mjs +788 -741
  34. package/bin/lib/remoteControl.mjs +26 -26
  35. package/docs/AIVIN_MASCOT.md +14 -0
  36. package/docs/CLI.md +1504 -1484
  37. package/docs/media/aivin-mascot-live.gif +0 -0
  38. package/docs/media/aivin-mascot-live.png +0 -0
  39. package/docs/media/aivin-remote-architecture.svg +102 -0
  40. package/package.json +71 -71
  41. package/docs/media/aivin-mascot-states.mp4 +0 -0
package/README.md CHANGED
@@ -154,11 +154,17 @@ a description? `aivin plugin convert` turns an existing directory into a plugin
154
154
 
155
155
  ## Aivin mascot on Windows
156
156
 
157
+ <p align="center">
158
+ <img src="docs/media/aivin-mascot-live.gif" alt="The current live Aivin mascot showing chat, file drag and attached-file states" width="480" />
159
+ </p>
160
+
157
161
  When Aivin Remote is running on Windows, a small animated Aivin mascot can float above your apps.
158
162
  It shows whether Aivin is idle, working, thinking, waiting for you, done, paused, offline, or has hit
159
163
  an error. Hover or click it to type a question, use its microphone for a live voice conversation,
160
164
  right-click for the activity panel, or drop local files onto it to attach them to your next message.
161
165
  The mascot stays out of Aivin screenshots and moves aside while the agent controls another window.
166
+ The animation above is captured from the current WPF interface: it shows a chat, the drag target and
167
+ the tray holding files already attached to the next message.
162
168
 
163
169
  ```bash
164
170
  aivin remote start # start the listener and mascot
@@ -172,6 +178,16 @@ Turning it off from the activity panel plays a short fade-and-slide exit animati
172
178
  listener continues in the background. See the dedicated [Aivin mascot guide](docs/AIVIN_MASCOT.md)
173
179
  for interactions, voice and keyboard shortcuts, states, privacy behavior, and troubleshooting.
174
180
 
181
+ ### How Remote connects Aivin to computers
182
+
183
+ ![Aivin Platform routes authenticated work to listeners on selected computers; each listener applies local policy and returns progress and results](docs/media/aivin-remote-architecture.svg)
184
+
185
+ Each paired computer opens its own authenticated outbound connection to Aivin Platform. The
186
+ platform routes a chat or mission to the selected computer; its listener applies local policy,
187
+ requests approval for protected actions, runs the allowed local tools, and sends progress and
188
+ results back. The mascot talks to the listener on the same computer—it is not a separate remote
189
+ control channel.
190
+
175
191
  ## What you get from a scaffold
176
192
 
177
193
  Both `aivin init` and `aivin create` produce the same project shape (`init` additionally writes
package/bin/cli.mjs CHANGED
@@ -94,6 +94,7 @@ import {
94
94
  resetDeviceId,
95
95
  loadDeviceCredentials,
96
96
  pairDevice,
97
+ pairWithCodeOnly,
97
98
  listDevices,
98
99
  unpairDevice,
99
100
  isRemotePaused,
@@ -107,6 +108,11 @@ import {
107
108
  deleteMemoryItems,
108
109
  clearDeviceMemory,
109
110
  createFileIndex,
111
+ loadIndexFolders,
112
+ saveIndexFolders,
113
+ loadIndexExcludes,
114
+ saveIndexExcludes,
115
+ resolveInRoots,
110
116
  indexRootsFor,
111
117
  runRemoteMission,
112
118
  MemoryKind,
@@ -1174,8 +1180,18 @@ remoteCommand
1174
1180
  .description('Pair (or re-pair) this computer with your account without starting the listener')
1175
1181
  .option('--dir <path>', 'Folder the agent may work in (default: current folder)')
1176
1182
  .option('--name <name>', 'Name shown for this computer (default: hostname)')
1183
+ .option('--code <code>', 'Pair with a one-time code from Aivin (chat box → Browser ▾ → Add this computer) - no `aivin login` needed')
1184
+ .option('--server <url>', 'Aivin server the code belongs to')
1185
+ .option('--full-access', 'Let the agent work anywhere on this computer (with --code)')
1177
1186
  .action(async (options) => {
1178
1187
  try {
1188
+ if (options.code) {
1189
+ // Bộ cài (đã có khay): chỉ ghép — khay mở listener ngay khi thấy máy đã ghép.
1190
+ const { creds, stopped } = await pairWithCodeOnly(options);
1191
+ console.log(chalk.green(`✅ Đã kết nối máy "${creds.name}" với tài khoản Aivin của bạn — quay lại Aivin để chọn máy này.`));
1192
+ if (stopped) console.log(chalk.gray(' Đã dừng phiên nhận việc cũ — Aivin mở lại bằng kết nối mới.'));
1193
+ return;
1194
+ }
1179
1195
  const roots = [path.resolve(options.dir || process.cwd())];
1180
1196
  const creds = await pairDevice({ serverUrl: missionServerUrl(), apiKey: process.env.API_KEY, roots, name: options.name, profile: buildDeviceProfile(roots) });
1181
1197
  console.log(chalk.green(`✅ Đã ghép máy "${creds.name}" (${creds.device_id})`));
@@ -1464,6 +1480,57 @@ remoteCommand
1464
1480
  }
1465
1481
  });
1466
1482
 
1483
+ remoteCommand
1484
+ .command('index [action] [folder]')
1485
+ .description('Working folders indexed fully (code too) so agents find everything in them instantly: list (default) | add <folder> | remove <folder>. Agents add one themselves when you tell them in chat where you work')
1486
+ .action((action = 'list', folder) => {
1487
+ try {
1488
+ const creds = loadDeviceCredentials();
1489
+ if (action === 'list') {
1490
+ const folders = loadIndexFolders();
1491
+ if (!folders.length) return console.log(chalk.gray('Chưa có thư mục làm việc nào. Thêm: aivin remote index add <thư mục>'));
1492
+ return folders.forEach((f) => console.log(`📁 ${f}`));
1493
+ }
1494
+ if (!['add', 'remove'].includes(action) || !folder) throw new Error('Dùng: aivin remote index [list | add <thư mục> | remove <thư mục>]');
1495
+ // Chỉ trong thư mục máy cho phép — chỉ mục ngoài đó trả về tệp mà agent không mở được.
1496
+ const abs = creds?.roots?.length ? resolveInRoots(creds.roots, folder) : path.resolve(folder);
1497
+ if (action === 'add') {
1498
+ if (!fs.statSync(abs, { throwIfNoEntry: false })?.isDirectory()) throw new Error(`Không phải thư mục: ${abs}`);
1499
+ saveIndexFolders([...loadIndexFolders(), abs]);
1500
+ console.log(chalk.green(`✅ Đã thêm thư mục làm việc ${abs} — listener đang chạy sẽ lập chỉ mục trong vài giây.`));
1501
+ } else {
1502
+ saveIndexFolders(loadIndexFolders().filter((f) => f !== abs));
1503
+ console.log(chalk.green(`✅ Đã bỏ thư mục làm việc ${abs}`));
1504
+ }
1505
+ } catch (error) {
1506
+ remoteFail(error);
1507
+ }
1508
+ });
1509
+
1510
+ remoteCommand
1511
+ .command('index-exclude [action] [pattern]')
1512
+ .description('Custom exclude rules for file indexing: list (default) | add <name/pattern> | remove <name/pattern>')
1513
+ .action((action = 'list', pattern) => {
1514
+ try {
1515
+ if (action === 'list') {
1516
+ const excludes = loadIndexExcludes();
1517
+ if (!excludes.length) return console.log(chalk.gray('Chưa có mẫu loại trừ tuỳ biến nào. Thêm: aivin remote index-exclude add <tên_hoặc_mẫu>'));
1518
+ return excludes.forEach((e) => console.log(`🚫 ${e}`));
1519
+ }
1520
+ if (!['add', 'remove'].includes(action) || !pattern) throw new Error('Dùng: aivin remote index-exclude [list | add <mẫu> | remove <mẫu>]');
1521
+ const item = String(pattern).trim();
1522
+ if (action === 'add') {
1523
+ saveIndexExcludes([...loadIndexExcludes(), item]);
1524
+ console.log(chalk.green(`✅ Đã thêm mẫu loại trừ "${item}" — listener đang chạy sẽ áp dụng trong vài giây.`));
1525
+ } else {
1526
+ saveIndexExcludes(loadIndexExcludes().filter((e) => e.toLowerCase() !== item.toLowerCase()));
1527
+ console.log(chalk.green(`✅ Đã xoá mẫu loại trừ "${item}"`));
1528
+ }
1529
+ } catch (error) {
1530
+ remoteFail(error);
1531
+ }
1532
+ });
1533
+
1467
1534
  remoteCommand
1468
1535
  .command('reset-id')
1469
1536
  .description('Give this computer a new device id (cloned machines) - you must pair again')
@@ -95,7 +95,23 @@ export async function ensureAivinBrowser(preferredId, { ports = DEBUG_PORTS, lau
95
95
  const tokenOf = (t) => (typeof t === 'function' ? t() : t);
96
96
 
97
97
  /** Khung trình duyệt gửi lên có thể đáng xem (gắn / gỡ phiên, tab mới, trả lời có targetId) — so chuỗi trước, chỉ parse khi cần. */
98
- const UPSTREAM_INTEREST_RE = /attachedToTarget|detachedFromTarget|targetCreated|targetInfoChanged|"targetId"/;
98
+ const UPSTREAM_INTEREST_RE = /attachedToTarget|detachedFromTarget|targetCreated|targetInfoChanged|targetDestroyed|"targetId"/;
99
+ const KEEPALIVE_MS = 30_000;
100
+ const MAX_EARLY_QUEUE_BYTES = 4 * 1024 * 1024;
101
+
102
+ function watchSocketAlive(ws, onDead, intervalMs = KEEPALIVE_MS) {
103
+ if (!intervalMs || typeof ws.ping !== 'function') return () => {};
104
+ let awaitingPong = false;
105
+ ws.on('pong', () => { awaitingPong = false; });
106
+ const timer = setInterval(() => {
107
+ if (ws.readyState !== WSClient.OPEN) return;
108
+ if (awaitingPong) { try { ws.terminate?.(); } catch { /* đã đóng */ } onDead(); return; }
109
+ awaitingPong = true;
110
+ try { ws.ping(); } catch { /* đang đóng */ }
111
+ }, intervalMs);
112
+ timer.unref?.();
113
+ return () => clearInterval(timer);
114
+ }
99
115
 
100
116
  /**
101
117
  * Hai WebSocket nối nhau (BE ↔ trình duyệt), chờ cả hai mở. Một đầu đóng → đóng đầu kia. Lệnh BE gửi xuống đi qua bộ lọc `cdpPolicy.mjs`, cộng:
@@ -109,7 +125,9 @@ export function pipeTunnel({ relayUrl, authorization, chromeWsUrl, signal, downl
109
125
  const extensionSessions = new Set();
110
126
  const aivinTargets = new Set();
111
127
  const pendingCreates = new Set(); // `${sessionId}:${id}` của lệnh Target.createTarget chưa có trả lời
112
- const close = () => {
128
+ let stopKeepalive = () => {};
129
+ const close = () => {
130
+ stopKeepalive();
113
131
  try { toBackend.close(); } catch { /* đã đóng */ }
114
132
  try { toChrome.close(); } catch { /* đã đóng */ }
115
133
  };
@@ -175,10 +193,14 @@ export function pipeTunnel({ relayUrl, authorization, chromeWsUrl, signal, downl
175
193
  noteTarget(params.targetInfo);
176
194
  // Tab bật ra từ tab AI (window.open, target=_blank) cũng là của AI.
177
195
  const info = params.targetInfo;
178
- if (msg.method === 'Target.targetCreated' && info?.type === 'page' && aivinTargets.has(info.openerId)) markAivin(info.targetId);
196
+ if (msg.method === 'Target.targetCreated' && info?.type === 'page' && aivinTargets.has(info.openerId)) markAivin(info.targetId);
197
+ } else if (msg.method === 'Target.targetDestroyed' && params.targetId) {
198
+ extensionTargets.delete(params.targetId);
199
+ aivinTargets.delete(params.targetId);
179
200
  }
180
201
  });
181
- relay(toChrome, toBackend);
202
+ relay(toChrome, toBackend);
203
+ stopKeepalive = watchSocketAlive(toBackend, close);
182
204
  const opened = (ws) => new Promise((resolve, reject) => {
183
205
  ws.once('open', resolve);
184
206
  ws.once('error', reject);
@@ -197,14 +219,24 @@ function pipeTunnelToMux({ relayUrl, authorization, mux, signal }) {
197
219
  const toBackend = new WSClient(relayUrl, { headers: { Authorization: authorization }, agent: proxyAgentFor(relayUrl) });
198
220
  let client = null;
199
221
  let closed = false;
200
- const early = [];
201
- const close = () => {
222
+ const early = [];
223
+ let earlyBytes = 0;
224
+ let stopKeepalive = () => {};
225
+ const close = () => {
226
+ stopKeepalive();
202
227
  if (closed) return;
203
228
  closed = true;
204
229
  try { toBackend.close(); } catch { /* đã đóng */ }
205
230
  client?.close();
206
231
  };
207
- toBackend.on('message', (data) => { if (client) client.send(String(data)); else early.push(String(data)); });
232
+ toBackend.on('message', (data) => {
233
+ const str = String(data);
234
+ if (client) { client.send(str); return; }
235
+ earlyBytes += Buffer.byteLength(str);
236
+ if (earlyBytes > MAX_EARLY_QUEUE_BYTES) { try { toBackend.close(1009, 'too much data before pairing'); } catch { /* đã đóng */ } close(); return; }
237
+ early.push(str);
238
+ });
239
+ stopKeepalive = watchSocketAlive(toBackend, close);
208
240
  toBackend.on('close', close);
209
241
  toBackend.on('error', close);
210
242
  const onAbort = () => close();
@@ -364,7 +396,14 @@ export function createBrowserTunnels({
364
396
  async function readDownload(args, ctx) {
365
397
  const name = String(args?.name || '');
366
398
  if (!name || name !== path.basename(name) || name.includes('..')) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Invalid file name');
367
- const hit = await findDownload(downloadsDir, name, Number(args?.since) || 0, ctx?.signal);
399
+ const reqOffset = Math.max(0, Number(args?.offset) || 0);
400
+ const since = Number(args?.since) || 0;
401
+ let hit = null;
402
+ if (reqOffset > 0 && !name.endsWith(PARTIAL_SUFFIX)) {
403
+ const st = await fs.promises.stat(path.join(downloadsDir, name)).catch(() => null);
404
+ if (st?.isFile() && st.mtimeMs >= since - 2000) hit = { name, size: st.size };
405
+ }
406
+ if (!hit) hit = await findDownload(downloadsDir, name, since, ctx?.signal);
368
407
  if (!hit) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Downloaded file not found: ${name}`);
369
408
  const offset = Math.max(0, Number(args?.offset) || 0);
370
409
  const length = Math.min(Math.max(0, Number(args?.length) || MAX_READ_BYTES), MAX_READ_BYTES, Math.max(0, hit.size - offset));
@@ -22,21 +22,34 @@ function payloadBytes(payload) {
22
22
  * - Kết quả chưa gửi được (mất mạng, chưa có ack) ghi xuống `REMOTE_OUTBOX_FILE` — daemon khởi động lại vẫn gửi.
23
23
  * - `heldIds()`: lời gọi máy đang giữ, gửi lên khi chào để BE đối chiếu (huỷ việc không còn ai chờ, khỏi gửi lại việc máy đang làm).
24
24
  */
25
- export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.now() } = {}) {
25
+ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.now(), debounceMs = 40 } = {}) {
26
26
  const calls = new Map();
27
+ let persistTimer = null;
28
+ let writeChain = Promise.resolve();
27
29
 
28
- function persist() {
30
+ function buildUnsentRows() {
29
31
  const unsent = [...calls.entries()].filter(([, e]) => e.state === CallState.DONE && !e.sent);
32
+ return unsent.map(([id, e]) => {
33
+ const payload = payloadBytes(e.payload) <= PERSIST_RESULT_BYTES ? e.payload
34
+ : { call_id: id, ok: false, error: 'Result was too large to keep while offline — run the step again', error_code: 'OUTPUT_TOO_LARGE', duration_ms: e.payload.duration_ms };
35
+ return { id, at: e.at, payload };
36
+ });
37
+ }
38
+
39
+ function clearPersistTimer() {
40
+ if (!persistTimer) return;
41
+ clearTimeout(persistTimer);
42
+ persistTimer = null;
43
+ }
44
+
45
+ function persistSync() {
46
+ clearPersistTimer();
47
+ const rows = buildUnsentRows();
30
48
  try {
31
- if (!unsent.length) {
49
+ if (!rows.length) {
32
50
  fs.rmSync(file, { force: true });
33
51
  return;
34
52
  }
35
- const rows = unsent.map(([id, e]) => {
36
- const payload = payloadBytes(e.payload) <= PERSIST_RESULT_BYTES ? e.payload
37
- : { call_id: id, ok: false, error: 'Result was too large to keep while offline — run the step again', error_code: 'OUTPUT_TOO_LARGE', duration_ms: e.payload.duration_ms };
38
- return { id, at: e.at, payload };
39
- });
40
53
  fs.mkdirSync(path.dirname(file), { recursive: true });
41
54
  const tmp = `${file}.tmp`;
42
55
  fs.writeFileSync(tmp, JSON.stringify(rows), { mode: 0o600 });
@@ -44,6 +57,44 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
44
57
  } catch { /* không ghi được: vẫn giữ trong bộ nhớ */ }
45
58
  }
46
59
 
60
+ function enqueueAsyncPersist() {
61
+ clearPersistTimer();
62
+ const rows = buildUnsentRows();
63
+ if (!rows.length) {
64
+ try { fs.rmSync(file, { force: true }); } catch { /* bỏ qua */ }
65
+ return writeChain;
66
+ }
67
+ const serialized = JSON.stringify(rows);
68
+ writeChain = writeChain.then(async () => {
69
+ try {
70
+ await fs.promises.mkdir(path.dirname(file), { recursive: true });
71
+ const tmp = `${file}.tmp`;
72
+ await fs.promises.writeFile(tmp, serialized, { mode: 0o600 });
73
+ await fs.promises.rename(tmp, file);
74
+ } catch { /* không ghi được: vẫn giữ trong bộ nhớ */ }
75
+ });
76
+ return writeChain;
77
+ }
78
+
79
+ function schedulePersist() {
80
+ const hasUnsent = [...calls.values()].some((e) => e.state === CallState.DONE && !e.sent);
81
+ if (!hasUnsent) {
82
+ clearPersistTimer();
83
+ try { fs.rmSync(file, { force: true }); } catch { /* bỏ qua */ }
84
+ return;
85
+ }
86
+ if (debounceMs <= 0) {
87
+ persistSync();
88
+ return;
89
+ }
90
+ if (persistTimer) return;
91
+ persistTimer = setTimeout(() => {
92
+ persistTimer = null;
93
+ void enqueueAsyncPersist();
94
+ }, debounceMs);
95
+ persistTimer.unref?.();
96
+ }
97
+
47
98
  function load() {
48
99
  let rows;
49
100
  try { rows = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return; }
@@ -70,7 +121,7 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
70
121
  calls.delete(id);
71
122
  changed = true;
72
123
  }
73
- if (changed) persist();
124
+ if (changed) schedulePersist();
74
125
  }
75
126
 
76
127
  load();
@@ -86,7 +137,10 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
86
137
  /** Lời gọi xong — kết quả chờ gửi. `persistNow`: ghi xuống đĩa ngay (đang mất kết nối). */
87
138
  finish(callId, payload, { persistNow = false } = {}) {
88
139
  calls.set(callId, { state: CallState.DONE, at: now(), payload, sent: false });
89
- if (persistNow) persist();
140
+ if (persistNow) {
141
+ for (const e of calls.values()) if (e.state === CallState.DONE && !e.sent) e.onDisk = true;
142
+ persistSync();
143
+ }
90
144
  },
91
145
  markSent(callId) {
92
146
  const e = calls.get(callId);
@@ -94,7 +148,7 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
94
148
  const wasOnDisk = e.onDisk;
95
149
  e.sent = true;
96
150
  e.payload = { call_id: callId, ...pick(e.payload) };
97
- if (wasOnDisk) persist();
151
+ if (wasOnDisk) schedulePersist();
98
152
  },
99
153
  /** Lời gọi đã xong bị BE gửi lại: đánh dấu chưa gửi, trả kết quả để gửi lần nữa. */
100
154
  reopen(callId) {
@@ -104,9 +158,14 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
104
158
  return e.payload;
105
159
  },
106
160
  /** Ghi các kết quả chưa gửi xuống đĩa (gửi chưa được xác nhận / daemon sắp dừng). */
107
- persist() {
161
+ persist({ sync = false } = {}) {
108
162
  for (const e of calls.values()) if (e.state === CallState.DONE && !e.sent) e.onDisk = true;
109
- persist();
163
+ if (sync) persistSync();
164
+ else schedulePersist();
165
+ },
166
+ /** Đẩy ngay các thay đổi đang chờ ghi bất đồng bộ xuống đĩa. */
167
+ flush() {
168
+ return persistTimer ? enqueueAsyncPersist() : writeChain;
110
169
  },
111
170
  /** BE báo không còn ai chờ → bỏ kết quả chưa gửi của các lời gọi này. */
112
171
  drop(callIds) {
@@ -118,7 +177,7 @@ export function createCallLedger({ file = REMOTE_OUTBOX_FILE, now = () => Date.n
118
177
  changed = true;
119
178
  }
120
179
  }
121
- if (changed) persist();
180
+ if (changed) schedulePersist();
122
181
  },
123
182
  unsent: () => [...calls.values()].filter((e) => e.state === CallState.DONE && !e.sent).map((e) => e.payload),
124
183
  heldIds: () => [...calls.entries()].filter(([, e]) => e.state === CallState.RUNNING || (e.state === CallState.DONE && !e.sent)).map(([id]) => id),
@@ -16,7 +16,7 @@ import { ensureMemoryLoaded, memoryStats, stopWatchingMemory, watchMemoryDir } f
16
16
  import { buildCatalog, buildDeviceProfile } from './deviceProfile.mjs';
17
17
  import { createFileIndex, indexRootsFor } from './fileIndexer.mjs';
18
18
  import { createScheduler } from './scheduler.mjs';
19
- import { acquireDaemonLock } from './daemonLock.mjs';
19
+ import { acquireDaemonLock, lockHolder } from './daemonLock.mjs';
20
20
  import { randomUUID } from 'crypto';
21
21
  import { DeviceToolError, fullAccessRoots, isRemotePaused, setRemotePaused } from './sandbox.mjs';
22
22
  import { createMascot, HostEvent as MascotHostEvent } from './mascot/index.mjs';
@@ -39,6 +39,8 @@ import { createScheduleManager } from './schedule.mjs';
39
39
  import { remoteDebuggingPage } from './dailyBrowser.mjs';
40
40
  import { HOME_BASE, SHARED_DIR, createMultiUserHost, isMultiUserMode } from './multiUser.mjs';
41
41
  import { createAutoUpdater } from './autoUpdate.mjs';
42
+ import { createDesktopCastManager } from './desktop/desktopCast.mjs';
43
+ import { createDesktopWebRtc } from './desktop/desktopWebRtc.mjs';
42
44
  import {
43
45
  BootAction, MAX_BOOTS_BEFORE_ROLLBACK, RESTART_EXIT_CODE, UPDATE_CONFIRM_AFTER_MS, UPDATE_ROLLED_BACK, checkBootAfterUpdate, cleanupRetired, clearStaleInstalledMarker,
44
46
  confirmUpdate, ingestSupervisorRollback, isStandaloneBinary, noteCleanExit, updateProfile,
@@ -141,6 +143,24 @@ async function ensurePaired({ serverUrl, apiKey, code, roots, rootsGiven, name,
141
143
  return creds;
142
144
  }
143
145
 
146
+ /**
147
+ * `aivin remote pair --code`: chỉ ghép máy, không nhận việc — bộ cài dùng khi đã có khay (khay thấy máy đã ghép là mở listener ngay,
148
+ * người dùng đóng được cửa sổ cài). Listener đang chạy bằng token cũ thì dừng nó để khay mở lại bằng token mới. Trả pid đã dừng (hoặc null).
149
+ */
150
+ export async function pairWithCodeOnly(options) {
151
+ const serverUrl = resolveServerUrl(options, loadDeviceCredentials());
152
+ configureProxy({ explicit: options.proxy });
153
+ const fullAccess = !options.dir && !!options.fullAccess;
154
+ const roots = (fullAccess ? fullAccessRoots() : [options.dir || process.cwd()]).map((r) => path.resolve(r));
155
+ const access = fullAccess ? DeviceAccess.FULL : DeviceAccess.FOLDERS;
156
+ const profile = { ...buildDeviceProfile(fullAccess ? [os.homedir()] : roots), roots, access };
157
+ const creds = await pairDeviceWithCode({ serverUrl, code: options.code, roots, name: options.name, profile });
158
+ saveDeviceCredentials({ ...creds, access });
159
+ const stale = lockHolder();
160
+ if (stale) try { process.kill(stale); } catch { /* vừa tự thoát */ }
161
+ return { creds, stopped: stale };
162
+ }
163
+
144
164
  /**
145
165
  * Daemon nhận việc từ BE (`aivin remote start`): ghép máy (token thiết bị riêng), nối namespace `/device`, công bố hồ sơ + danh mục công
146
166
  * cụ theo năng lực máy, nhận lô lời gọi, chạy song song theo nhóm, trả kết quả + luồng stdout. Thư mục gốc, công tắc ngắt, lọc biến môi
@@ -238,11 +258,12 @@ export async function startRemoteClient(options = {}) {
238
258
  const fileIndex = multiUser ? null : createFileIndex(indexRootsFor(roots, fullAccess));
239
259
  const useDailyBrowser = options.separateBrowser !== true;
240
260
  const browserTunnels = browser ? createBrowserTunnels({ serverUrl, deviceToken: () => creds.device_token, browser, useDailyBrowser, say: (m) => say(chalk.cyan(m)) }) : null;
241
- // Một tiến trình host chung cho giao diện + Office (chỉ dựng khi lời gọi đầu tiên cần).
242
- const winHost = guiProfile || officeApps.length ? createWindowsHost() : null;
261
+ // Tiến trình host riêng cho giao diện và cho Office COM (chỉ dựng khi lời gọi đầu tiên cần) — một lệnh COM treo / bị huỷ không làm mất snapshot giao diện.
262
+ const guiHost = guiProfile ? createWindowsHost() : null;
263
+ const officeHost = officeApps.length ? createWindowsHost() : null;
243
264
  // Không nói cửa sổ mà focus đang ở linh vật (chủ máy vừa gõ vào ô hỏi) → cửa sổ họ đang dùng lúc hỏi (mascot/ask.mjs).
244
265
  const gui = guiProfile ? createGuiController({
245
- fullAccess, host: winHost, say: (m) => say(chalk.magenta(m)),
266
+ fullAccess, host: guiHost, say: (m) => say(chalk.magenta(m)),
246
267
  defaultWindow: () => (mascot.pid() ? { avoid_pid: mascot.pid(), fallback: mascotChat?.userWindow()?.window } : null),
247
268
  }) : null;
248
269
  // Kho hoàn tác (xoá → thùng rác của kho, ghi đè → giữ bản cũ). Máy tính tổ chức: công cụ tệp chạy dưới tài khoản thành viên, không có kho.
@@ -301,13 +322,14 @@ export async function startRemoteClient(options = {}) {
301
322
  return ack?.ok ? { ok: true } : { ok: false, error: ack?.error || 'failed' };
302
323
  },
303
324
  }) : null;
304
- const env = { roots, binaries: profile.binaries, projects: profile.projects, fileIndex, browserTunnels, gui, office: officeApps.length ? { host: winHost, apps: officeApps } : null, undo, processes, schedules, watches, transfer, meetings, media, clipboard: multiUser ? null : createClipboard() };
325
+ const env = { roots, binaries: profile.binaries, projects: profile.projects, fileIndex, browserTunnels, gui, office: officeApps.length ? { host: officeHost, apps: officeApps } : null, undo, processes, schedules, watches, transfer, meetings, media, clipboard: multiUser ? null : createClipboard() };
305
326
  const host = multiUser ? createMultiUserHost({ baseEnv: env, say: (m) => say(chalk.gray(m)) }) : null;
306
327
  host?.start();
307
328
  const tools = buildTools(env);
308
329
  const byName = toolMap(tools);
309
330
  // Công cụ chủ máy tắt (`aivin remote policy deny`) không vào danh mục — Planner không lập kế hoạch với nó (gọi tới vẫn bị chặn ở sàn luật).
310
331
  const deniedTools = new Set(policyGuard.read().deny_tools);
332
+ if (deniedTools.has('gui.act')) deniedTools.add('gui.do');
311
333
  const { catalog, hash } = buildCatalog(tools.filter((t) => !deniedTools.has(t.name)));
312
334
  const confirmer = multiUser ? null : createLocalConfirmer();
313
335
  // Nhiều người dùng: thêm trần song song theo từng thành viên — một người không chiếm hết chỗ của cả tổ chức.
@@ -337,6 +359,11 @@ export async function startRemoteClient(options = {}) {
337
359
  },
338
360
  });
339
361
  if (isRemotePaused()) mascot.paused(true);
362
+ const desktopCast = createDesktopCastManager();
363
+ const desktopWebRtc = createDesktopWebRtc({
364
+ emitSignal: (payload) => { if (socket?.connected) socket.emit(DeviceEvent.DESKTOP_CAST_SIGNAL, payload); },
365
+ emitStatus: (payload) => { if (socket?.connected) socket.emit(DeviceEvent.DESKTOP_CAST_STATUS, payload); },
366
+ });
340
367
  let mascotChat = null;
341
368
 
342
369
  say(chalk.blue('💻 Aivin Device Agent — máy này nhận việc từ agent của bạn'));
@@ -358,6 +385,7 @@ export async function startRemoteClient(options = {}) {
358
385
  // `aivin remote meeting start|stop` gõ ở máy → daemon này; buổi ghi / biên bản dở từ lần chạy trước → làm nốt.
359
386
  const stopMeetingRequests = meetings ? watchMeetingRequests(meetings) : null;
360
387
 
388
+ void gui?.prewarm?.();
361
389
  fileIndex?.build()
362
390
  .then((s) => { say(chalk.gray(` Chỉ mục tệp: ${s.files} tệp (${s.updated} cập nhật, ${s.ms} ms)`)); fileIndex.watch(); })
363
391
  .catch((e) => say(chalk.yellow(` ⚠️ Lập chỉ mục tệp lỗi: ${e.message}`)));
@@ -400,7 +428,8 @@ export async function startRemoteClient(options = {}) {
400
428
  void scheduler.cancelAll('Remote control was paused on this device');
401
429
  cancelGating([...gating.keys()]);
402
430
  browserTunnels?.closeAll();
403
- winHost?.close();
431
+ guiHost?.close();
432
+ officeHost?.close();
404
433
  processes.stopAll();
405
434
  }
406
435
  if (paused !== pausedSeen) mascot.paused(paused);
@@ -440,14 +469,16 @@ export async function startRemoteClient(options = {}) {
440
469
  if (selfManaged) noteCleanExit();
441
470
  const draining = scheduler.cancelAll('The Aivin agent on this device stopped');
442
471
  cancelGating([...gating.keys()]);
443
- ledger.persist();
472
+ ledger.persist({ sync: true });
444
473
  socket.disconnect();
445
474
  browserTunnels?.closeAll();
446
475
  // Đóng tệp ghi họp cho đúng; biên bản làm ở lần chạy sau (meetings.recover).
447
476
  stopMeetingRequests?.();
448
477
  void meetings?.shutdown();
449
478
  gui?.close();
450
- winHost?.close();
479
+ guiHost?.close();
480
+ officeHost?.close();
481
+ desktopCast.stop();
451
482
  processes.stopAll();
452
483
  keepAwake.close();
453
484
  watches?.closeAll();
@@ -759,6 +790,56 @@ export async function startRemoteClient(options = {}) {
759
790
  socket.on(DeviceEvent.NOTIFY, guarded(DeviceEvent.NOTIFY, (payload) => mascotChat.onNotify(payload)));
760
791
  socket.on(DeviceEvent.VOICE_EVENT, guarded(DeviceEvent.VOICE_EVENT, (payload) => mascotChat.onVoiceEvent(payload)));
761
792
  }
793
+ socket.on(DeviceEvent.DESKTOP_CAST_START, guarded(DeviceEvent.DESKTOP_CAST_START, async (payload) => {
794
+ const sessionId = payload?.session_id;
795
+ const viewerId = payload?.viewer_id;
796
+ const webRtcStarted = payload?.transport === 'webrtc' && sessionId && viewerId
797
+ ? await desktopWebRtc.start({ sessionId, viewerId, iceServers: payload?.ice_servers || [] }).catch(() => false)
798
+ : false;
799
+ if (!desktopCast.isActive()) desktopCast.start({
800
+ sessionId: payload?.session_id,
801
+ maxFps: payload?.max_fps || 15,
802
+ maxWidth: payload?.max_width || 1366,
803
+ quality: payload?.quality || 65,
804
+ monitor: payload?.monitor ?? -1,
805
+ onFrame: (frame) => {
806
+ desktopWebRtc.push(frame);
807
+ // Chưa nối xong WebRTC hoặc runtime native không có → JPEG fallback vẫn cho first frame ngay.
808
+ if (desktopWebRtc.needsFallback() && socket.connected) socket.volatile.emit(DeviceEvent.DESKTOP_CAST_FRAME, frame);
809
+ },
810
+ onReady: (meta) => {
811
+ say(chalk.cyan(` 🖥️ Desktop Cast đang phát trực tiếp (${meta.bounds?.width}x${meta.bounds?.height})`));
812
+ if (socket.connected) socket.emit(DeviceEvent.DESKTOP_CAST_STATUS, {
813
+ session_id: sessionId, viewer_id: viewerId, state: 'ready', transport: webRtcStarted ? 'webrtc' : 'jpeg', bounds: meta.bounds,
814
+ });
815
+ },
816
+ onError: (err) => {
817
+ say(chalk.yellow(` ⚠️ Desktop Cast lỗi: ${err?.message || err}`));
818
+ },
819
+ onStop: () => {
820
+ say(chalk.gray(` ⏹ Desktop Cast đã dừng`));
821
+ },
822
+ });
823
+ if (!webRtcStarted && socket.connected) socket.emit(DeviceEvent.DESKTOP_CAST_STATUS, {
824
+ session_id: sessionId, viewer_id: viewerId, state: 'degraded', transport: 'jpeg', reason: 'webrtc_runtime_unavailable',
825
+ });
826
+ }));
827
+ socket.on(DeviceEvent.DESKTOP_CAST_STOP, guarded(DeviceEvent.DESKTOP_CAST_STOP, (payload) => {
828
+ if (payload?.viewer_id) desktopWebRtc.close(payload.viewer_id);
829
+ if (payload?.final !== false) {
830
+ desktopWebRtc.closeAll();
831
+ desktopCast.stop();
832
+ }
833
+ }));
834
+ socket.on(DeviceEvent.DESKTOP_CAST_INPUT, guarded(DeviceEvent.DESKTOP_CAST_INPUT, (payload) => {
835
+ desktopCast.sendInput(payload);
836
+ }));
837
+ socket.on(DeviceEvent.DESKTOP_CAST_CONFIG, guarded(DeviceEvent.DESKTOP_CAST_CONFIG, (payload) => {
838
+ desktopCast.config(payload);
839
+ }));
840
+ socket.on(DeviceEvent.DESKTOP_CAST_SIGNAL, guarded(DeviceEvent.DESKTOP_CAST_SIGNAL, (payload) => {
841
+ void desktopWebRtc.signal(payload).catch(() => undefined);
842
+ }));
762
843
  meetings?.recover();
763
844
 
764
845
  // Lưới cuối: promise bị từ chối mà không ai bắt → ghi log, KHÔNG thoát (daemon phục vụ cả tổ chức, chết là mất mọi lời gọi đang chạy).
@@ -0,0 +1,53 @@
1
+ import { execFile } from 'child_process';
2
+ import fs from 'fs';
3
+ import os from 'os';
4
+ import path from 'path';
5
+
6
+ /**
7
+ * Tệp "chỉ có trên mây" (OneDrive / Dropbox / Google Drive / iCloud trên Windows, Files On-Demand): mở để đọc là Windows TẢI VỀ — một lần
8
+ * quét lập chỉ mục có thể kéo về hàng GB. Đọc thuộc tính thì không tải: OFFLINE (0x1000) / RECALL_ON_OPEN (0x40000) /
9
+ * RECALL_ON_DATA_ACCESS (0x400000) → chỉ lập chỉ mục tên. macOS: tệp iCloud chưa tải là tệp ẩn `.x.icloud` (đã bị bỏ như tệp ẩn).
10
+ */
11
+
12
+ const CLOUD_DIR_RE = /^(OneDrive|Dropbox|Google Drive|iCloudDrive|iCloud Drive|Box)( - .*| \(.*\))?$/i;
13
+ const CLOUD_ONLY_MASK = 0x1000 | 0x40000 | 0x400000;
14
+ const CHECK_TIMEOUT_MS = 60_000;
15
+
16
+ /** Đường dẫn nằm trong thư mục đồng bộ đám mây (chỉ Windows mới có tệp giữ chỗ cần lo). */
17
+ export function inCloudFolder(abs, platform = process.platform) {
18
+ return platform === 'win32' && abs.split(path.sep).some((seg) => CLOUD_DIR_RE.test(seg));
19
+ }
20
+
21
+ const SCRIPT = `
22
+ $ErrorActionPreference = 'SilentlyContinue'
23
+ [Console]::OutputEncoding = [Text.Encoding]::UTF8
24
+ foreach ($p in [IO.File]::ReadAllLines($env:AIVIN_CLOUD_LIST, [Text.Encoding]::UTF8)) {
25
+ try { if (([int][IO.File]::GetAttributes($p)) -band ${CLOUD_ONLY_MASK}) { [Console]::Out.WriteLine($p) } } catch { }
26
+ }
27
+ `;
28
+
29
+ function runPowerShell(listFile) {
30
+ return new Promise((resolve, reject) => {
31
+ execFile('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', SCRIPT], {
32
+ env: { ...process.env, AIVIN_CLOUD_LIST: listFile }, windowsHide: true, timeout: CHECK_TIMEOUT_MS, maxBuffer: 64 * 1024 * 1024, encoding: 'utf8',
33
+ }, (err, stdout) => (err ? reject(err) : resolve(stdout)));
34
+ });
35
+ }
36
+
37
+ /**
38
+ * Trong `paths`, tệp nào chỉ có trên mây — hỏi một lần cho cả lô. Không hỏi được (PowerShell bị chặn…) → coi CẢ LÔ là trên mây: thà mất
39
+ * đoạn chữ đầu còn hơn tải về cả thư mục.
40
+ */
41
+ export async function cloudOnlyFiles(paths, { platform = process.platform, run = runPowerShell } = {}) {
42
+ if (platform !== 'win32' || !paths.length) return new Set();
43
+ const listFile = path.join(os.tmpdir(), `aivin-cloud-${process.pid}-${Date.now()}.txt`);
44
+ try {
45
+ fs.writeFileSync(listFile, paths.join('\n'), 'utf8');
46
+ const out = await run(listFile);
47
+ return new Set(String(out).split(/\r?\n/).filter(Boolean));
48
+ } catch {
49
+ return new Set(paths);
50
+ } finally {
51
+ fs.rmSync(listFile, { force: true });
52
+ }
53
+ }
@@ -86,6 +86,18 @@ export const DeviceEvent = Object.freeze({
86
86
  CHAT_CANCEL: 'device:chat_cancel',
87
87
  /** CLI → BE (30/10/2026): mở phiên chat mới cho linh vật — câu hỏi kế đi vào phiên mới (phiên cũ vẫn trên Aivin). Ack `{ ok, error? }`. */
88
88
  CHAT_NEW: 'device:chat_new',
89
+ /** BE → CLI: yêu cầu bắt đầu phát hình màn hình máy tính trực tiếp (scenecast). */
90
+ DESKTOP_CAST_START: 'device:desktop_cast_start',
91
+ /** BE → CLI: yêu cầu dừng phát hình màn hình máy tính trực tiếp. */
92
+ DESKTOP_CAST_STOP: 'device:desktop_cast_stop',
93
+ /** CLI → BE: một khung hình màn hình máy tính (JPEG base64) kèm kích thước. */
94
+ DESKTOP_CAST_FRAME: 'device:desktop_cast_frame',
95
+ /** BE → CLI: thao tác điều khiển chuột / bàn phím từ xa. */
96
+ DESKTOP_CAST_INPUT: 'device:desktop_cast_input',
97
+ /** BE → CLI: cập nhật cấu hình chất lượng / tốc độ khung hình (FPS, quality). */
98
+ DESKTOP_CAST_CONFIG: 'device:desktop_cast_config',
99
+ DESKTOP_CAST_SIGNAL: 'device:desktop_cast_signal',
100
+ DESKTOP_CAST_STATUS: 'device:desktop_cast_status',
89
101
  });
90
102
 
91
103
  /** Loại báo chủ động (`device:notify`). */
@@ -202,6 +214,9 @@ export const DeviceErrorCode = Object.freeze({
202
214
  GUI_UNAVAILABLE: 'GUI_UNAVAILABLE',
203
215
  /** node_id của lần observe cũ hoặc phần tử đã biến mất — observe lại. */
204
216
  GUI_STALE_NODE: 'GUI_STALE_NODE',
217
+ GUI_TARGET_NOT_FOUND: 'GUI_TARGET_NOT_FOUND',
218
+ GUI_AMBIGUOUS_TARGET: 'GUI_AMBIGUOUS_TARGET',
219
+ GUI_NO_EFFECT: 'GUI_NO_EFFECT',
205
220
  /** Người dùng đang dùng chuột / bàn phím — AI dừng, hỏi trước khi làm tiếp. */
206
221
  GUI_USER_ACTIVE: 'GUI_USER_ACTIVE',
207
222
  /** Ứng dụng không được điều khiển (quản lý mật khẩu, hộp nâng quyền, terminal khi không toàn quyền…). */
@@ -212,6 +227,8 @@ export const DeviceErrorCode = Object.freeze({
212
227
  GUI_LOCKED: 'GUI_LOCKED',
213
228
  /** `gui.wait_for` hết giờ mà giao diện chưa tới trạng thái chờ. */
214
229
  GUI_WAIT_TIMEOUT: 'GUI_WAIT_TIMEOUT',
230
+ /** Cửa sổ ứng dụng đích bị treo (Not Responding) — không gọi UI Automation để tránh đơ host. */
231
+ GUI_WINDOW_HUNG: 'GUI_WINDOW_HUNG',
215
232
  /** OCR của Windows không dùng được (không có gói ngôn ngữ OCR / WinRT lỗi) — observe vẫn trả cây + ảnh. */
216
233
  GUI_OCR_UNAVAILABLE: 'GUI_OCR_UNAVAILABLE',
217
234
  });