@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,415 @@
|
|
|
1
|
+
import fs from 'fs';
|
|
2
|
+
import path from 'path';
|
|
3
|
+
import { randomUUID } from 'crypto';
|
|
4
|
+
import { DeviceErrorCode, REMOTE_CONFIG_DIR, ToolGroup } from '../constants.mjs';
|
|
5
|
+
import { DeviceToolError, resolveInRoots } from '../sandbox.mjs';
|
|
6
|
+
import { createMediaHost } from './recorder.mjs';
|
|
7
|
+
import { Speaker, clock, formatTranscript, transcribeRecording } from './transcribe.mjs';
|
|
8
|
+
|
|
9
|
+
/**
|
|
10
|
+
* Ghi chú cuộc họp (29/10/2026): "vào họp cùng tôi, ghi chú, họp xong gửi báo cáo cho sếp". Không ai vào phòng họp thay người dùng — máy ghi
|
|
11
|
+
* tiếng của chính máy này (âm thanh máy = người khác nói, micro = chủ máy) + ảnh màn hình khi đổi (slide chia sẻ), chạy với mọi app họp (Meet,
|
|
12
|
+
* Zoom, Teams, Zalo…). Ghi xong mới xử lý một thể: chuyển chữ từng đoạn qua `device:stt`, ghi `transcript.md`, xoá tệp âm thanh (trừ
|
|
13
|
+
* `keep_audio`), rồi — nếu lúc bắt đầu có dặn `then` — tự mở một lượt chat trên Aivin (`device:chat`, như chủ máy gõ cho linh vật) với việc đã dặn
|
|
14
|
+
* kèm id biên bản; agent đọc biên bản bằng `meeting.transcript`, tóm tắt, soạn thư (gửi thư vẫn phải bấm xác nhận trên máy).
|
|
15
|
+
*
|
|
16
|
+
* Tự dừng khi: cửa sổ họp (đã thấy lúc đầu) đóng VÀ máy im ≥ 60 s; cả hai luồng im `silence_minutes`; quá `max_minutes`; bật công tắc ngắt.
|
|
17
|
+
* Bắt đầu ghi luôn phải có người bấm Cho phép trên máy (localPolicy.mjs) — AI không tự bật ghi âm khi không ai biết.
|
|
18
|
+
* Dữ liệu nằm trong `~/.aivin/meetings/<id>/` (công cụ tệp không đọc được), hoặc `save_dir` trong vùng được phép nếu người dùng muốn tự giữ.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
export const MEETINGS_DIR = path.join(REMOTE_CONFIG_DIR, 'meetings');
|
|
22
|
+
export const MeetingStatus = Object.freeze({ RECORDING: 'recording', TRANSCRIBING: 'transcribing', DONE: 'done', FAILED: 'failed' });
|
|
23
|
+
export const StopReason = Object.freeze({
|
|
24
|
+
REQUESTED: 'requested', MEETING_CLOSED: 'meeting_closed', SILENCE: 'silence', MAX_DURATION: 'max_duration', PAUSED: 'paused',
|
|
25
|
+
SHUTDOWN: 'shutdown', RECORDER_EXITED: 'recorder_exited',
|
|
26
|
+
});
|
|
27
|
+
|
|
28
|
+
/** Tiêu đề cửa sổ / tab của app họp đang trong cuộc họp. */
|
|
29
|
+
export const MEETING_TITLE_RE = /google meet|\bmeet\s*[-–—:]|zoom meeting|zoom workplace|cuộc họp zoom|microsoft teams|webex|skype|zalo|huddle|discord|jitsi|whereby|lark|feishu/i;
|
|
30
|
+
|
|
31
|
+
const SOUND_RMS = 0.01;
|
|
32
|
+
const WINDOW_GONE_MS = 60_000;
|
|
33
|
+
const TICK_MS = 5000;
|
|
34
|
+
const STOP_WAIT_MS = 20_000;
|
|
35
|
+
const MAX_INDEX = 100;
|
|
36
|
+
const MAX_THEN = 2000;
|
|
37
|
+
const TRANSCRIPT_PAGE = 30_000;
|
|
38
|
+
const FOLLOW_UP_RETRY_MS = 60_000;
|
|
39
|
+
const FOLLOW_UP_TRIES = 30;
|
|
40
|
+
|
|
41
|
+
const safeName = (s) => [...String(s || '')].map((ch) => (ch.charCodeAt(0) < 32 || '<>:"/\\|?*'.includes(ch) ? ' ' : ch)).join('').replace(/\s+/g, ' ').trim().slice(0, 60);
|
|
42
|
+
const bad = (m) => new DeviceToolError(DeviceErrorCode.INVALID_ARGS, m);
|
|
43
|
+
const clamp = (v, lo, hi, d) => { const n = Number(v); return Number.isFinite(n) && n > 0 ? Math.min(Math.max(n, lo), hi) : d; };
|
|
44
|
+
|
|
45
|
+
/** Câu mở lượt chat sau buổi họp (gửi như chủ máy gõ). */
|
|
46
|
+
export function followUpText(meta) {
|
|
47
|
+
const vi = meta.lang !== 'en';
|
|
48
|
+
const mins = Math.max(1, Math.round((meta.duration_s || 0) / 60));
|
|
49
|
+
const screens = meta.screens?.length || 0;
|
|
50
|
+
if (vi) {
|
|
51
|
+
return `[Tự động sau cuộc họp] Cuộc họp "${meta.title}" đã kết thúc (${mins} phút). Biên bản ghi âm đã có trên máy này: đọc bằng công cụ meeting.transcript với id "${meta.id}"`
|
|
52
|
+
+ `${screens ? ` (có ${screens} ảnh màn hình, xem bằng meeting.screenshot)` : ''}. Việc tôi đã dặn: ${meta.then}`;
|
|
53
|
+
}
|
|
54
|
+
return `[Automatic, after the meeting] The meeting "${meta.title}" has ended (${mins} min). Its transcript is on this computer: read it with the meeting.transcript tool, id "${meta.id}"`
|
|
55
|
+
+ `${screens ? ` (${screens} screenshots, view with meeting.screenshot)` : ''}. What I asked for: ${meta.then}`;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/**
|
|
59
|
+
* `stt(wav, lang)` → `{ ok, text, error }`; `followUp(text)` → `{ ok, error? }` (mở lượt chat); `isPaused()` — công tắc ngắt; `keepAwake` —
|
|
60
|
+
* `{ hold, release }`; `notify({ title, body })`; `say(text)` — nhật ký daemon.
|
|
61
|
+
*/
|
|
62
|
+
export function createMeetingManager({
|
|
63
|
+
roots = [], media = createMediaHost(), stt, followUp = async () => ({ ok: false, error: 'unavailable' }), isPaused = () => false,
|
|
64
|
+
keepAwake = { hold() {}, release() {} }, notify = () => {}, say = () => {}, lang = 'vi', baseDir = MEETINGS_DIR, tickMs = TICK_MS,
|
|
65
|
+
now = () => Date.now(), micBusy = () => false,
|
|
66
|
+
} = {}) {
|
|
67
|
+
const indexFile = path.join(baseDir, 'index.json');
|
|
68
|
+
let current = null; // { meta, rec, timer, lastSound, windowSeen, windowAt, stopping }
|
|
69
|
+
let queue = Promise.resolve();
|
|
70
|
+
let processing = null; // id đang chuyển chữ
|
|
71
|
+
|
|
72
|
+
const readIndex = () => { try { return JSON.parse(fs.readFileSync(indexFile, 'utf8')); } catch { return []; } };
|
|
73
|
+
const writeIndex = (list) => { fs.mkdirSync(baseDir, { recursive: true }); fs.writeFileSync(indexFile, JSON.stringify(list.slice(0, MAX_INDEX), null, 2)); };
|
|
74
|
+
const metaFile = (dir) => path.join(dir, 'meeting.json');
|
|
75
|
+
const save = (meta) => { fs.mkdirSync(meta.dir, { recursive: true }); fs.writeFileSync(metaFile(meta.dir), JSON.stringify(meta, null, 2)); };
|
|
76
|
+
const load = (dir) => { try { return JSON.parse(fs.readFileSync(metaFile(dir), 'utf8')); } catch { return null; } };
|
|
77
|
+
|
|
78
|
+
function find(id) {
|
|
79
|
+
const list = readIndex();
|
|
80
|
+
const entry = id ? list.find((e) => e.id === id) : list[0];
|
|
81
|
+
const meta = entry ? load(entry.dir) : null;
|
|
82
|
+
if (!meta) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, id ? `No meeting recording with id ${id}` : 'No meeting has been recorded on this computer yet');
|
|
83
|
+
return meta;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
async function start(args = {}) {
|
|
87
|
+
if (current) throw bad(`A meeting is already being recorded ("${current.meta.title}", id ${current.meta.id}) — stop it first with meeting.stop`);
|
|
88
|
+
if (isPaused()) throw new DeviceToolError(DeviceErrorCode.KILL_SWITCH, 'This computer is paused');
|
|
89
|
+
// The owner is talking with the mascot: the bot's voice and that conversation would end up in the meeting notes.
|
|
90
|
+
if (micBusy()) throw bad('The owner is talking with Aivin through the mascot right now — ask them to end that conversation first, then start the recording');
|
|
91
|
+
const id = `m-${new Date(now()).toISOString().slice(0, 10)}-${randomUUID().slice(0, 8)}`;
|
|
92
|
+
const title = String(args.title || '').trim().slice(0, 120) || (lang === 'en' ? 'Meeting' : 'Cuộc họp');
|
|
93
|
+
const then = String(args.then || '').trim();
|
|
94
|
+
if (then.length > MAX_THEN) throw bad(`then is too long (max ${MAX_THEN} characters)`);
|
|
95
|
+
let dir = path.join(baseDir, id);
|
|
96
|
+
if (args.save_dir) {
|
|
97
|
+
const stamp = new Date(now()).toISOString().slice(0, 16).replace('T', ' ').replace(':', 'h');
|
|
98
|
+
dir = path.join(resolveInRoots(roots, String(args.save_dir)), `${stamp} ${safeName(title)}`.trim());
|
|
99
|
+
}
|
|
100
|
+
const meta = {
|
|
101
|
+
id, title, then: then || null, lang: args.lang === 'en' || args.lang === 'vi' ? args.lang : lang, dir, status: MeetingStatus.RECORDING,
|
|
102
|
+
started_at: new Date(now()).toISOString(), ended_at: null, duration_s: 0, stop_reason: null,
|
|
103
|
+
screens_enabled: args.screens !== false, keep_audio: args.keep_audio === true,
|
|
104
|
+
max_minutes: clamp(args.max_minutes, 5, 480, 180), silence_minutes: clamp(args.silence_minutes, 2, 60, 10),
|
|
105
|
+
sources: null, screens: [], progress: null, error: null, follow_up: then ? 'pending' : null, by: args.by || 'ai',
|
|
106
|
+
};
|
|
107
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
108
|
+
const rec = media.record({ dir, screens: meta.screens_enabled });
|
|
109
|
+
try {
|
|
110
|
+
meta.sources = await rec.ready;
|
|
111
|
+
} catch (e) {
|
|
112
|
+
rec.kill();
|
|
113
|
+
fs.rmSync(dir, { recursive: true, force: true });
|
|
114
|
+
throw e;
|
|
115
|
+
}
|
|
116
|
+
save(meta);
|
|
117
|
+
writeIndex([{ id, dir }, ...readIndex().filter((e) => e.id !== id)]);
|
|
118
|
+
const c = { meta, rec, lastSound: now(), windowSeen: false, windowAt: 0, stopping: null, startedMs: now() };
|
|
119
|
+
current = c;
|
|
120
|
+
rec.on('level', (m) => { if (Number(m.system) > SOUND_RMS || Number(m.mic) > SOUND_RMS) c.lastSound = now(); c.level = { system: m.system, mic: m.mic }; c.systemSoundAt = Number(m.system) > SOUND_RMS ? now() : c.systemSoundAt; });
|
|
121
|
+
rec.on('windows', (m) => {
|
|
122
|
+
const hit = (m.titles || []).find((t) => MEETING_TITLE_RE.test(t));
|
|
123
|
+
if (hit) { c.windowSeen = true; c.windowAt = now(); c.windowTitle = hit; }
|
|
124
|
+
});
|
|
125
|
+
rec.on('screen', (m) => { meta.screens.push({ file: m.file, secs: m.secs }); save(meta); });
|
|
126
|
+
rec.on('warn', (m) => say(`⚠️ Ghi họp: ${m.what} — ${m.error}`));
|
|
127
|
+
void rec.done.then(() => { if (current === c && !c.stopping) void stop({ reason: StopReason.RECORDER_EXITED }).catch(() => undefined); });
|
|
128
|
+
c.timer = setInterval(() => tick(c), tickMs);
|
|
129
|
+
c.timer.unref?.();
|
|
130
|
+
keepAwake.hold();
|
|
131
|
+
const missing = !meta.sources.system ? 'âm thanh máy' : !meta.sources.mic ? 'micro' : null;
|
|
132
|
+
say(`🎙️ Đang ghi cuộc họp "${title}"${missing ? ` (không mở được ${missing})` : ''} — dừng: "aivin remote meeting stop" hoặc bảo AI dừng ghi.`);
|
|
133
|
+
notify({
|
|
134
|
+
title: lang === 'en' ? 'Aivin is recording your meeting' : 'Aivin đang ghi cuộc họp',
|
|
135
|
+
body: lang === 'en' ? `"${title}" — let the other participants know. Stop: aivin remote meeting stop` : `"${title}" — hãy báo cho mọi người trong cuộc họp biết. Dừng: aivin remote meeting stop`,
|
|
136
|
+
});
|
|
137
|
+
return {
|
|
138
|
+
id, title, status: meta.status, sources: meta.sources, screens: meta.screens_enabled, max_minutes: meta.max_minutes,
|
|
139
|
+
...(args.save_dir ? { dir } : {}),
|
|
140
|
+
note: 'Recording. Tell the user to let the other participants know they are being recorded. It stops by itself when the meeting window closes, after a long silence or at max_minutes; the transcript is made afterwards'
|
|
141
|
+
+ (then ? ' and a new chat turn starts with the "then" instruction.' : '.'),
|
|
142
|
+
};
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
function tick(c) {
|
|
146
|
+
if (current !== c || c.stopping) return;
|
|
147
|
+
const t = now();
|
|
148
|
+
let reason = null;
|
|
149
|
+
if (isPaused()) reason = StopReason.PAUSED;
|
|
150
|
+
else if (t - c.startedMs >= c.meta.max_minutes * 60_000) reason = StopReason.MAX_DURATION;
|
|
151
|
+
else if (c.windowSeen && t - c.windowAt >= WINDOW_GONE_MS && t - (c.systemSoundAt || 0) >= WINDOW_GONE_MS) reason = StopReason.MEETING_CLOSED;
|
|
152
|
+
else if (t - c.lastSound >= c.meta.silence_minutes * 60_000) reason = StopReason.SILENCE;
|
|
153
|
+
if (reason) void stop({ reason }).catch((e) => say(`⚠️ Dừng ghi họp lỗi: ${e?.message || e}`));
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
async function stop({ id, reason = StopReason.REQUESTED } = {}) {
|
|
157
|
+
const c = current;
|
|
158
|
+
if (!c || (id && c.meta.id !== id)) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, 'No meeting is being recorded');
|
|
159
|
+
if (c.stopping) return c.stopping;
|
|
160
|
+
c.stopping = (async () => {
|
|
161
|
+
clearInterval(c.timer);
|
|
162
|
+
c.rec.stop();
|
|
163
|
+
const timeout = new Promise((r) => setTimeout(() => r('timeout'), STOP_WAIT_MS));
|
|
164
|
+
const finished = await Promise.race([c.rec.done, timeout]);
|
|
165
|
+
if (finished === 'timeout') c.rec.kill();
|
|
166
|
+
const meta = c.meta;
|
|
167
|
+
meta.ended_at = new Date(now()).toISOString();
|
|
168
|
+
meta.duration_s = Math.round((now() - c.startedMs) / 1000);
|
|
169
|
+
meta.stop_reason = reason;
|
|
170
|
+
meta.status = MeetingStatus.TRANSCRIBING;
|
|
171
|
+
save(meta);
|
|
172
|
+
current = null;
|
|
173
|
+
keepAwake.release();
|
|
174
|
+
say(`⏹ Đã dừng ghi "${meta.title}" (${clock(meta.duration_s)}, ${reason}) — đang làm biên bản…`);
|
|
175
|
+
if (reason !== StopReason.SHUTDOWN) enqueue(meta);
|
|
176
|
+
return { id: meta.id, title: meta.title, status: meta.status, duration_s: meta.duration_s, stop_reason: reason };
|
|
177
|
+
})();
|
|
178
|
+
return c.stopping;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function enqueue(meta) {
|
|
182
|
+
queue = queue.then(() => processMeeting(meta)).catch(() => undefined);
|
|
183
|
+
return queue;
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
async function processMeeting(meta) {
|
|
187
|
+
processing = meta.id;
|
|
188
|
+
try {
|
|
189
|
+
const files = ['system.wav', 'mic.wav'].map((f) => path.join(meta.dir, f));
|
|
190
|
+
const result = await transcribeRecording({
|
|
191
|
+
files,
|
|
192
|
+
labels: [Speaker.OTHERS, Speaker.ME], // thứ tự như files: âm thanh máy, micro
|
|
193
|
+
stt: (wav) => stt(wav, meta.lang),
|
|
194
|
+
onProgress: ({ done, total }) => { meta.progress = { done, total }; if (done % 5 === 0 || done === total) save(meta); },
|
|
195
|
+
});
|
|
196
|
+
fs.writeFileSync(path.join(meta.dir, 'transcript.md'), formatTranscript({
|
|
197
|
+
title: meta.title, startedAt: meta.started_at, seconds: result.seconds || meta.duration_s, segments: result.segments, failed: result.failed,
|
|
198
|
+
screens: meta.screens, lang: meta.lang,
|
|
199
|
+
}));
|
|
200
|
+
meta.segments = result.segments.length;
|
|
201
|
+
meta.failed_parts = result.failed.length;
|
|
202
|
+
if (!meta.keep_audio && result.failed.length === 0) for (const f of files) fs.rmSync(f, { force: true });
|
|
203
|
+
meta.status = MeetingStatus.DONE;
|
|
204
|
+
save(meta);
|
|
205
|
+
say(`📝 Biên bản "${meta.title}" xong — ${result.segments.length} đoạn${result.failed.length ? `, ${result.failed.length} đoạn không chuyển được (giữ tệp âm thanh)` : ''}.`);
|
|
206
|
+
notify({
|
|
207
|
+
title: meta.lang === 'en' ? 'Meeting transcript ready' : 'Biên bản cuộc họp đã xong',
|
|
208
|
+
body: meta.then ? (meta.lang === 'en' ? `"${meta.title}" — Aivin is now doing what you asked.` : `"${meta.title}" — Aivin đang làm việc bạn đã dặn.`) : `"${meta.title}"`,
|
|
209
|
+
});
|
|
210
|
+
if (meta.then) await sendFollowUp(meta);
|
|
211
|
+
} catch (e) {
|
|
212
|
+
meta.status = MeetingStatus.FAILED;
|
|
213
|
+
meta.error = e?.message || String(e);
|
|
214
|
+
save(meta);
|
|
215
|
+
say(`❌ Không làm được biên bản "${meta.title}": ${meta.error} (tệp âm thanh vẫn giữ trong ${meta.dir})`);
|
|
216
|
+
} finally {
|
|
217
|
+
processing = null;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
/** Lượt chat sau họp — BE bận / máy mất mạng thì thử lại mỗi phút (tối đa nửa giờ). Công tắc ngắt đang bật → không gửi. */
|
|
222
|
+
async function sendFollowUp(meta) {
|
|
223
|
+
for (let i = 0; i < FOLLOW_UP_TRIES; i++) {
|
|
224
|
+
if (isPaused()) { meta.follow_up = 'skipped_paused'; save(meta); return; }
|
|
225
|
+
let res;
|
|
226
|
+
try { res = await followUp(followUpText(meta)); } catch (e) { res = { ok: false, error: e?.message || String(e) }; }
|
|
227
|
+
if (res?.ok) { meta.follow_up = 'sent'; save(meta); return; }
|
|
228
|
+
if (res?.error && !['busy', 'offline'].includes(res.error)) { meta.follow_up = `failed: ${res.error}`; save(meta); return; }
|
|
229
|
+
await new Promise((r) => setTimeout(r, FOLLOW_UP_RETRY_MS));
|
|
230
|
+
}
|
|
231
|
+
meta.follow_up = 'failed: gave up';
|
|
232
|
+
save(meta);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
/** Daemon vừa chạy: buổi ghi dở (daemon chết giữa chừng) / biên bản dở → làm nốt. */
|
|
236
|
+
function recover() {
|
|
237
|
+
for (const entry of readIndex().slice(0, 20)) {
|
|
238
|
+
const meta = load(entry.dir);
|
|
239
|
+
if (!meta || (meta.status !== MeetingStatus.RECORDING && meta.status !== MeetingStatus.TRANSCRIBING)) continue;
|
|
240
|
+
if (meta.status === MeetingStatus.RECORDING) {
|
|
241
|
+
let mtime = Date.parse(meta.started_at);
|
|
242
|
+
for (const f of ['system.wav', 'mic.wav']) { try { mtime = Math.max(mtime, fs.statSync(path.join(meta.dir, f)).mtimeMs); } catch { /* không có */ } }
|
|
243
|
+
meta.ended_at = new Date(mtime).toISOString();
|
|
244
|
+
meta.duration_s = Math.round((mtime - Date.parse(meta.started_at)) / 1000);
|
|
245
|
+
meta.stop_reason = meta.stop_reason || StopReason.RECORDER_EXITED;
|
|
246
|
+
meta.status = MeetingStatus.TRANSCRIBING;
|
|
247
|
+
save(meta);
|
|
248
|
+
}
|
|
249
|
+
say(`📝 Làm nốt biên bản "${meta.title}" (dở từ lần chạy trước)…`);
|
|
250
|
+
enqueue(meta);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
function status() {
|
|
255
|
+
const c = current;
|
|
256
|
+
return {
|
|
257
|
+
recording: c ? {
|
|
258
|
+
id: c.meta.id, title: c.meta.title, elapsed_s: Math.round((now() - c.startedMs) / 1000), sources: c.meta.sources, level: c.level || null,
|
|
259
|
+
screens: c.meta.screens.length, meeting_window: c.windowTitle || null, then: c.meta.then,
|
|
260
|
+
} : null,
|
|
261
|
+
transcribing: processing ? (() => { try { const m = find(processing); return { id: m.id, title: m.title, progress: m.progress }; } catch { return { id: processing }; } })() : null,
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
function list({ limit = 20 } = {}) {
|
|
266
|
+
return readIndex().slice(0, Math.min(Number(limit) || 20, MAX_INDEX)).map((e) => load(e.dir)).filter(Boolean).map((m) => ({
|
|
267
|
+
id: m.id, title: m.title, status: m.status, started_at: m.started_at, duration_s: m.duration_s, stop_reason: m.stop_reason,
|
|
268
|
+
screens: m.screens?.length || 0, follow_up: m.follow_up, ...(m.dir.startsWith(baseDir) ? {} : { dir: m.dir }),
|
|
269
|
+
}));
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function transcript({ id, offset = 0, max_chars = TRANSCRIPT_PAGE } = {}) {
|
|
273
|
+
const meta = find(id);
|
|
274
|
+
const base = { id: meta.id, title: meta.title, status: meta.status, started_at: meta.started_at, duration_s: meta.duration_s };
|
|
275
|
+
if (meta.status === MeetingStatus.RECORDING) return { ...base, text: null, note: 'Still recording — the transcript is made after the meeting ends.' };
|
|
276
|
+
if (meta.status === MeetingStatus.TRANSCRIBING) return { ...base, text: null, progress: meta.progress, note: 'Still transcribing — try again in a minute.' };
|
|
277
|
+
let text;
|
|
278
|
+
try { text = fs.readFileSync(path.join(meta.dir, 'transcript.md'), 'utf8'); } catch { throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, meta.error ? `Transcript failed: ${meta.error}` : 'Transcript file is missing'); }
|
|
279
|
+
const from = Math.max(0, Number(offset) || 0);
|
|
280
|
+
const size = Math.min(Math.max(1000, Number(max_chars) || TRANSCRIPT_PAGE), 100_000);
|
|
281
|
+
const page = text.slice(from, from + size);
|
|
282
|
+
return {
|
|
283
|
+
...base, text: page, total_chars: text.length, ...(from + size < text.length ? { next_offset: from + size } : {}),
|
|
284
|
+
screens: (meta.screens || []).map((s) => ({ file: s.file, at: clock(s.secs) })),
|
|
285
|
+
...(meta.dir.startsWith(baseDir) ? {} : { file: path.join(meta.dir, 'transcript.md') }),
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
function screenshot({ id, file } = {}) {
|
|
290
|
+
const meta = find(id);
|
|
291
|
+
const name = String(file || '');
|
|
292
|
+
if (!(meta.screens || []).some((s) => s.file === name)) throw new DeviceToolError(DeviceErrorCode.NOT_FOUND, `No screenshot ${name} in this meeting`);
|
|
293
|
+
const buf = fs.readFileSync(path.join(meta.dir, 'screens', name));
|
|
294
|
+
return { id: meta.id, file: name, image: { mime: 'image/jpeg', base64: buf.toString('base64') } };
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** Daemon dừng: đóng tệp ghi cho đúng; biên bản làm ở lần chạy sau (recover). */
|
|
298
|
+
async function shutdown() {
|
|
299
|
+
if (current) await stop({ reason: StopReason.SHUTDOWN }).catch(() => undefined);
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
return {
|
|
303
|
+
start, stop, status, list, transcript, screenshot, recover, shutdown,
|
|
304
|
+
busy: () => !!current || !!processing,
|
|
305
|
+
/** Chờ hết việc chuyển chữ đang xếp hàng (test). */
|
|
306
|
+
idle: () => queue,
|
|
307
|
+
};
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
const str = (description) => ({ type: 'string', description });
|
|
311
|
+
const num = (description) => ({ type: 'number', description });
|
|
312
|
+
const bool = (description) => ({ type: 'boolean', description });
|
|
313
|
+
const schema = (properties, required = []) => ({ type: 'object', properties, required });
|
|
314
|
+
|
|
315
|
+
/** Công cụ ghi chú cuộc họp + chụp màn hình cho danh mục của Planner. */
|
|
316
|
+
export function buildMeetingTools({ meetings, media }) {
|
|
317
|
+
const tools = [];
|
|
318
|
+
if (meetings) {
|
|
319
|
+
tools.push(
|
|
320
|
+
{ name: 'meeting.start', group: ToolGroup.MEDIA,
|
|
321
|
+
handler: (a) => meetings.start({ ...a, by: 'ai' }),
|
|
322
|
+
description: 'Take notes of a meeting the user is in on this computer (Google Meet, Zoom, Teams, Zalo… any app; nobody joins the meeting): records what the others say (the computer\'s sound) and the user\'s microphone, plus a screenshot whenever the screen changes (shared slides). Recording ends by itself when the meeting window closes, after a long silence or at max_minutes (or with meeting.stop); the transcript is made afterwards. Give "then" for what to do when it is ready (e.g. "summarize the decisions and action items and draft an email to my manager anh.nguyen@x.com") — a new chat turn starts with it automatically. The person at this computer must approve; tell them to let the participants know they are recorded.',
|
|
323
|
+
input_schema: schema({
|
|
324
|
+
title: str('meeting name, e.g. "Weekly sales review"'), then: str('what to do with the transcript when the meeting is over'),
|
|
325
|
+
lang: str('vi | en — language spoken (default the mascot language)'), screens: bool('save screenshots when the screen changes (default true)'),
|
|
326
|
+
max_minutes: num('stop after this long, default 180, max 480'), silence_minutes: num('stop after this long without any sound, default 10'),
|
|
327
|
+
save_dir: str('also keep the transcript + screenshots in this folder (inside the allowed area) so they can be attached to an email'),
|
|
328
|
+
keep_audio: bool('keep the audio files after transcribing (default: deleted)'),
|
|
329
|
+
}) },
|
|
330
|
+
{ name: 'meeting.stop', group: ToolGroup.MEDIA,
|
|
331
|
+
handler: (a) => meetings.stop({ id: a.id }),
|
|
332
|
+
description: 'Stop the meeting recording now; the transcript is then made (and the "then" instruction runs when it is ready).',
|
|
333
|
+
input_schema: schema({ id: str('meeting id (default the one recording)') }) },
|
|
334
|
+
{ name: 'meeting.status', group: ToolGroup.MEDIA, read_only: true, handler: () => meetings.status(),
|
|
335
|
+
description: 'Whether a meeting is being recorded (elapsed time, sound levels, screenshots so far) and transcription progress.', input_schema: schema({}) },
|
|
336
|
+
{ name: 'meeting.list', group: ToolGroup.MEDIA, read_only: true, handler: (a) => ({ meetings: meetings.list(a) }),
|
|
337
|
+
description: 'Meetings recorded on this computer, newest first: id, title, when, duration, status.', input_schema: schema({ limit: num('default 20') }) },
|
|
338
|
+
{ name: 'meeting.transcript', group: ToolGroup.MEDIA, read_only: true, handler: (a) => meetings.transcript(a),
|
|
339
|
+
description: 'Read the transcript of a recorded meeting (timestamped; screenshots are marked where they were taken). Long transcripts come in pages: pass next_offset.',
|
|
340
|
+
input_schema: schema({ id: str('meeting id (default the latest)'), offset: num('character offset from next_offset'), max_chars: num('default 30000') }) },
|
|
341
|
+
{ name: 'meeting.screenshot', group: ToolGroup.MEDIA, read_only: true, handler: (a) => meetings.screenshot(a),
|
|
342
|
+
description: 'View one screenshot taken during a meeting (file name from meeting.transcript).',
|
|
343
|
+
input_schema: schema({ id: str('meeting id'), file: str('screenshot file, e.g. "00-12-30.jpg"') }, ['file']) },
|
|
344
|
+
);
|
|
345
|
+
}
|
|
346
|
+
if (media) {
|
|
347
|
+
tools.push({ name: 'screen.capture', group: ToolGroup.MEDIA, read_only: true,
|
|
348
|
+
handler: (a, c) => media.snap({ monitor: Number.isInteger(a.monitor) ? a.monitor : -1, max_width: Number(a.max_width) || 1600 }, c?.signal),
|
|
349
|
+
description: 'Screenshot of the whole screen (all monitors side by side) or one monitor; also lists the monitors. The Aivin mascot is never in it.',
|
|
350
|
+
input_schema: schema({ monitor: num('monitor index from a previous call; default all'), max_width: num('default 1600, max 3840') }) });
|
|
351
|
+
}
|
|
352
|
+
return tools;
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
// ── `aivin remote meeting start|stop` → daemon đang chạy: tệp yêu cầu trong `meetings/requests/` (như công tắc ngắt — lệnh cục bộ, người
|
|
356
|
+
// ngồi trước máy, nên bắt đầu ghi từ đây không cần hộp xác nhận). ───────────────────────────────────────────────────────────────────────
|
|
357
|
+
|
|
358
|
+
const REQUEST_POLL_MS = 1500;
|
|
359
|
+
const REQUEST_WAIT_MS = 30_000;
|
|
360
|
+
const requestsDir = (baseDir) => path.join(baseDir, 'requests');
|
|
361
|
+
|
|
362
|
+
/** Daemon: đọc yêu cầu, làm, ghi kết quả `<id>.res.json`. Trả hàm dừng. */
|
|
363
|
+
export function watchMeetingRequests(meetings, { baseDir = MEETINGS_DIR, pollMs = REQUEST_POLL_MS } = {}) {
|
|
364
|
+
const dir = requestsDir(baseDir);
|
|
365
|
+
let busy = false;
|
|
366
|
+
const timer = setInterval(async () => {
|
|
367
|
+
if (busy) return;
|
|
368
|
+
busy = true;
|
|
369
|
+
try {
|
|
370
|
+
let names = [];
|
|
371
|
+
try { names = fs.readdirSync(dir).filter((n) => n.endsWith('.req.json')); } catch { return; }
|
|
372
|
+
for (const name of names) {
|
|
373
|
+
const file = path.join(dir, name);
|
|
374
|
+
let req;
|
|
375
|
+
try { req = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { req = null; }
|
|
376
|
+
fs.rmSync(file, { force: true });
|
|
377
|
+
if (!req) continue;
|
|
378
|
+
let res;
|
|
379
|
+
try {
|
|
380
|
+
if (req.action === 'start') res = { ok: true, result: await meetings.start({ ...req.args, by: 'user' }) };
|
|
381
|
+
else if (req.action === 'stop') res = { ok: true, result: await meetings.stop({ id: req.args?.id }) };
|
|
382
|
+
else res = { ok: false, error: `Unknown action ${req.action}` };
|
|
383
|
+
} catch (e) {
|
|
384
|
+
res = { ok: false, error: e?.message || String(e) };
|
|
385
|
+
}
|
|
386
|
+
fs.writeFileSync(path.join(dir, name.replace('.req.json', '.res.json')), JSON.stringify(res));
|
|
387
|
+
}
|
|
388
|
+
} finally {
|
|
389
|
+
busy = false;
|
|
390
|
+
}
|
|
391
|
+
}, pollMs);
|
|
392
|
+
timer.unref?.();
|
|
393
|
+
return () => clearInterval(timer);
|
|
394
|
+
}
|
|
395
|
+
|
|
396
|
+
/** CLI: gửi yêu cầu cho daemon, chờ kết quả. Daemon không chạy → lỗi rõ. */
|
|
397
|
+
export async function requestMeeting(action, args = {}, { baseDir = MEETINGS_DIR, waitMs = REQUEST_WAIT_MS } = {}) {
|
|
398
|
+
const dir = requestsDir(baseDir);
|
|
399
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
400
|
+
const id = randomUUID();
|
|
401
|
+
const reqFile = path.join(dir, `${id}.req.json`);
|
|
402
|
+
const resFile = path.join(dir, `${id}.res.json`);
|
|
403
|
+
fs.writeFileSync(reqFile, JSON.stringify({ action, args, at: new Date().toISOString() }));
|
|
404
|
+
const deadline = Date.now() + waitMs;
|
|
405
|
+
while (Date.now() < deadline) {
|
|
406
|
+
await new Promise((r) => setTimeout(r, 300));
|
|
407
|
+
if (!fs.existsSync(resFile)) continue;
|
|
408
|
+
const res = JSON.parse(fs.readFileSync(resFile, 'utf8'));
|
|
409
|
+
fs.rmSync(resFile, { force: true });
|
|
410
|
+
if (!res.ok) throw new Error(res.error);
|
|
411
|
+
return res.result;
|
|
412
|
+
}
|
|
413
|
+
fs.rmSync(reqFile, { force: true });
|
|
414
|
+
throw new Error('The Aivin device agent is not running on this computer — start it with `aivin remote start`, then try again.');
|
|
415
|
+
}
|
|
@@ -0,0 +1,109 @@
|
|
|
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 { DeviceErrorCode, REMOTE_CONFIG_DIR } from '../constants.mjs';
|
|
7
|
+
import { DeviceToolError } from '../sandbox.mjs';
|
|
8
|
+
import { MEDIA_HOST_CSHARP, MEDIA_HOST_PS1 } from './recorderSource.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Chạy tiến trình ghi / chụp của recorderSource.mjs. Lần đầu PowerShell dịch C# (~vài giây) rồi lưu DLL theo dấu vân tay mã vào
|
|
12
|
+
* `~/.aivin/media/`, các lần sau nạp DLL. `record()` — một tiến trình sống suốt buổi ghi; `snap()` — một tiến trình ngắn mỗi ảnh.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
const MEDIA_DIR = path.join(REMOTE_CONFIG_DIR, 'media');
|
|
16
|
+
const READY_TIMEOUT_MS = 60_000;
|
|
17
|
+
const SNAP_TIMEOUT_MS = 30_000;
|
|
18
|
+
|
|
19
|
+
function hostFiles(dir = MEDIA_DIR) {
|
|
20
|
+
const hash = createHash('sha256').update(MEDIA_HOST_CSHARP).update(MEDIA_HOST_PS1).digest('hex').slice(0, 16);
|
|
21
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
22
|
+
const src = path.join(dir, `media-${hash}.cs`);
|
|
23
|
+
const ps1 = path.join(dir, `media-${hash}.ps1`);
|
|
24
|
+
if (!fs.existsSync(src)) fs.writeFileSync(src, MEDIA_HOST_CSHARP);
|
|
25
|
+
if (!fs.existsSync(ps1)) fs.writeFileSync(ps1, MEDIA_HOST_PS1);
|
|
26
|
+
for (const name of fs.readdirSync(dir)) {
|
|
27
|
+
if (name.startsWith('media-') && !name.startsWith(`media-${hash}`)) fs.rmSync(path.join(dir, name), { force: true });
|
|
28
|
+
}
|
|
29
|
+
return { src, ps1, dll: path.join(dir, `media-${hash}.dll`) };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
export function mediaSupported(platform = process.platform) {
|
|
33
|
+
return platform === 'win32';
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
export function createMediaHost({ spawnImpl = spawn, dir = MEDIA_DIR } = {}) {
|
|
37
|
+
const launch = (mode, args) => {
|
|
38
|
+
const files = hostFiles(dir);
|
|
39
|
+
return spawnImpl('powershell.exe', ['-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-File', files.ps1], {
|
|
40
|
+
env: { ...process.env, AIVIN_MEDIA_SRC: files.src, AIVIN_MEDIA_DLL: files.dll, AIVIN_MEDIA_MODE: mode, AIVIN_MEDIA_ARGS: JSON.stringify(args) },
|
|
41
|
+
windowsHide: true,
|
|
42
|
+
});
|
|
43
|
+
};
|
|
44
|
+
|
|
45
|
+
/** Một ảnh màn hình (`monitor` -1 = tất cả màn hình ghép lại). */
|
|
46
|
+
function snap(args = {}, signal) {
|
|
47
|
+
return new Promise((resolve, reject) => {
|
|
48
|
+
const child = launch('snap', { monitor: Number.isInteger(args.monitor) ? args.monitor : -1, max_width: args.max_width || 1600, quality: args.quality || 70 });
|
|
49
|
+
let stderr = '';
|
|
50
|
+
let result = null;
|
|
51
|
+
const timer = setTimeout(() => { child.kill(); reject(new DeviceToolError(DeviceErrorCode.CALL_TIMEOUT, 'Screen capture timed out')); }, SNAP_TIMEOUT_MS);
|
|
52
|
+
const onAbort = () => { child.kill(); reject(new DeviceToolError(DeviceErrorCode.CANCELLED, 'Cancelled')); };
|
|
53
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
54
|
+
child.stderr.on('data', (d) => { stderr = (stderr + d).slice(-2000); });
|
|
55
|
+
readline.createInterface({ input: child.stdout }).on('line', (line) => {
|
|
56
|
+
try { const msg = JSON.parse(line); if (msg.t === 'snap' || msg.t === 'error') result = msg; } catch { /* dòng rác của PowerShell */ }
|
|
57
|
+
});
|
|
58
|
+
child.on('error', (e) => { clearTimeout(timer); reject(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `Cannot start the capture helper: ${e.message}`)); });
|
|
59
|
+
child.on('close', () => {
|
|
60
|
+
clearTimeout(timer);
|
|
61
|
+
signal?.removeEventListener('abort', onAbort);
|
|
62
|
+
if (result?.t === 'snap') resolve({ image: result.image, monitors: result.monitors });
|
|
63
|
+
else reject(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, result?.error || stderr.trim().split(/\r?\n/).slice(-2).join(' ') || 'Screen capture failed'));
|
|
64
|
+
});
|
|
65
|
+
});
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Bắt đầu ghi vào `dir` → `{ ready, done, stop(), on(type, fn) }`. `ready` xong khi đã mở được ít nhất một luồng âm thanh
|
|
70
|
+
* (`{ system, mic }` cho biết luồng nào); `done` → `{ secs, system, mic, screens }`. Sự kiện: level / windows / screen / warn.
|
|
71
|
+
*/
|
|
72
|
+
function record({ dir: outDir, screens = true, screensEverySec = 15, maxScreens = 300 }) {
|
|
73
|
+
const listeners = new Map();
|
|
74
|
+
const emit = (type, msg) => { for (const fn of listeners.get(type) || []) { try { fn(msg); } catch { /* người nghe lỗi không làm hỏng buổi ghi */ } } };
|
|
75
|
+
const child = launch('record', { dir: outDir, screens, screens_every_sec: screensEverySec, max_screens: maxScreens });
|
|
76
|
+
let stderr = '';
|
|
77
|
+
let finished = null;
|
|
78
|
+
let resolveReady;
|
|
79
|
+
let rejectReady;
|
|
80
|
+
const ready = new Promise((res, rej) => { resolveReady = res; rejectReady = rej; });
|
|
81
|
+
const readyTimer = setTimeout(() => { rejectReady(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, 'The recorder did not start in time')); child.kill(); }, READY_TIMEOUT_MS);
|
|
82
|
+
child.stderr.on('data', (d) => { stderr = (stderr + d).slice(-4000); });
|
|
83
|
+
readline.createInterface({ input: child.stdout }).on('line', (line) => {
|
|
84
|
+
let msg;
|
|
85
|
+
try { msg = JSON.parse(line); } catch { return; }
|
|
86
|
+
if (msg.t === 'ready') { clearTimeout(readyTimer); resolveReady({ system: !!msg.system, mic: !!msg.mic }); return; }
|
|
87
|
+
if (msg.t === 'done') { finished = msg; return; }
|
|
88
|
+
if (msg.t === 'error') { clearTimeout(readyTimer); rejectReady(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, msg.error || 'Recording failed')); }
|
|
89
|
+
emit(msg.t, msg);
|
|
90
|
+
});
|
|
91
|
+
const done = new Promise((resolve) => {
|
|
92
|
+
child.on('error', (e) => { clearTimeout(readyTimer); rejectReady(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `Cannot start the recorder: ${e.message}`)); resolve(null); });
|
|
93
|
+
child.on('close', () => {
|
|
94
|
+
clearTimeout(readyTimer);
|
|
95
|
+
rejectReady(new DeviceToolError(DeviceErrorCode.EXECUTION_FAILED, `The recorder exited${stderr ? `: ${stderr.trim().split(/\r?\n/).slice(-2).join(' ')}` : ''}`));
|
|
96
|
+
resolve(finished);
|
|
97
|
+
});
|
|
98
|
+
});
|
|
99
|
+
return {
|
|
100
|
+
ready,
|
|
101
|
+
done,
|
|
102
|
+
stop() { try { child.stdin.write('stop\n'); child.stdin.end(); } catch { /* đã thoát */ } },
|
|
103
|
+
kill() { try { child.kill(); } catch { /* đã thoát */ } },
|
|
104
|
+
on(type, fn) { if (!listeners.has(type)) listeners.set(type, []); listeners.get(type).push(fn); },
|
|
105
|
+
};
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
return { snap, record };
|
|
109
|
+
}
|