@aivin-labs/cli 1.0.27 → 1.0.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -50
- package/bin/cli.mjs +66 -12
- package/bin/lib/context.mjs +61 -113
- package/bin/lib/remote/autoStart.mjs +2 -2
- package/bin/lib/remote/client.mjs +45 -30
- package/bin/lib/remote/constants.mjs +2 -0
- package/bin/lib/remote/credentials.mjs +138 -152
- package/bin/lib/remote/desktop/desktopCastSource.mjs +8 -2
- package/bin/lib/remote/desktop/index.mjs +22 -5
- package/bin/lib/remote/desktop/strings.mjs +10 -0
- package/bin/lib/remote/desktop/traySource.mjs +1127 -976
- package/bin/lib/remote/desktop/uninstall.mjs +1 -1
- package/bin/lib/remote/gui/index.mjs +6 -3
- package/bin/lib/remote/processes.mjs +14 -4
- package/bin/lib/remote/sandbox.mjs +2 -1
- package/bin/lib/remote/tokenRotation.mjs +3 -3
- package/bin/lib/remote/tokenStore.mjs +4 -4
- package/bin/lib/remote/toolHandlers.mjs +8 -2
- package/bin/lib/servers.mjs +69 -0
- package/docs/AIVIN_MASCOT.md +2 -2
- package/docs/CLI.md +1600 -1576
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-mission-flow.png +0 -0
- package/docs/media/cli-capabilities.png +0 -0
- package/package.json +1 -1
|
@@ -5,7 +5,7 @@ import { spawn } from 'child_process';
|
|
|
5
5
|
import { REMOTE_CONFIG_DIR } from '../constants.mjs';
|
|
6
6
|
import { lockHolder } from '../daemonLock.mjs';
|
|
7
7
|
import { disableAutoStart, uninstallDesktopApp } from '../autoStart.mjs';
|
|
8
|
-
import {
|
|
8
|
+
import { clearAllDeviceCredentials, loadDeviceCredentials, unpairDevice } from '../credentials.mjs';
|
|
9
9
|
import { isStandaloneBinary } from '../../update/versions.mjs';
|
|
10
10
|
import { launcherExePath } from './index.mjs';
|
|
11
11
|
|
|
@@ -4,6 +4,7 @@ import { spawn } from 'child_process';
|
|
|
4
4
|
import { DeviceErrorCode, ToolGroup } from '../constants.mjs';
|
|
5
5
|
import { DeviceToolError, resolveInRoots } from '../sandbox.mjs';
|
|
6
6
|
import { showOSNotification } from '../notify.mjs';
|
|
7
|
+
import { PS_UTF8_PREFIX } from '../processes.mjs';
|
|
7
8
|
import { createWindowsHost } from './windowsHost.mjs';
|
|
8
9
|
|
|
9
10
|
/**
|
|
@@ -163,14 +164,16 @@ export function matchApps(apps, query) {
|
|
|
163
164
|
|
|
164
165
|
function runPowerShellJson(script, signal) {
|
|
165
166
|
return new Promise((resolve, reject) => {
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
167
|
+
// Đầu ra UTF-8: tên cửa sổ / ứng dụng tiếng Việt không thành `?` (PowerShell không console ghi theo bảng mã OEM).
|
|
168
|
+
const c = spawn('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command', `${PS_UTF8_PREFIX}${script}`], { windowsHide: true });
|
|
169
|
+
const chunks = [];
|
|
170
|
+
c.stdout.on('data', (d) => { chunks.push(d); });
|
|
169
171
|
const onAbort = () => { try { c.kill(); } catch { /* đã thoát */ } };
|
|
170
172
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
171
173
|
c.on('error', (e) => reject(e));
|
|
172
174
|
c.on('close', () => {
|
|
173
175
|
signal?.removeEventListener('abort', onAbort);
|
|
176
|
+
const out = Buffer.concat(chunks).toString('utf8');
|
|
174
177
|
try { const v = JSON.parse(out || 'null'); resolve(Array.isArray(v) ? v : v ? [v] : []); } catch (e) { reject(e); }
|
|
175
178
|
});
|
|
176
179
|
});
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawn } from 'child_process';
|
|
2
|
+
import { StringDecoder } from 'string_decoder';
|
|
2
3
|
import { DeviceErrorCode, ToolGroup } from './constants.mjs';
|
|
3
4
|
import { DeviceToolError, agentEnv, assertCommandAllowed, displayPath, resolveInRoots } from './sandbox.mjs';
|
|
4
5
|
import { accountEnv, withProcessCap } from './multiUser.mjs';
|
|
@@ -27,9 +28,15 @@ const schema = (properties, required = []) => ({ type: 'object', properties, req
|
|
|
27
28
|
* Chương trình + tham số chạy một dòng lệnh trong shell của máy. PowerShell 5.1 trả mã thoát 1 cho mọi lỗi của chương trình ngoài (mất mã
|
|
28
29
|
* thật — `node` thoát 2 thành 1): bọc để trả đúng `$LASTEXITCODE`, lệnh PowerShell lỗi (không có mã) thì 1.
|
|
29
30
|
*/
|
|
31
|
+
/**
|
|
32
|
+
* PowerShell 5 chạy không có console (daemon) ghi đầu ra theo bảng mã OEM (437/850…): chữ Việt thành `?` ngay tại máy, BE không cứu được
|
|
33
|
+
* (05/11/2026: `Tiếng Việt` → `Ti?ng Vi?t`, tên thư mục `Thư mục` → `Thu m?c`). Đặt UTF-8 (không BOM) cho cả console lẫn ống tới chương trình con.
|
|
34
|
+
*/
|
|
35
|
+
export const PS_UTF8_PREFIX = '$__aivinUtf8 = New-Object System.Text.UTF8Encoding($false); try { [Console]::OutputEncoding = $__aivinUtf8; [Console]::InputEncoding = $__aivinUtf8 } catch {}; $OutputEncoding = $__aivinUtf8; ';
|
|
36
|
+
|
|
30
37
|
export function shellCommand(command, platform = process.platform) {
|
|
31
38
|
if (platform === 'win32') {
|
|
32
|
-
const wrapped =
|
|
39
|
+
const wrapped = `${PS_UTF8_PREFIX}& {
|
|
33
40
|
${command}
|
|
34
41
|
}; if ($LASTEXITCODE) { exit $LASTEXITCODE } elseif (-not $?) { exit 1 }`;
|
|
35
42
|
return [hasPwsh() ? 'pwsh.exe' : 'powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-Command', wrapped]];
|
|
@@ -53,7 +60,8 @@ export function createProcessManager() {
|
|
|
53
60
|
|
|
54
61
|
/** Ghi log theo dòng vào bộ đệm vòng (giữ MAX_LINES dòng cuối); `cursor` tăng mãi để đọc tiếp không sót / không lặp. */
|
|
55
62
|
function pushOutput(p, stream, chunk) {
|
|
56
|
-
|
|
63
|
+
// StringDecoder giữ byte dở của ký tự nhiều byte sang chunk sau (toString() từng chunk ra `Ti���ng`).
|
|
64
|
+
const text = p.partial[stream] + p.decoders[stream].write(chunk);
|
|
57
65
|
const parts = text.split(/\r?\n/);
|
|
58
66
|
p.partial[stream] = parts.pop();
|
|
59
67
|
for (const line of parts) addLine(p, stream, line);
|
|
@@ -91,7 +99,7 @@ export function createProcessManager() {
|
|
|
91
99
|
// Cần gõ vào (trả lời câu hỏi): PowerShell không chuyển stdin sang chương trình con → Windows chạy qua cmd.exe (chương trình con dùng
|
|
92
100
|
// chung stdin, mã thoát giữ nguyên); nơi khác shell vốn đã chuyển.
|
|
93
101
|
const interactive = !!args.interactive && process.platform === 'win32';
|
|
94
|
-
let [cmd, argv] = interactive ? ['cmd.exe', ['/d', '/s', '/c', `"${command}"`]] : shellCommand(command);
|
|
102
|
+
let [cmd, argv] = interactive ? ['cmd.exe', ['/d', '/s', '/c', `"chcp 65001 >nul & ${command}"`]] : shellCommand(command);
|
|
95
103
|
const runAs = env.runAs;
|
|
96
104
|
if (runAs) [cmd, argv] = withProcessCap(cmd, argv);
|
|
97
105
|
const baseEnv = agentEnv();
|
|
@@ -102,7 +110,8 @@ export function createProcessManager() {
|
|
|
102
110
|
const id = `p${++seq}`;
|
|
103
111
|
const p = {
|
|
104
112
|
id, owner: ownerOf(env), name: String(args.name || '').slice(0, 60) || undefined, command, cwdDisplay: displayPath(env.roots, cwd), child, status: 'running', exitCode: null,
|
|
105
|
-
startedAt: Date.now(), endedAt: 0, lines: [], cursor: 0, partial: { stdout: '', stderr: '' },
|
|
113
|
+
startedAt: Date.now(), endedAt: 0, lines: [], cursor: 0, partial: { stdout: '', stderr: '' },
|
|
114
|
+
decoders: { stdout: new StringDecoder('utf8'), stderr: new StringDecoder('utf8') }, waiters: new Set(), exitWaiters: new Set(),
|
|
106
115
|
};
|
|
107
116
|
procs.set(id, p);
|
|
108
117
|
child.stdout.on('data', (c) => pushOutput(p, 'stdout', c));
|
|
@@ -111,6 +120,7 @@ export function createProcessManager() {
|
|
|
111
120
|
child.stdin.on('error', (e) => addLine(p, 'stderr', `Cannot write to input: ${e.message}`));
|
|
112
121
|
const finish = (code) => {
|
|
113
122
|
if (p.status !== 'running') return;
|
|
123
|
+
for (const s of ['stdout', 'stderr']) p.partial[s] += p.decoders[s].end();
|
|
114
124
|
for (const s of ['stdout', 'stderr']) if (p.partial[s]) { addLine(p, s, p.partial[s]); p.partial[s] = ''; }
|
|
115
125
|
p.status = 'exited';
|
|
116
126
|
p.exitCode = code ?? -1;
|
|
@@ -178,7 +178,8 @@ export function scrubEnv(env = process.env) {
|
|
|
178
178
|
export const AGENT_CALL_ENV = 'AIVIN_AGENT_CALL';
|
|
179
179
|
|
|
180
180
|
export function agentEnv(env = process.env) {
|
|
181
|
-
|
|
181
|
+
// Python ghi ra ống theo bảng mã máy (cp1252) → UnicodeEncodeError khi in chữ Việt; ép UTF-8 trừ khi người dùng đã tự đặt.
|
|
182
|
+
return { PYTHONIOENCODING: 'utf-8', PYTHONUTF8: '1', ...scrubEnv(env), [AGENT_CALL_ENV]: '1' };
|
|
182
183
|
}
|
|
183
184
|
|
|
184
185
|
const HUMAN_ONLY_REMOTE_COMMANDS = new Set(['start', 'pair', 'unpair', 'pause', 'resume', 'enable', 'disable', 'reset-id', 'do', 'forget-folder']);
|
|
@@ -8,8 +8,8 @@ import { confirmTokenRotation, revertTokenRotation } from './credentials.mjs';
|
|
|
8
8
|
*/
|
|
9
9
|
|
|
10
10
|
/** Chào thành công bằng `token` → token cũ (nếu còn giữ) hết cần. Không ném. */
|
|
11
|
-
export function settleRotation(token) {
|
|
12
|
-
try { return confirmTokenRotation(token); } catch { return false; }
|
|
11
|
+
export function settleRotation(token, serverUrl) {
|
|
12
|
+
try { return confirmTokenRotation(token, serverUrl); } catch { return false; }
|
|
13
13
|
}
|
|
14
14
|
|
|
15
15
|
/**
|
|
@@ -18,7 +18,7 @@ export function settleRotation(token) {
|
|
|
18
18
|
*/
|
|
19
19
|
export function fallBackToPreviousToken({ creds, socket, isStopped = () => false, delayMs = 1000, revert = revertTokenRotation }) {
|
|
20
20
|
let previous;
|
|
21
|
-
try { previous = revert(creds.device_token); } catch { previous = null; }
|
|
21
|
+
try { previous = revert(creds.device_token, creds.server_url); } catch { previous = null; }
|
|
22
22
|
if (!previous) return false;
|
|
23
23
|
creds.device_token = previous;
|
|
24
24
|
socket.auth = { ...socket.auth, device_token: previous };
|
|
@@ -62,8 +62,8 @@ export function openToken(record) {
|
|
|
62
62
|
if (record.device_token) return record.device_token;
|
|
63
63
|
try {
|
|
64
64
|
if (record.token_store === TokenStoreKind.DPAPI && record.token_enc) return run('powershell.exe', [...PS, DPAPI_UNPROTECT], record.token_enc) || null;
|
|
65
|
-
if (record.token_store === TokenStoreKind.KEYCHAIN) return run('/usr/bin/security', ['find-generic-password', '-a', record.device_id, '-s', SERVICE, '-w']) || null;
|
|
66
|
-
if (record.token_store === TokenStoreKind.LIBSECRET) return run('secret-tool', ['lookup', 'service', SERVICE, 'account', record.device_id]) || null;
|
|
65
|
+
if (record.token_store === TokenStoreKind.KEYCHAIN) return run('/usr/bin/security', ['find-generic-password', '-a', record.token_account || record.device_id, '-s', SERVICE, '-w']) || null;
|
|
66
|
+
if (record.token_store === TokenStoreKind.LIBSECRET) return run('secret-tool', ['lookup', 'service', SERVICE, 'account', record.token_account || record.device_id]) || null;
|
|
67
67
|
} catch { /* không giải được */ }
|
|
68
68
|
return null;
|
|
69
69
|
}
|
|
@@ -71,7 +71,7 @@ export function openToken(record) {
|
|
|
71
71
|
/** Xoá token khỏi kho hệ điều hành (DPAPI / tệp thường: xoá tệp là đủ). */
|
|
72
72
|
export function forgetToken(record) {
|
|
73
73
|
try {
|
|
74
|
-
if (record?.token_store === TokenStoreKind.KEYCHAIN) run('/usr/bin/security', ['delete-generic-password', '-a', record.device_id, '-s', SERVICE]);
|
|
75
|
-
if (record?.token_store === TokenStoreKind.LIBSECRET) run('secret-tool', ['clear', 'service', SERVICE, 'account', record.device_id]);
|
|
74
|
+
if (record?.token_store === TokenStoreKind.KEYCHAIN) run('/usr/bin/security', ['delete-generic-password', '-a', record.token_account || record.device_id, '-s', SERVICE]);
|
|
75
|
+
if (record?.token_store === TokenStoreKind.LIBSECRET) run('secret-tool', ['clear', 'service', SERVICE, 'account', record.token_account || record.device_id]);
|
|
76
76
|
} catch { /* không có thì thôi */ }
|
|
77
77
|
}
|
|
@@ -2,6 +2,7 @@ import fs from 'fs';
|
|
|
2
2
|
import os from 'os';
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import { spawn } from 'child_process';
|
|
5
|
+
import { StringDecoder } from 'string_decoder';
|
|
5
6
|
import { DeviceErrorCode, IGNORED_DIRS, MemoryKind, ToolGroup } from './constants.mjs';
|
|
6
7
|
import { isSecretPath } from './secretPaths.mjs';
|
|
7
8
|
import {
|
|
@@ -343,6 +344,8 @@ function runProcess(cmd, argv, { cwd, signal, onOutput, env, maxOutput = MAX_EXE
|
|
|
343
344
|
const settle = (code, extra = {}) => {
|
|
344
345
|
if (settled) return;
|
|
345
346
|
settled = true;
|
|
347
|
+
if (stdout.length < maxOutput) stdout += outDec.end();
|
|
348
|
+
if (stderr.length < maxOutput) stderr += errDec.end();
|
|
346
349
|
timers.forEach(clearTimeout);
|
|
347
350
|
signal?.removeEventListener('abort', onAbort);
|
|
348
351
|
child.stdout.destroy();
|
|
@@ -363,8 +366,11 @@ function runProcess(cmd, argv, { cwd, signal, onOutput, env, maxOutput = MAX_EXE
|
|
|
363
366
|
timers.push(setTimeout(() => settle(-1), ABORT_SETTLE_MS));
|
|
364
367
|
};
|
|
365
368
|
signal?.addEventListener('abort', onAbort, { once: true });
|
|
366
|
-
|
|
367
|
-
|
|
369
|
+
// StringDecoder: chunk cắt giữa ký tự UTF-8 nhiều byte không thành `�` (chữ Việt / emoji ở biên chunk).
|
|
370
|
+
const outDec = new StringDecoder('utf8');
|
|
371
|
+
const errDec = new StringDecoder('utf8');
|
|
372
|
+
child.stdout.on('data', (chunk) => { const t = outDec.write(chunk); if (stdout.length < maxOutput) stdout += t; if (t) onOutput?.('stdout', t); });
|
|
373
|
+
child.stderr.on('data', (chunk) => { const t = errDec.write(chunk); if (stderr.length < maxOutput) stderr += t; if (t) onOutput?.('stderr', t); });
|
|
368
374
|
child.on('error', (e) => {
|
|
369
375
|
settled = true;
|
|
370
376
|
timers.forEach(clearTimeout);
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { createHash } from 'crypto';
|
|
5
|
+
import { writeFileAtomic } from './remote/atomicFile.mjs';
|
|
6
|
+
|
|
7
|
+
export const SERVER_CONFIG_FILE = path.join(process.env.AIVIN_REMOTE_HOME || path.join(os.homedir(), '.aivin'), 'server.json');
|
|
8
|
+
export const DEFAULT_SERVER_URL = 'https://api.aivin.cloud';
|
|
9
|
+
|
|
10
|
+
export function resolveServerUrl(input, { fallback = DEFAULT_SERVER_URL } = {}) {
|
|
11
|
+
const raw = String(input ?? '').trim();
|
|
12
|
+
if (!raw) return resolveServerUrl(fallback);
|
|
13
|
+
const alias = raw.toLowerCase();
|
|
14
|
+
if (alias === 'cloud') return 'https://api.aivin.cloud';
|
|
15
|
+
if (alias === 'vn') return 'https://api.aivin.vn';
|
|
16
|
+
const local = alias.match(/^local(?::(\d+))?$/);
|
|
17
|
+
if (local) {
|
|
18
|
+
const port = Number(local[1] || 3001);
|
|
19
|
+
if (port < 1 || port > 65535) throw new Error('Cổng local phải nằm trong khoảng 1–65535.');
|
|
20
|
+
return `http://localhost:${port}`;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
const candidate = /^[a-z][a-z\d+.-]*:\/\//i.test(raw) ? raw : `https://${raw}`;
|
|
24
|
+
let url;
|
|
25
|
+
try { url = new URL(candidate); } catch { throw new Error(`Máy chủ không hợp lệ: ${raw}`); }
|
|
26
|
+
if (url.username || url.password) throw new Error('URL máy chủ không được chứa username hoặc password.');
|
|
27
|
+
const host = url.hostname.toLowerCase();
|
|
28
|
+
const loopback = host === 'localhost' || host === '127.0.0.1' || host === '::1' || host === '[::1]';
|
|
29
|
+
if (url.protocol !== 'https:' && !(url.protocol === 'http:' && loopback)) {
|
|
30
|
+
throw new Error('Chỉ localhost mới được dùng HTTP; máy chủ khác phải dùng HTTPS.');
|
|
31
|
+
}
|
|
32
|
+
for (const domain of ['aivin.cloud', 'aivin.vn']) {
|
|
33
|
+
if (host === domain) return `https://api.${domain}`;
|
|
34
|
+
if (host.endsWith(`.${domain}`)) {
|
|
35
|
+
const first = host.slice(0, -(domain.length + 1)).split('.').at(-1);
|
|
36
|
+
if (!/(^|-)api$/.test(first)) return `https://api.${domain}`;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
url.hash = '';
|
|
40
|
+
url.search = '';
|
|
41
|
+
return url.toString().replace(/\/+$/, '');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
export function serverKey(serverUrl) {
|
|
45
|
+
return createHash('sha256').update(resolveServerUrl(serverUrl)).digest('hex').slice(0, 24);
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
export function readActiveServer() {
|
|
49
|
+
try {
|
|
50
|
+
const value = JSON.parse(fs.readFileSync(SERVER_CONFIG_FILE, 'utf8'))?.server_url;
|
|
51
|
+
return value ? resolveServerUrl(value) : null;
|
|
52
|
+
} catch { return null; }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
export function setActiveServer(serverUrl) {
|
|
56
|
+
const normalized = resolveServerUrl(serverUrl);
|
|
57
|
+
fs.mkdirSync(path.dirname(SERVER_CONFIG_FILE), { recursive: true });
|
|
58
|
+
writeFileAtomic(SERVER_CONFIG_FILE, `${JSON.stringify({ server_url: normalized }, null, 2)}\n`, { mode: 0o600 });
|
|
59
|
+
try { fs.chmodSync(SERVER_CONFIG_FILE, 0o600); } catch { /* Windows ACL follows the user profile */ }
|
|
60
|
+
return normalized;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
export function serverLabel(serverUrl) {
|
|
64
|
+
const url = resolveServerUrl(serverUrl);
|
|
65
|
+
if (url === 'https://api.aivin.cloud') return 'Cloud';
|
|
66
|
+
if (url === 'https://api.aivin.vn') return 'VN';
|
|
67
|
+
if (url.startsWith('http://localhost:') || url.startsWith('http://127.0.0.1:')) return 'Local';
|
|
68
|
+
return new URL(url).host;
|
|
69
|
+
}
|
package/docs/AIVIN_MASCOT.md
CHANGED
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
# Aivin mascot
|
|
2
2
|
|
|
3
3
|
<p align="center">
|
|
4
|
-
<img src="media/aivin-mascot-live.gif" alt="The
|
|
4
|
+
<img src="media/aivin-mascot-live.gif" alt="The live Aivin mascot ask box showing a conversation and the mascot" width="720" />
|
|
5
5
|
</p>
|
|
6
6
|
|
|
7
7
|
The Aivin mascot is the floating Windows interface for Aivin Remote. It shows what the agent is doing, accepts typed or spoken questions, and gives access to recent activity without opening the web app.
|
|
8
8
|
|
|
9
|
-
The animation above is
|
|
9
|
+
The animation above is an enlarged capture of the real WPF ask box and mascot, cropped to remove excess space. It shows the live conversation and the mascot's file attachment states.
|
|
10
10
|
|
|
11
11
|
## How it connects to Aivin
|
|
12
12
|
|