@aivin-labs/cli 1.0.8 → 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.
- package/README.md +41 -0
- package/bin/assets/aivin-mascot.png +0 -0
- package/bin/cli.mjs +1979 -1780
- package/bin/lib/browserAutomation.mjs +232 -469
- package/bin/lib/localBrowser.mjs +345 -0
- package/bin/lib/remote/activityLog.mjs +1 -1
- package/bin/lib/remote/autoStart.mjs +174 -14
- package/bin/lib/remote/browserTunnel.mjs +187 -37
- package/bin/lib/remote/callLedger.mjs +74 -15
- package/bin/lib/remote/cdpPolicy.mjs +14 -1
- package/bin/lib/remote/client.mjs +174 -11
- package/bin/lib/remote/clipboard.mjs +138 -0
- package/bin/lib/remote/cloudFiles.mjs +53 -0
- package/bin/lib/remote/codingAgents.mjs +293 -0
- package/bin/lib/remote/constants.mjs +78 -0
- package/bin/lib/remote/dailyBrowser.mjs +9 -3
- package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
- package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
- package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
- package/bin/lib/remote/desktop/index.mjs +309 -0
- package/bin/lib/remote/desktop/linux.mjs +144 -0
- package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -0
- package/bin/lib/remote/desktop/mac.mjs +187 -0
- package/bin/lib/remote/desktop/macTraySource.mjs +295 -0
- package/bin/lib/remote/desktop/strings.mjs +74 -0
- package/bin/lib/remote/desktop/traySource.mjs +541 -0
- package/bin/lib/remote/deviceProfile.mjs +1 -0
- package/bin/lib/remote/docText.mjs +86 -1
- package/bin/lib/remote/fileIndexer.mjs +757 -399
- package/bin/lib/remote/folderRules.mjs +140 -0
- package/bin/lib/remote/gui/index.mjs +208 -18
- package/bin/lib/remote/gui/windowsHost.mjs +9 -2
- package/bin/lib/remote/gui/windowsHostSource.mjs +444 -49
- package/bin/lib/remote/idempotency.mjs +50 -21
- package/bin/lib/remote/localPolicy.mjs +17 -4
- package/bin/lib/remote/mascot/adpcm.mjs +70 -0
- package/bin/lib/remote/mascot/ask.mjs +768 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +530 -0
- package/bin/lib/remote/mascot/assets.mjs +825 -216
- package/bin/lib/remote/mascot/bot.mjs +397 -0
- package/bin/lib/remote/mascot/hostSource.mjs +500 -103
- package/bin/lib/remote/mascot/hotkey.mjs +66 -0
- package/bin/lib/remote/mascot/index.mjs +199 -28
- package/bin/lib/remote/mascot/labels.mjs +2 -3
- package/bin/lib/remote/mascot/rigSource.mjs +614 -0
- package/bin/lib/remote/mascot/strings.mjs +204 -18
- package/bin/lib/remote/mascot/ui.mjs +104 -0
- package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
- package/bin/lib/remote/meeting/index.mjs +415 -0
- package/bin/lib/remote/meeting/recorder.mjs +109 -0
- package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
- package/bin/lib/remote/meeting/transcribe.mjs +259 -0
- package/bin/lib/remote/osSearch.mjs +107 -0
- package/bin/lib/remote/sqliteDb.mjs +51 -0
- package/bin/lib/remote/tabGroups.mjs +209 -0
- package/bin/lib/remote/toolHandlers.mjs +788 -726
- package/bin/lib/remoteControl.mjs +26 -26
- package/docs/AIVIN_MASCOT.md +130 -0
- package/docs/CLI.md +1504 -1353
- package/docs/media/aivin-mascot-live.gif +0 -0
- package/docs/media/aivin-mascot-live.png +0 -0
- package/docs/media/aivin-remote-architecture.svg +102 -0
- package/package.json +71 -71
|
@@ -0,0 +1,293 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import os from 'os';
|
|
3
|
+
import path from 'path';
|
|
4
|
+
import { randomUUID } from 'crypto';
|
|
5
|
+
import { execFileSync, spawn } from 'child_process';
|
|
6
|
+
import { DeviceErrorCode, REMOTE_CONFIG_DIR, ToolGroup } from './constants.mjs';
|
|
7
|
+
import { DeviceToolError, resolveInRoots, scrubEnv } from './sandbox.mjs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Giao việc cho agent lập trình trên máy (30/10/2026) — Claude Code trước, Codex / Gemini / Aider… sau — bằng chế độ không giao diện của
|
|
11
|
+
* chính agent (`claude -p --output-format stream-json`…) thay vì gõ vào panel trong VS Code qua GUI (webview, cây trợ năng trống, giòn).
|
|
12
|
+
*
|
|
13
|
+
* Một bộ công cụ chung `agent.run / status / stop / sessions` + một ADAPTER mỏng mỗi agent. Adapter chỉ khai cái riêng của agent đó:
|
|
14
|
+
* tìm binary, dựng tham số (chế độ quyền, nói tiếp phiên, model), đọc một dòng sự kiện ra chữ / công cụ / kết quả. Phần chung viết một lần:
|
|
15
|
+
* chạy nền, chờ, đọc tiếp theo con trỏ, dừng, nhớ phiên theo thư mục, đẩy chữ lên Aivin (`ctx.onOutput`). Thêm agent = thêm adapter đã
|
|
16
|
+
* kiểm cờ dòng lệnh THẬT trên máy (không đoán).
|
|
17
|
+
*
|
|
18
|
+
* An toàn: đề bài đi qua stdin (không lộ trong danh sách tiến trình, không dính trích dẫn của shell); chế độ quyền chỉ `plan` (chỉ đọc) /
|
|
19
|
+
* `manual` (mặc định: việc cần quyền bị từ chối — chế độ không giao diện không ai trả lời hộp hỏi) / `accept_edits` (sửa tệp trong thư
|
|
20
|
+
* mục) — không bao giờ chế độ bỏ qua quyền. BE xét `agent.run` như `shell.exec` (buộc hỏi người ở máy không toàn quyền): agent tự chạy lệnh.
|
|
21
|
+
*/
|
|
22
|
+
|
|
23
|
+
const SESSIONS_FILE = path.join(REMOTE_CONFIG_DIR, 'agent-sessions.json');
|
|
24
|
+
const MAX_SESSIONS = 50;
|
|
25
|
+
const MAX_JOBS = 4;
|
|
26
|
+
const DEFAULT_WAIT_MS = 90_000;
|
|
27
|
+
const MAX_WAIT_MS = 10 * 60_000;
|
|
28
|
+
const MAX_PROMPT_CHARS = 20_000;
|
|
29
|
+
const MAX_ANSWER_CHARS = 12_000;
|
|
30
|
+
const MAX_TEXTS = 400;
|
|
31
|
+
const KEEP_DONE_MS = 30 * 60_000;
|
|
32
|
+
/** Đã chạy đủ MAX_JOBS việc cùng lúc. */
|
|
33
|
+
const AGENT_BUSY = 'AGENT_BUSY';
|
|
34
|
+
const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
|
|
35
|
+
const MODEL_RE = /^[a-z0-9][a-z0-9.\-[\]]{0,60}$/i;
|
|
36
|
+
|
|
37
|
+
/** Chế độ quyền chung — mỗi adapter đổi sang cờ của agent mình; agent không có chế độ tương đương thì từ chối. */
|
|
38
|
+
export const AgentMode = Object.freeze({ PLAN: 'plan', MANUAL: 'manual', ACCEPT_EDITS: 'accept_edits' });
|
|
39
|
+
|
|
40
|
+
const str = (description) => ({ type: 'string', description });
|
|
41
|
+
const num = (description) => ({ type: 'number', description });
|
|
42
|
+
const schema = (properties, required = []) => ({ type: 'object', properties, required });
|
|
43
|
+
|
|
44
|
+
/** `<dir>/<exe>` của mọi thư mục trong PATH. */
|
|
45
|
+
function onPath(exe, env) {
|
|
46
|
+
return String(env.PATH || env.Path || '').split(path.delimiter).filter(Boolean).map((dir) => path.join(dir, exe));
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Claude Code (2.1.x): `-p --output-format stream-json --verbose`, `--permission-mode`, `--resume <id>`, `--model`. Kiểm thật 30/10/2026. */
|
|
50
|
+
export const CLAUDE_ADAPTER = Object.freeze({
|
|
51
|
+
id: 'claude',
|
|
52
|
+
label: 'Claude Code',
|
|
53
|
+
candidates({ env = process.env, platform = process.platform, home = os.homedir() } = {}) {
|
|
54
|
+
const exe = platform === 'win32' ? 'claude.exe' : 'claude';
|
|
55
|
+
const out = [...onPath(exe, env), path.join(home, '.local', 'bin', exe), path.join(home, '.claude', 'local', exe)];
|
|
56
|
+
// Bản kèm extension VS Code (người dùng chỉ cài extension, không cài CLI).
|
|
57
|
+
const extRoot = path.join(home, '.vscode', 'extensions');
|
|
58
|
+
try {
|
|
59
|
+
for (const d of fs.readdirSync(extRoot)) if (d.startsWith('anthropic.claude-code-')) out.push(path.join(extRoot, d, 'resources', 'native-binary', exe));
|
|
60
|
+
} catch { /* không có VS Code */ }
|
|
61
|
+
return out;
|
|
62
|
+
},
|
|
63
|
+
args({ mode, resume, model }) {
|
|
64
|
+
const flag = { [AgentMode.PLAN]: 'plan', [AgentMode.MANUAL]: 'manual', [AgentMode.ACCEPT_EDITS]: 'acceptEdits' }[mode];
|
|
65
|
+
const argv = ['-p', '--output-format', 'stream-json', '--verbose', '--permission-mode', flag];
|
|
66
|
+
if (resume) argv.push('--resume', resume);
|
|
67
|
+
if (model) argv.push('--model', model);
|
|
68
|
+
return argv;
|
|
69
|
+
},
|
|
70
|
+
/** Một dòng `stream-json` → cập nhật việc; trả đoạn chữ đáng đẩy lên Aivin (chữ agent viết / công cụ nó dùng), hoặc ''. */
|
|
71
|
+
parse(job, msg) {
|
|
72
|
+
if (msg.session_id && !job.session_id) job.session_id = msg.session_id;
|
|
73
|
+
if (msg.type === 'system' && msg.subtype === 'init') { job.model = msg.model; return ''; }
|
|
74
|
+
if (msg.type === 'assistant') {
|
|
75
|
+
const parts = [];
|
|
76
|
+
for (const c of msg.message?.content || []) {
|
|
77
|
+
if (c.type === 'text' && c.text?.trim()) { job.texts.push(c.text); parts.push(c.text); }
|
|
78
|
+
if (c.type === 'tool_use') {
|
|
79
|
+
const target = c.input?.file_path || c.input?.path || c.input?.command || c.input?.pattern || c.input?.url || '';
|
|
80
|
+
const line = `🔧 ${c.name}${target ? ` ${String(target).slice(0, 160)}` : ''}`;
|
|
81
|
+
job.tools.push(line);
|
|
82
|
+
parts.push(line);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
return parts.join('\n');
|
|
86
|
+
}
|
|
87
|
+
if (msg.type === 'result') {
|
|
88
|
+
job.result = {
|
|
89
|
+
ok: !msg.is_error && msg.subtype === 'success', answer: String(msg.result ?? '').slice(0, MAX_ANSWER_CHARS),
|
|
90
|
+
cost_usd: typeof msg.total_cost_usd === 'number' ? Math.round(msg.total_cost_usd * 10_000) / 10_000 : undefined,
|
|
91
|
+
turns: msg.num_turns, duration_ms: msg.duration_ms,
|
|
92
|
+
};
|
|
93
|
+
}
|
|
94
|
+
return '';
|
|
95
|
+
},
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
export const DEFAULT_AGENT_ADAPTERS = Object.freeze([CLAUDE_ADAPTER]);
|
|
99
|
+
|
|
100
|
+
function versionOf(bin) {
|
|
101
|
+
try {
|
|
102
|
+
const out = execFileSync(bin, ['--version'], { encoding: 'utf8', timeout: 15_000, windowsHide: true });
|
|
103
|
+
const m = /(\d+)\.(\d+)\.(\d+)/.exec(out);
|
|
104
|
+
return m ? m.slice(1).map(Number) : null;
|
|
105
|
+
} catch { return null; }
|
|
106
|
+
}
|
|
107
|
+
const newer = (a, b) => { for (let i = 0; i < 3; i++) if (a[i] !== b[i]) return a[i] > b[i]; return false; };
|
|
108
|
+
|
|
109
|
+
/** Bản mới nhất chạy được của một agent trên máy, hoặc null. */
|
|
110
|
+
export function findAgentBinary(adapter, opts = {}) {
|
|
111
|
+
let best = null;
|
|
112
|
+
for (const bin of [...new Set(adapter.candidates(opts))]) {
|
|
113
|
+
if (!fs.existsSync(bin)) continue;
|
|
114
|
+
const v = (opts.versionOf || versionOf)(bin);
|
|
115
|
+
if (v && (!best || newer(v, best.version))) best = { bin, version: v };
|
|
116
|
+
}
|
|
117
|
+
return best ? { bin: best.bin, version: best.version.join('.') } : null;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
/** Tham số của một lần chạy — kiểm chung (chế độ, mã phiên, model) rồi adapter dựng cờ riêng. Đề bài KHÔNG ở đây. */
|
|
121
|
+
export function agentArgs(adapter, { mode = AgentMode.MANUAL, resume, model } = {}) {
|
|
122
|
+
if (!Object.values(AgentMode).includes(mode)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `mode must be one of: ${Object.values(AgentMode).join(', ')}`);
|
|
123
|
+
if (resume && !UUID_RE.test(resume)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'session must be "new", "continue" or a session id');
|
|
124
|
+
if (model && !MODEL_RE.test(model)) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Bad model name');
|
|
125
|
+
return adapter.args({ mode, resume, model });
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function loadSessions() {
|
|
129
|
+
try { const v = JSON.parse(fs.readFileSync(SESSIONS_FILE, 'utf8')); return Array.isArray(v) ? v : []; } catch { return []; }
|
|
130
|
+
}
|
|
131
|
+
function saveSessions(list) {
|
|
132
|
+
try { fs.mkdirSync(path.dirname(SESSIONS_FILE), { recursive: true }); fs.writeFileSync(SESSIONS_FILE, JSON.stringify(list.slice(0, MAX_SESSIONS), null, 1)); } catch { /* chỉ để tiện nói tiếp */ }
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
export function createAgentRunner({ adapters = DEFAULT_AGENT_ADAPTERS, find = findAgentBinary, spawnImpl = spawn, now = Date.now } = {}) {
|
|
136
|
+
const found = new Map();
|
|
137
|
+
const jobs = new Map();
|
|
138
|
+
const binaryOf = (adapter) => {
|
|
139
|
+
if (!found.has(adapter.id)) found.set(adapter.id, find(adapter));
|
|
140
|
+
return found.get(adapter.id);
|
|
141
|
+
};
|
|
142
|
+
/** Agent đã cài trên máy (theo thứ tự ưu tiên của danh sách adapter). */
|
|
143
|
+
const installed = () => adapters.filter((a) => binaryOf(a));
|
|
144
|
+
const adapterFor = (id) => {
|
|
145
|
+
const list = installed();
|
|
146
|
+
if (!list.length) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No coding agent is installed on this computer (looked for: ${adapters.map((a) => a.label).join(', ')})`);
|
|
147
|
+
if (!id) return list[0];
|
|
148
|
+
const a = list.find((x) => x.id === id);
|
|
149
|
+
if (!a) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `${id} is not installed here — available: ${list.map((x) => x.id).join(', ')}`);
|
|
150
|
+
return a;
|
|
151
|
+
};
|
|
152
|
+
|
|
153
|
+
const prune = () => {
|
|
154
|
+
for (const [id, j] of jobs) if (j.status !== 'running' && now() - j.endedAt > KEEP_DONE_MS) jobs.delete(id);
|
|
155
|
+
};
|
|
156
|
+
const view = (j, sinceText = 0, sinceTool = 0) => ({
|
|
157
|
+
job: j.id, agent: j.agent, status: j.status, session_id: j.session_id, cwd: j.cwdShown, mode: j.mode, model: j.model,
|
|
158
|
+
new_text: j.texts.slice(sinceText).join('\n\n').slice(-MAX_ANSWER_CHARS) || undefined,
|
|
159
|
+
tools_used: j.tools.slice(sinceTool).slice(-40),
|
|
160
|
+
...(j.result ? { result: j.result } : {}),
|
|
161
|
+
...(j.error ? { error: j.error } : {}),
|
|
162
|
+
next_text: j.texts.length, next_tool: j.tools.length,
|
|
163
|
+
});
|
|
164
|
+
|
|
165
|
+
function remember(j) {
|
|
166
|
+
if (!j.session_id) return;
|
|
167
|
+
const list = loadSessions().filter((s) => !(s.agent === j.agent && s.session_id === j.session_id));
|
|
168
|
+
list.unshift({ agent: j.agent, session_id: j.session_id, cwd: j.cwd, prompt: j.prompt.slice(0, 200), at: new Date(now()).toISOString(), ok: j.result?.ok });
|
|
169
|
+
saveSessions(list);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
function waitDone(j, ms, signal) {
|
|
173
|
+
if (j.status !== 'running') return Promise.resolve();
|
|
174
|
+
return new Promise((resolve) => {
|
|
175
|
+
const done = () => { clearTimeout(t); signal?.removeEventListener('abort', done); j.waiters.delete(done); resolve(); };
|
|
176
|
+
const t = setTimeout(done, ms);
|
|
177
|
+
signal?.addEventListener('abort', done, { once: true });
|
|
178
|
+
j.waiters.add(done);
|
|
179
|
+
});
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
async function run(args, ctx = {}, env = {}) {
|
|
183
|
+
prune();
|
|
184
|
+
const prompt = String(args.prompt || '').trim();
|
|
185
|
+
if (!prompt) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, 'Give prompt (the task for the coding agent)');
|
|
186
|
+
if (prompt.length > MAX_PROMPT_CHARS) throw new DeviceToolError(DeviceErrorCode.INVALID_ARGS, `prompt is longer than ${MAX_PROMPT_CHARS} characters`);
|
|
187
|
+
if ([...jobs.values()].filter((j) => j.status === 'running').length >= MAX_JOBS) throw new DeviceToolError(AGENT_BUSY, `${MAX_JOBS} agent tasks are already running — wait or agent.stop one`);
|
|
188
|
+
const adapter = adapterFor(args.agent ? String(args.agent) : undefined);
|
|
189
|
+
const cwd = resolveInRoots(env.roots || [], String(args.cwd || (env.roots || [])[0] || '.'));
|
|
190
|
+
if (!fs.existsSync(cwd) || !fs.statSync(cwd).isDirectory()) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `Folder not found: ${args.cwd}`);
|
|
191
|
+
const session = String(args.session || 'new');
|
|
192
|
+
const resume = session === 'new' ? undefined
|
|
193
|
+
: session === 'continue' ? loadSessions().find((s) => s.agent === adapter.id && s.cwd === cwd)?.session_id
|
|
194
|
+
: session;
|
|
195
|
+
if (session === 'continue' && !resume) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No earlier ${adapter.label} session in this folder — use session "new"`);
|
|
196
|
+
const mode = String(args.mode || AgentMode.MANUAL);
|
|
197
|
+
const argv = agentArgs(adapter, { mode, resume, model: args.model ? String(args.model) : undefined });
|
|
198
|
+
|
|
199
|
+
const j = {
|
|
200
|
+
id: `${adapter.id}-${randomUUID().slice(0, 8)}`, agent: adapter.id, status: 'running', prompt, cwd, cwdShown: args.cwd || cwd, mode,
|
|
201
|
+
session_id: resume, model: undefined, texts: [], tools: [], result: null, error: null, endedAt: 0, waiters: new Set(), child: null,
|
|
202
|
+
};
|
|
203
|
+
const child = spawnImpl(binaryOf(adapter).bin, argv, { cwd, env: scrubEnv(process.env), windowsHide: true, stdio: ['pipe', 'pipe', 'pipe'] });
|
|
204
|
+
j.child = child;
|
|
205
|
+
jobs.set(j.id, j);
|
|
206
|
+
let buf = '';
|
|
207
|
+
let stderr = '';
|
|
208
|
+
child.stdout.on('data', (d) => {
|
|
209
|
+
buf += d.toString();
|
|
210
|
+
let nl;
|
|
211
|
+
while ((nl = buf.indexOf('\n')) >= 0) {
|
|
212
|
+
const line = buf.slice(0, nl).trim();
|
|
213
|
+
buf = buf.slice(nl + 1);
|
|
214
|
+
if (!line) continue;
|
|
215
|
+
let msg;
|
|
216
|
+
try { msg = JSON.parse(line); } catch { continue; }
|
|
217
|
+
if (!msg || typeof msg !== 'object') continue;
|
|
218
|
+
const shown = adapter.parse(j, msg);
|
|
219
|
+
if (j.texts.length > MAX_TEXTS) j.texts.splice(0, j.texts.length - MAX_TEXTS);
|
|
220
|
+
if (shown && typeof ctx.onOutput === 'function') { try { ctx.onOutput(`${shown}\n`); } catch { /* chỉ là tiến trình */ } }
|
|
221
|
+
}
|
|
222
|
+
});
|
|
223
|
+
child.stderr.on('data', (d) => { stderr = (stderr + d.toString()).slice(-2000); });
|
|
224
|
+
const finish = (code) => {
|
|
225
|
+
if (j.status !== 'running') return;
|
|
226
|
+
j.status = j.result?.ok ? 'done' : 'failed';
|
|
227
|
+
if (!j.result) j.error = (stderr.trim().split(/\r?\n/).slice(-3).join(' ') || `${adapter.id} exited with code ${code}`).slice(0, 500);
|
|
228
|
+
j.endedAt = now();
|
|
229
|
+
remember(j);
|
|
230
|
+
for (const w of [...j.waiters]) w();
|
|
231
|
+
};
|
|
232
|
+
child.on('error', (e) => { j.error = e.message; finish(-1); });
|
|
233
|
+
child.on('close', (code) => finish(code));
|
|
234
|
+
child.stdin.end(prompt);
|
|
235
|
+
|
|
236
|
+
await waitDone(j, Math.min(Number(args.wait_ms) || DEFAULT_WAIT_MS, MAX_WAIT_MS), ctx.signal);
|
|
237
|
+
return { ...view(j), hint: j.status === 'running' ? 'Still working — call agent.status with this job (and next_text / next_tool) to read on' : undefined };
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
async function status(args, ctx = {}) {
|
|
241
|
+
const j = jobs.get(String(args.job || ''));
|
|
242
|
+
if (!j) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No agent task ${args.job} (finished more than 30 minutes ago, or never started)`);
|
|
243
|
+
await waitDone(j, Math.min(Number(args.wait_ms) || 0, MAX_WAIT_MS), ctx.signal);
|
|
244
|
+
return view(j, Number(args.next_text) || 0, Number(args.next_tool) || 0);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function stop(args) {
|
|
248
|
+
const j = jobs.get(String(args.job || ''));
|
|
249
|
+
if (!j) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No agent task ${args.job}`);
|
|
250
|
+
if (j.status === 'running') {
|
|
251
|
+
try { j.child?.kill(); } catch { /* đã thoát */ }
|
|
252
|
+
j.status = 'stopped'; j.endedAt = now();
|
|
253
|
+
for (const w of [...j.waiters]) w();
|
|
254
|
+
}
|
|
255
|
+
return view(j);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
function sessions(args, _ctx, env = {}) {
|
|
259
|
+
const cwd = args.cwd ? resolveInRoots(env.roots || [], String(args.cwd)) : null;
|
|
260
|
+
return { sessions: loadSessions().filter((s) => (!cwd || s.cwd === cwd) && (!args.agent || s.agent === args.agent)).slice(0, 20) };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
return {
|
|
264
|
+
run, status, stop, sessions,
|
|
265
|
+
installed: () => installed().map((a) => ({ id: a.id, label: a.label, version: binaryOf(a).version })),
|
|
266
|
+
stopAll: () => { for (const j of jobs.values()) if (j.status === 'running') { try { j.child?.kill(); } catch { /* đã thoát */ } } },
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/** Công cụ agent lập trình cho danh mục của Planner — `agent` liệt kê đúng các agent đã cài trên máy này. */
|
|
271
|
+
export function buildAgentTools(runner) {
|
|
272
|
+
const agents = runner.installed();
|
|
273
|
+
const list = agents.map((a) => `${a.id} (${a.label} ${a.version})`).join(', ');
|
|
274
|
+
return [
|
|
275
|
+
{ name: 'agent.run', group: ToolGroup.PROC, handler: (a, c, e) => runner.run(a, c, e),
|
|
276
|
+
description: `Give a task to a coding agent installed on this computer, in a project folder, headless — installed: ${list}. Returns its answer, the tools it used, cost and a session id to continue later. Use this instead of typing into an agent's panel in VS Code through gui.*. session: "new" (default), "continue" (the latest session of that agent in that folder) or a session id. mode: manual (default; anything needing permission is refused), plan (read-only, it only proposes), accept_edits (may edit files in the folder). Waits up to wait_ms, then returns the job still running — read on with agent.status.`,
|
|
277
|
+
input_schema: schema({
|
|
278
|
+
prompt: str('the task, in plain words'), agent: str(`which agent (default ${agents[0]?.id}): ${agents.map((a) => a.id).join(' | ')}`),
|
|
279
|
+
cwd: str('project folder (default the first allowed folder)'), session: str('new | continue | <session id>'),
|
|
280
|
+
mode: str('manual | plan | accept_edits'), model: str('optional model alias of that agent'),
|
|
281
|
+
wait_ms: num(`wait for the answer up to this long (default ${DEFAULT_WAIT_MS}, max ${MAX_WAIT_MS})`),
|
|
282
|
+
}, ['prompt']) },
|
|
283
|
+
{ name: 'agent.status', group: ToolGroup.PROC, read_only: true, handler: (a, c) => runner.status(a, c),
|
|
284
|
+
description: 'Read a running / finished coding-agent task: new text and tools since next_text / next_tool, the result when done. wait_ms waits for it to finish first.',
|
|
285
|
+
input_schema: schema({ job: str('job from agent.run'), next_text: num('cursor from the previous call'), next_tool: num('cursor from the previous call'), wait_ms: num('max 600000') }, ['job']) },
|
|
286
|
+
{ name: 'agent.stop', group: ToolGroup.PROC, handler: (a) => runner.stop(a),
|
|
287
|
+
description: 'Stop a running coding-agent task.',
|
|
288
|
+
input_schema: schema({ job: str('job from agent.run') }, ['job']) },
|
|
289
|
+
{ name: 'agent.sessions', group: ToolGroup.PROC, read_only: true, handler: (a, c, e) => runner.sessions(a, c, e),
|
|
290
|
+
description: 'Recent coding-agent sessions started from Aivin on this computer (agent, folder, first words of the task, when, ok) — to continue one.',
|
|
291
|
+
input_schema: schema({ cwd: str('only sessions of this folder'), agent: str('only this agent') }) },
|
|
292
|
+
];
|
|
293
|
+
}
|
|
@@ -55,8 +55,66 @@ export const DeviceEvent = Object.freeze({
|
|
|
55
55
|
WATCHES: 'device:watches',
|
|
56
56
|
/** CLI → BE (29/10/2026): sắp thoát để chuyển sang bản CLI vừa tự cập nhật — `{ reason, version, expect_back_ms }`; máy sẽ nối lại ngay. */
|
|
57
57
|
RESTARTING: 'device:restarting',
|
|
58
|
+
/** CLI → BE (29/10/2026): chủ máy hỏi / giao việc qua linh vật — `{ text, request_id }`, ack `{ ok, request_id, session_id, error? }`. */
|
|
59
|
+
CHAT: 'device:chat',
|
|
60
|
+
/** BE → CLI: tiến trình / câu trả lời của lượt chat — `{ request_id, kind: progress | answer | timeout | error, text }`. */
|
|
61
|
+
CHAT_EVENT: 'device:chat_event',
|
|
62
|
+
/** CLI → BE: giọng nói (WAV) → chữ, ack `{ ok, text, error? }` (biên bản họp). */
|
|
63
|
+
STT: 'device:stt',
|
|
64
|
+
/** CLI → BE (29/10/2026): mở phiên nói chuyện realtime với linh vật — ack `{ ok, session_id, error? }`, rồi `device:voice_event`. */
|
|
65
|
+
VOICE_START: 'device:voice_start',
|
|
66
|
+
/** CLI → BE: một đoạn mic `{ audio }` (base64 PCM16 mono, tần số `input_sample_rate` của sự kiện `ready`). */
|
|
67
|
+
VOICE_AUDIO: 'device:voice_audio',
|
|
68
|
+
/** CLI → BE: ngắt lời bot đang nói. */
|
|
69
|
+
VOICE_INTERRUPT: 'device:voice_interrupt',
|
|
70
|
+
/** CLI → BE: kết thúc phiên nói chuyện. */
|
|
71
|
+
VOICE_STOP: 'device:voice_stop',
|
|
72
|
+
/** BE → CLI: `{ kind: ready | user_transcript | assistant_transcript | audio | audio_done | speech_started | error | closed, … }`. */
|
|
73
|
+
VOICE_EVENT: 'device:voice_event',
|
|
74
|
+
/**
|
|
75
|
+
* BE → CLI (29/10/2026): linh vật báo chủ động — việc của chủ máy (giao trên web, chạy nền, automation…) xong / lỗi / cần trả lời:
|
|
76
|
+
* `{ id, kind: done | failed | needs_you, title, text, session_id?, question? }`.
|
|
77
|
+
*/
|
|
78
|
+
NOTIFY: 'device:notify',
|
|
79
|
+
/** CLI → BE (30/10/2026): báo chủ động chưa nhận (offline / rớt mạng lúc gửi) — ack `{ ok, notices }`; gọi sau HELLO. */
|
|
80
|
+
INBOX: 'device:inbox',
|
|
81
|
+
/** CLI → BE: đã nhận các báo `{ ids }` (từ `notify`, `inbox`, hay `notice_id` của `chat_event`) — BE bỏ khỏi hộp. */
|
|
82
|
+
NOTIFY_ACK: 'device:notify_ack',
|
|
83
|
+
/** CLI → BE: câu hỏi còn ghim đã đóng chưa `{ items: [{ session_id, reply_id }] }` — ack `{ ok, closed: reply_id[] }`. */
|
|
84
|
+
QUESTIONS: 'device:questions',
|
|
85
|
+
/** CLI → BE: dừng lượt chat đang chạy `{ request_id }` — lượt kết thúc bằng `error` mã `cancelled`. */
|
|
86
|
+
CHAT_CANCEL: 'device:chat_cancel',
|
|
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
|
+
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',
|
|
58
101
|
});
|
|
59
102
|
|
|
103
|
+
/** Loại báo chủ động (`device:notify`). */
|
|
104
|
+
export const NotifyKind = Object.freeze({ DONE: 'done', FAILED: 'failed', NEEDS_YOU: 'needs_you' });
|
|
105
|
+
|
|
106
|
+
/** Loại sự kiện của phiên nói chuyện (`device:voice_event`). */
|
|
107
|
+
export const VoiceEventKind = Object.freeze({
|
|
108
|
+
READY: 'ready', USER_TRANSCRIPT: 'user_transcript', ASSISTANT_TRANSCRIPT: 'assistant_transcript', AUDIO: 'audio', AUDIO_DONE: 'audio_done',
|
|
109
|
+
SPEECH_STARTED: 'speech_started', ERROR: 'error', CLOSED: 'closed',
|
|
110
|
+
/** Dòng tiến trình của việc agent đang làm trong lúc nói chuyện. */
|
|
111
|
+
PROGRESS: 'progress',
|
|
112
|
+
});
|
|
113
|
+
|
|
114
|
+
/** Loại sự kiện của lượt chat từ linh vật (`device:chat_event`). */
|
|
115
|
+
/** `delta`: câu trả lời đang viết — `text` = cả câu tới lúc đó; chỉ tới khi máy xin (`stream: true` trong `device:chat`). */
|
|
116
|
+
export const ChatEventKind = Object.freeze({ PROGRESS: 'progress', ANSWER: 'answer', TIMEOUT: 'timeout', ERROR: 'error', NEEDS_INPUT: 'needs_input', DELTA: 'delta' });
|
|
117
|
+
|
|
60
118
|
/** Năng lực BE báo trong ack của `device:hello` (`features`). */
|
|
61
119
|
/** Pha của `device:hold`: `waiting` = chờ người bấm xác nhận trên máy, `started` = đã qua hộp, bước bắt đầu chạy (BE phân biệt chưa chạy / chạy dở). */
|
|
62
120
|
export const HoldPhase = Object.freeze({ WAITING: 'waiting', STARTED: 'started' });
|
|
@@ -66,6 +124,14 @@ export const ServerFeature = Object.freeze({
|
|
|
66
124
|
WATCH: 'watch',
|
|
67
125
|
/** BE gửi lại lời gọi khi máy nối lại + xác nhận từng kết quả (ack của `device:result`) — máy giữ kết quả tới khi BE nhận. */
|
|
68
126
|
RESUME: 'resume',
|
|
127
|
+
/** Nói chuyện realtime với linh vật (`device:voice_*`). */
|
|
128
|
+
VOICE: 'voice',
|
|
129
|
+
/** Hộp báo chủ động (`device:inbox` / `device:notify_ack`) + `device:questions`. */
|
|
130
|
+
INBOX: 'inbox',
|
|
131
|
+
/** Dừng lượt chat từ linh vật (`device:chat_cancel`). */
|
|
132
|
+
CHAT_CANCEL: 'chat_cancel',
|
|
133
|
+
/** Mở phiên chat mới cho linh vật (`device:chat_new`). */
|
|
134
|
+
CHAT_NEW: 'chat_new',
|
|
69
135
|
});
|
|
70
136
|
|
|
71
137
|
/** Nhóm giới hạn song song trên máy — mỗi công cụ thuộc một nhóm. */
|
|
@@ -84,6 +150,8 @@ export const ToolGroup = Object.freeze({
|
|
|
84
150
|
OFFICE: 'office',
|
|
85
151
|
/** Tiến trình nền (proc.*) — proc.wait_for giữ chỗ lâu nên trần rộng hơn nhóm chạy lệnh. */
|
|
86
152
|
PROC: 'proc',
|
|
153
|
+
/** Ghi chú cuộc họp (meeting.*) + chụp màn hình (screen.capture). */
|
|
154
|
+
MEDIA: 'media',
|
|
87
155
|
});
|
|
88
156
|
|
|
89
157
|
/** Số lời gọi chạy cùng lúc tối đa mỗi nhóm (chỉnh qua biến môi trường AIVIN_REMOTE_LIMIT_<NHÓM>). */
|
|
@@ -98,6 +166,7 @@ export const DEFAULT_GROUP_LIMITS = Object.freeze({
|
|
|
98
166
|
[ToolGroup.GUI]: 1,
|
|
99
167
|
[ToolGroup.OFFICE]: 1,
|
|
100
168
|
[ToolGroup.PROC]: 16,
|
|
169
|
+
[ToolGroup.MEDIA]: 4,
|
|
101
170
|
});
|
|
102
171
|
|
|
103
172
|
/**
|
|
@@ -145,6 +214,9 @@ export const DeviceErrorCode = Object.freeze({
|
|
|
145
214
|
GUI_UNAVAILABLE: 'GUI_UNAVAILABLE',
|
|
146
215
|
/** node_id của lần observe cũ hoặc phần tử đã biến mất — observe lại. */
|
|
147
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',
|
|
148
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. */
|
|
149
221
|
GUI_USER_ACTIVE: 'GUI_USER_ACTIVE',
|
|
150
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…). */
|
|
@@ -153,6 +225,12 @@ export const DeviceErrorCode = Object.freeze({
|
|
|
153
225
|
GUI_PASSWORD_FIELD: 'GUI_PASSWORD_FIELD',
|
|
154
226
|
/** Màn hình đang khoá / hộp bảo mật đang hiện. */
|
|
155
227
|
GUI_LOCKED: 'GUI_LOCKED',
|
|
228
|
+
/** `gui.wait_for` hết giờ mà giao diện chưa tới trạng thái chờ. */
|
|
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',
|
|
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. */
|
|
233
|
+
GUI_OCR_UNAVAILABLE: 'GUI_OCR_UNAVAILABLE',
|
|
156
234
|
});
|
|
157
235
|
|
|
158
236
|
export const MemoryKind = Object.freeze({
|
|
@@ -3,7 +3,7 @@ import net from 'net';
|
|
|
3
3
|
import path from 'path';
|
|
4
4
|
import { execFile } from 'child_process';
|
|
5
5
|
import WSClient from 'ws';
|
|
6
|
-
import { LOCAL_BROWSERS, resolveBrowserInstall } from '../
|
|
6
|
+
import { LOCAL_BROWSERS, resolveBrowserInstall } from '../localBrowser.mjs';
|
|
7
7
|
import { applyDevicePolicy, executableDownloadGuid } from './cdpPolicy.mjs';
|
|
8
8
|
|
|
9
9
|
/**
|
|
@@ -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)
|
|
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
|
|
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,198 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import readline from 'readline';
|
|
4
|
+
import { createHash } from 'crypto';
|
|
5
|
+
import { spawn } from 'child_process';
|
|
6
|
+
import { REMOTE_CONFIG_DIR } from '../constants.mjs';
|
|
7
|
+
import { DESKTOP_CAST_CSHARP, DESKTOP_CAST_PS1 } from './desktopCastSource.mjs';
|
|
8
|
+
|
|
9
|
+
const CAST_DIR = path.join(REMOTE_CONFIG_DIR, 'desktop-cast');
|
|
10
|
+
|
|
11
|
+
function hostFiles(dir = CAST_DIR) {
|
|
12
|
+
const hash = createHash('sha256').update(DESKTOP_CAST_CSHARP).update(DESKTOP_CAST_PS1).digest('hex').slice(0, 16);
|
|
13
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
14
|
+
const src = path.join(dir, `cast-${hash}.cs`);
|
|
15
|
+
const ps1 = path.join(dir, `cast-${hash}.ps1`);
|
|
16
|
+
if (!fs.existsSync(src)) fs.writeFileSync(src, DESKTOP_CAST_CSHARP);
|
|
17
|
+
if (!fs.existsSync(ps1)) fs.writeFileSync(ps1, DESKTOP_CAST_PS1);
|
|
18
|
+
for (const name of fs.readdirSync(dir)) {
|
|
19
|
+
if (name.startsWith('cast-') && !name.startsWith(`cast-${hash}`)) fs.rmSync(path.join(dir, name), { force: true });
|
|
20
|
+
}
|
|
21
|
+
return { src, ps1, dll: path.join(dir, `cast-${hash}.dll`) };
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export function isDesktopCastSupported(platform = process.platform) {
|
|
25
|
+
return platform === 'win32';
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Quản lý phiên phát hình ảnh và điều khiển máy tính từ xa.
|
|
30
|
+
*/
|
|
31
|
+
export function createDesktopCastManager({ dir = CAST_DIR, spawnImpl = spawn } = {}) {
|
|
32
|
+
let activeSession = null;
|
|
33
|
+
|
|
34
|
+
function start({
|
|
35
|
+
sessionId,
|
|
36
|
+
maxFps = 15,
|
|
37
|
+
maxWidth = 1366,
|
|
38
|
+
quality = 65,
|
|
39
|
+
monitor = -1,
|
|
40
|
+
onFrame,
|
|
41
|
+
onReady,
|
|
42
|
+
onError,
|
|
43
|
+
onStop,
|
|
44
|
+
} = {}) {
|
|
45
|
+
if (activeSession) {
|
|
46
|
+
stop();
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
if (!isDesktopCastSupported()) {
|
|
50
|
+
onError?.(new Error('Desktop cast is currently supported on Windows only'));
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
const files = hostFiles(dir);
|
|
55
|
+
const argsJson = JSON.stringify({
|
|
56
|
+
max_fps: maxFps,
|
|
57
|
+
max_width: maxWidth,
|
|
58
|
+
quality,
|
|
59
|
+
monitor,
|
|
60
|
+
});
|
|
61
|
+
|
|
62
|
+
const child = spawnImpl('powershell.exe', [
|
|
63
|
+
'-NoProfile',
|
|
64
|
+
'-NonInteractive',
|
|
65
|
+
'-ExecutionPolicy',
|
|
66
|
+
'Bypass',
|
|
67
|
+
'-File',
|
|
68
|
+
files.ps1,
|
|
69
|
+
], {
|
|
70
|
+
env: {
|
|
71
|
+
...process.env,
|
|
72
|
+
AIVIN_CAST_SRC: files.src,
|
|
73
|
+
AIVIN_CAST_DLL: files.dll,
|
|
74
|
+
AIVIN_CAST_ARGS: argsJson,
|
|
75
|
+
},
|
|
76
|
+
windowsHide: true,
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
let rl = readline.createInterface({ input: child.stdout });
|
|
80
|
+
|
|
81
|
+
rl.on('line', (line) => {
|
|
82
|
+
let msg;
|
|
83
|
+
try {
|
|
84
|
+
msg = JSON.parse(line);
|
|
85
|
+
} catch {
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
if (msg.t === 'ready') {
|
|
90
|
+
onReady?.(msg);
|
|
91
|
+
} else if (msg.t === 'frame') {
|
|
92
|
+
onFrame?.({
|
|
93
|
+
sessionId,
|
|
94
|
+
image: msg.image,
|
|
95
|
+
width: msg.width,
|
|
96
|
+
height: msg.height,
|
|
97
|
+
screenWidth: msg.screenWidth,
|
|
98
|
+
screenHeight: msg.screenHeight,
|
|
99
|
+
monitor: msg.monitor,
|
|
100
|
+
screens: msg.screens,
|
|
101
|
+
ts: msg.ts,
|
|
102
|
+
});
|
|
103
|
+
} else if (msg.t === 'error') {
|
|
104
|
+
onError?.(new Error(msg.error || 'Desktop cast error'));
|
|
105
|
+
}
|
|
106
|
+
});
|
|
107
|
+
|
|
108
|
+
child.on('error', (err) => {
|
|
109
|
+
onError?.(err);
|
|
110
|
+
activeSession = null;
|
|
111
|
+
});
|
|
112
|
+
|
|
113
|
+
child.on('close', () => {
|
|
114
|
+
activeSession = null;
|
|
115
|
+
onStop?.();
|
|
116
|
+
});
|
|
117
|
+
|
|
118
|
+
function sendInput(inputCmd) {
|
|
119
|
+
if (!child.stdin || child.stdin.destroyed) return;
|
|
120
|
+
try {
|
|
121
|
+
const payload = JSON.stringify({ op: 'input', ...inputCmd });
|
|
122
|
+
child.stdin.write(payload + '\n');
|
|
123
|
+
} catch {
|
|
124
|
+
// bỏ qua lỗi ghi stdin nếu tiến trình đang đóng
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
function config(configCmd) {
|
|
129
|
+
if (!child.stdin || child.stdin.destroyed) return;
|
|
130
|
+
try {
|
|
131
|
+
const payload = JSON.stringify({ op: 'config', ...configCmd });
|
|
132
|
+
child.stdin.write(payload + '\n');
|
|
133
|
+
} catch {
|
|
134
|
+
// bỏ qua
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
function stop() {
|
|
139
|
+
if (!activeSession) return;
|
|
140
|
+
activeSession = null;
|
|
141
|
+
try {
|
|
142
|
+
if (child.stdin && !child.stdin.destroyed) {
|
|
143
|
+
child.stdin.write('stop\n');
|
|
144
|
+
}
|
|
145
|
+
} catch {
|
|
146
|
+
// bỏ qua
|
|
147
|
+
}
|
|
148
|
+
setTimeout(() => {
|
|
149
|
+
try {
|
|
150
|
+
child.kill();
|
|
151
|
+
} catch {
|
|
152
|
+
// bỏ qua
|
|
153
|
+
}
|
|
154
|
+
}, 500);
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
activeSession = {
|
|
158
|
+
sessionId,
|
|
159
|
+
child,
|
|
160
|
+
sendInput,
|
|
161
|
+
config,
|
|
162
|
+
stop,
|
|
163
|
+
};
|
|
164
|
+
|
|
165
|
+
return activeSession;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
function sendInput(inputCmd) {
|
|
169
|
+
if (activeSession) {
|
|
170
|
+
activeSession.sendInput(inputCmd);
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function config(configCmd) {
|
|
175
|
+
if (activeSession) {
|
|
176
|
+
activeSession.config(configCmd);
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function stop() {
|
|
181
|
+
if (activeSession) {
|
|
182
|
+
activeSession.stop();
|
|
183
|
+
activeSession = null;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
function isActive() {
|
|
188
|
+
return activeSession !== null;
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
return {
|
|
192
|
+
start,
|
|
193
|
+
sendInput,
|
|
194
|
+
config,
|
|
195
|
+
stop,
|
|
196
|
+
isActive,
|
|
197
|
+
};
|
|
198
|
+
}
|