@aivin-labs/cli 1.0.5 → 1.0.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +288 -216
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +551 -5
  4. package/bin/lib/browserAutomation.mjs +384 -614
  5. package/bin/lib/browserTui.mjs +276 -251
  6. package/bin/lib/cancellation.mjs +61 -0
  7. package/bin/lib/localBrowser.mjs +345 -0
  8. package/bin/lib/mcpProxy.mjs +869 -837
  9. package/bin/lib/missionStream.mjs +696 -691
  10. package/bin/lib/releaseKeys.mjs +9 -0
  11. package/bin/lib/remote/activityLog.mjs +68 -0
  12. package/bin/lib/remote/autoStart.mjs +617 -0
  13. package/bin/lib/remote/autoUpdate.mjs +129 -0
  14. package/bin/lib/remote/brand.mjs +60 -0
  15. package/bin/lib/remote/browserTunnel.mjs +403 -0
  16. package/bin/lib/remote/callLedger.mjs +134 -0
  17. package/bin/lib/remote/cdpPolicy.mjs +79 -0
  18. package/bin/lib/remote/client.mjs +808 -0
  19. package/bin/lib/remote/clipboard.mjs +138 -0
  20. package/bin/lib/remote/codingAgents.mjs +293 -0
  21. package/bin/lib/remote/constants.mjs +234 -0
  22. package/bin/lib/remote/credentials.mjs +208 -0
  23. package/bin/lib/remote/daemonLock.mjs +86 -0
  24. package/bin/lib/remote/dailyBrowser.mjs +371 -0
  25. package/bin/lib/remote/desktop/index.mjs +272 -0
  26. package/bin/lib/remote/desktop/linux.mjs +144 -0
  27. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  28. package/bin/lib/remote/desktop/mac.mjs +187 -0
  29. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  30. package/bin/lib/remote/desktop/strings.mjs +74 -0
  31. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  32. package/bin/lib/remote/deviceMemory.mjs +246 -0
  33. package/bin/lib/remote/deviceProfile.mjs +142 -0
  34. package/bin/lib/remote/deviceWatches.mjs +138 -0
  35. package/bin/lib/remote/docText.mjs +117 -0
  36. package/bin/lib/remote/fileIndexer.mjs +399 -0
  37. package/bin/lib/remote/gui/index.mjs +326 -0
  38. package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
  39. package/bin/lib/remote/gui/windowsHost.mjs +109 -0
  40. package/bin/lib/remote/gui/windowsHostSource.mjs +1156 -0
  41. package/bin/lib/remote/httpTransfer.mjs +89 -0
  42. package/bin/lib/remote/idempotency.mjs +135 -0
  43. package/bin/lib/remote/keepAwake.mjs +100 -0
  44. package/bin/lib/remote/localConfirm.mjs +268 -0
  45. package/bin/lib/remote/localPolicy.mjs +256 -0
  46. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  47. package/bin/lib/remote/mascot/ask.mjs +768 -0
  48. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  49. package/bin/lib/remote/mascot/assets.mjs +827 -0
  50. package/bin/lib/remote/mascot/bot.mjs +372 -0
  51. package/bin/lib/remote/mascot/hostSource.mjs +759 -0
  52. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  53. package/bin/lib/remote/mascot/index.mjs +493 -0
  54. package/bin/lib/remote/mascot/labels.mjs +82 -0
  55. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  56. package/bin/lib/remote/mascot/strings.mjs +375 -0
  57. package/bin/lib/remote/mascot/ui.mjs +104 -0
  58. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  59. package/bin/lib/remote/meeting/index.mjs +415 -0
  60. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  61. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  62. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  63. package/bin/lib/remote/memberFsPool.mjs +134 -0
  64. package/bin/lib/remote/memberFsWorker.mjs +60 -0
  65. package/bin/lib/remote/mission.mjs +156 -0
  66. package/bin/lib/remote/missionQuestion.mjs +63 -0
  67. package/bin/lib/remote/multiUser.mjs +344 -0
  68. package/bin/lib/remote/netProxy.mjs +145 -0
  69. package/bin/lib/remote/notify.mjs +58 -0
  70. package/bin/lib/remote/office/index.mjs +90 -0
  71. package/bin/lib/remote/policyCommand.mjs +93 -0
  72. package/bin/lib/remote/processes.mjs +217 -0
  73. package/bin/lib/remote/sandbox.mjs +221 -0
  74. package/bin/lib/remote/schedule.mjs +213 -0
  75. package/bin/lib/remote/scheduler.mjs +124 -0
  76. package/bin/lib/remote/tabGroups.mjs +209 -0
  77. package/bin/lib/remote/textIndex.mjs +131 -0
  78. package/bin/lib/remote/tokenStore.mjs +77 -0
  79. package/bin/lib/remote/toolHandlers.mjs +741 -0
  80. package/bin/lib/remote/undoStore.mjs +242 -0
  81. package/bin/lib/remoteControl.mjs +26 -0
  82. package/bin/lib/scaffold.mjs +654 -653
  83. package/bin/lib/selfUpdate.mjs +71 -0
  84. package/bin/lib/update/binarySwap.mjs +63 -0
  85. package/bin/lib/update/constants.mjs +56 -0
  86. package/bin/lib/update/download.mjs +145 -0
  87. package/bin/lib/update/signature.mjs +42 -0
  88. package/bin/lib/update/state.mjs +205 -0
  89. package/bin/lib/update/versions.mjs +60 -0
  90. package/docs/AIVIN_MASCOT.md +116 -0
  91. package/docs/CLI.md +1484 -1299
  92. package/docs/media/aivin-mascot-states.mp4 +0 -0
  93. package/package.json +71 -62
@@ -0,0 +1,394 @@
1
+ /**
2
+ * Tiến trình ghi họp + chụp màn hình trên Windows (29/10/2026) — PowerShell dịch mã C# dưới đây một lần (lưu DLL theo dấu vân tay, như gui/),
3
+ * chạy riêng một tiến trình cho mỗi buổi ghi (không chung host tuần tự của gui/: ghi kéo dài hàng giờ).
4
+ *
5
+ * - Ghi: WASAPI dùng chung (shared mode, thăm dò mỗi 10 ms) trên thiết bị LIÊN LẠC mặc định (`eCommunications` — app họp phát / thu ở đây):
6
+ * loopback của loa = tiếng người khác trong cuộc họp, và micro = tiếng chủ máy. Mỗi luồng đổi về 16 kHz mono 16-bit, ghi ra `system.wav` /
7
+ * `mic.wav`. Loopback không có gói nào khi máy im → chèn im lặng theo đồng hồ để hai tệp luôn khớp thời gian.
8
+ * - Mỗi giây báo mức âm (RMS) của hai luồng; mỗi 10 s báo tiêu đề cửa sổ đang mở (biết khi nào cửa sổ họp đóng); khi màn hình đổi rõ (so ảnh
9
+ * thu nhỏ) thì lưu một ảnh JPEG (slide đang chia sẻ) vào `screens/`. Linh vật tự ẩn khỏi ảnh chụp (WDA_EXCLUDEFROMCAPTURE).
10
+ * - Dừng: dòng `stop` ở stdin, hoặc stdin đóng (daemon thoát) → đóng tệp WAV cho đúng rồi thoát.
11
+ * - Chế độ `snap`: chụp một màn hình (hoặc tất cả) một lần → JSON `{ image: { mime, base64, width, height }, monitors }`.
12
+ *
13
+ * PowerShell 5.1 dịch bằng C# 5: không `$""`, `?.`, `out var`, thân hàm dạng `=>`.
14
+ */
15
+
16
+ export const MEDIA_HOST_CSHARP = String.raw`
17
+ using System;
18
+ using System.Collections.Generic;
19
+ using System.Drawing;
20
+ using System.Drawing.Imaging;
21
+ using System.IO;
22
+ using System.Runtime.InteropServices;
23
+ using System.Text;
24
+ using System.Threading;
25
+ using System.Web.Script.Serialization;
26
+ using System.Windows.Forms;
27
+
28
+ namespace AivinMedia {
29
+ [ComImport, Guid("BCDE0395-E52F-467C-8E3D-C4579291692E")] class MMDeviceEnumeratorCom {}
30
+
31
+ [ComImport, Guid("A95664D2-9614-4F35-A746-DE8DB63617E6"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
32
+ interface IMMDeviceEnumerator {
33
+ [PreserveSig] int EnumAudioEndpoints(int dataFlow, int stateMask, out IntPtr devices);
34
+ [PreserveSig] int GetDefaultAudioEndpoint(int dataFlow, int role, out IMMDevice endpoint);
35
+ }
36
+
37
+ [ComImport, Guid("D666063F-1587-4E43-81F1-B948E807363F"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
38
+ interface IMMDevice {
39
+ [PreserveSig] int Activate(ref Guid iid, int clsCtx, IntPtr activationParams, [MarshalAs(UnmanagedType.IUnknown)] out object iface);
40
+ }
41
+
42
+ [ComImport, Guid("1CB9AD4C-DBFA-4c32-B178-C2F568A703B2"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
43
+ interface IAudioClient {
44
+ [PreserveSig] int Initialize(int shareMode, int streamFlags, long bufferDuration, long periodicity, IntPtr format, IntPtr sessionGuid);
45
+ [PreserveSig] int GetBufferSize(out uint frames);
46
+ [PreserveSig] int GetStreamLatency(out long latency);
47
+ [PreserveSig] int GetCurrentPadding(out uint padding);
48
+ [PreserveSig] int IsFormatSupported(int shareMode, IntPtr format, out IntPtr closest);
49
+ [PreserveSig] int GetMixFormat(out IntPtr format);
50
+ [PreserveSig] int GetDevicePeriod(out long defaultPeriod, out long minPeriod);
51
+ [PreserveSig] int Start();
52
+ [PreserveSig] int Stop();
53
+ [PreserveSig] int Reset();
54
+ [PreserveSig] int SetEventHandle(IntPtr handle);
55
+ [PreserveSig] int GetService(ref Guid iid, [MarshalAs(UnmanagedType.IUnknown)] out object service);
56
+ }
57
+
58
+ [ComImport, Guid("C8ADBD64-E71E-48a0-A4DE-185C395CD317"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)]
59
+ interface IAudioCaptureClient {
60
+ [PreserveSig] int GetBuffer(out IntPtr data, out uint frames, out int flags, out long devicePosition, out long qpcPosition);
61
+ [PreserveSig] int ReleaseBuffer(uint frames);
62
+ [PreserveSig] int GetNextPacketSize(out uint frames);
63
+ }
64
+
65
+ static class Native {
66
+ [DllImport("user32.dll")] public static extern bool SetProcessDPIAware();
67
+ public delegate bool EnumProc(IntPtr h, IntPtr l);
68
+ [DllImport("user32.dll")] public static extern bool EnumWindows(EnumProc cb, IntPtr l);
69
+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);
70
+ [DllImport("user32.dll", CharSet = CharSet.Unicode)] public static extern int GetWindowText(IntPtr h, StringBuilder s, int max);
71
+ [DllImport("ole32.dll")] public static extern void CoTaskMemFree(IntPtr p);
72
+ }
73
+
74
+ static class Out {
75
+ static readonly object gate = new object();
76
+ static readonly JavaScriptSerializer json = new JavaScriptSerializer { MaxJsonLength = int.MaxValue };
77
+ public static void Send(Dictionary<string, object> msg) {
78
+ string line = json.Serialize(msg);
79
+ lock (gate) { Console.Out.WriteLine(line); Console.Out.Flush(); }
80
+ }
81
+ public static Dictionary<string, object> Parse(string text) {
82
+ if (string.IsNullOrEmpty(text)) return new Dictionary<string, object>();
83
+ return json.Deserialize<Dictionary<string, object>>(text);
84
+ }
85
+ public static Dictionary<string, object> Msg(string t) { var d = new Dictionary<string, object>(); d["t"] = t; return d; }
86
+ }
87
+
88
+ /** WAV 16 kHz mono 16-bit, kích thước ghi lại khi đóng. */
89
+ class WavWriter {
90
+ public const int Rate = 16000;
91
+ readonly FileStream fs;
92
+ long samples;
93
+ public WavWriter(string path) {
94
+ fs = new FileStream(path, FileMode.Create, FileAccess.Write, FileShare.Read);
95
+ fs.Write(new byte[44], 0, 44);
96
+ }
97
+ public long Samples { get { return samples; } }
98
+ public void Write(short[] buf, int count) {
99
+ var bytes = new byte[count * 2];
100
+ Buffer.BlockCopy(buf, 0, bytes, 0, count * 2);
101
+ fs.Write(bytes, 0, bytes.Length);
102
+ samples += count;
103
+ }
104
+ public void WriteSilence(long count) {
105
+ var zero = new byte[3200];
106
+ while (count > 0) { int n = (int)Math.Min(count, 1600); fs.Write(zero, 0, n * 2); samples += n; count -= n; }
107
+ }
108
+ public void Close() {
109
+ long data = samples * 2;
110
+ fs.Seek(0, SeekOrigin.Begin);
111
+ var w = new BinaryWriter(fs);
112
+ w.Write(Encoding.ASCII.GetBytes("RIFF")); w.Write((uint)(36 + data)); w.Write(Encoding.ASCII.GetBytes("WAVE"));
113
+ w.Write(Encoding.ASCII.GetBytes("fmt ")); w.Write(16); w.Write((short)1); w.Write((short)1); w.Write(Rate); w.Write(Rate * 2); w.Write((short)2); w.Write((short)16);
114
+ w.Write(Encoding.ASCII.GetBytes("data")); w.Write((uint)data);
115
+ w.Flush(); fs.Flush(); fs.Close();
116
+ }
117
+ }
118
+
119
+ /** Một luồng WASAPI (loopback của loa hoặc micro) → WAV 16 kHz mono. */
120
+ class AudioStream {
121
+ public readonly string Name;
122
+ readonly IAudioClient client;
123
+ readonly IAudioCaptureClient capture;
124
+ readonly WavWriter wav;
125
+ readonly int channels, bits; readonly bool isFloat; readonly double step;
126
+ double acc, sum; int n;
127
+ short[] outBuf = new short[16000];
128
+ byte[] raw = new byte[0];
129
+ double levelSum; long levelCount;
130
+
131
+ AudioStream(string name, IAudioClient c, IAudioCaptureClient cap, WavWriter w, int ch, int rate, int b, bool f) {
132
+ Name = name; client = c; capture = cap; wav = w; channels = ch; bits = b; isFloat = f; step = (double)WavWriter.Rate / rate;
133
+ }
134
+
135
+ public static AudioStream Open(string name, bool loopback, string path) {
136
+ var en = (IMMDeviceEnumerator)new MMDeviceEnumeratorCom();
137
+ IMMDevice dev;
138
+ // eCommunications (app họp dùng), không có thì eConsole.
139
+ if (en.GetDefaultAudioEndpoint(loopback ? 0 : 1, 2, out dev) != 0 && en.GetDefaultAudioEndpoint(loopback ? 0 : 1, 0, out dev) != 0) throw new Exception("no " + name + " device");
140
+ Guid iid = typeof(IAudioClient).GUID;
141
+ object o;
142
+ Check(dev.Activate(ref iid, 1 | 2 | 4 | 0x10, IntPtr.Zero, out o), "activate");
143
+ var client = (IAudioClient)o;
144
+ IntPtr fmt;
145
+ Check(client.GetMixFormat(out fmt), "mix format");
146
+ int tag = Marshal.ReadInt16(fmt, 0);
147
+ int ch = Marshal.ReadInt16(fmt, 2);
148
+ int rate = Marshal.ReadInt32(fmt, 4);
149
+ int bits = Marshal.ReadInt16(fmt, 14);
150
+ bool isFloat = tag == 3;
151
+ if (tag == unchecked((short)0xFFFE)) {
152
+ var sub = new byte[16];
153
+ Marshal.Copy(new IntPtr(fmt.ToInt64() + 24), sub, 0, 16);
154
+ isFloat = new Guid(sub) == new Guid("00000003-0000-0010-8000-00aa00389b71");
155
+ }
156
+ if (!(isFloat && bits == 32) && !(!isFloat && (bits == 16 || bits == 32))) { Native.CoTaskMemFree(fmt); throw new Exception(name + ": unsupported format " + bits + " bit"); }
157
+ Check(client.Initialize(0, loopback ? 0x00020000 : 0, 10000000, 0, fmt, IntPtr.Zero), "initialize");
158
+ Native.CoTaskMemFree(fmt);
159
+ Guid capIid = typeof(IAudioCaptureClient).GUID;
160
+ object c2;
161
+ Check(client.GetService(ref capIid, out c2), "capture client");
162
+ var s = new AudioStream(name, client, (IAudioCaptureClient)c2, new WavWriter(path), ch, rate, bits, isFloat);
163
+ Check(client.Start(), "start");
164
+ return s;
165
+ }
166
+
167
+ static void Check(int hr, string what) { if (hr != 0) throw new Exception(what + " failed 0x" + hr.ToString("X8")); }
168
+
169
+ /** Đọc hết gói đang chờ; trả số khung đã đọc. */
170
+ public int Pump() {
171
+ int total = 0;
172
+ uint packet;
173
+ while (capture.GetNextPacketSize(out packet) == 0 && packet > 0) {
174
+ IntPtr data; uint frames; int flags; long pos, qpc;
175
+ if (capture.GetBuffer(out data, out frames, out flags, out pos, out qpc) != 0) break;
176
+ bool silent = (flags & 2) != 0;
177
+ int outCount = 0;
178
+ int bytesPerFrame = channels * bits / 8;
179
+ int bytes = (int)frames * bytesPerFrame;
180
+ if (!silent) { if (raw.Length < bytes) raw = new byte[bytes]; Marshal.Copy(data, raw, 0, bytes); }
181
+ for (int i = 0; i < frames; i++) {
182
+ double v = 0;
183
+ if (!silent) {
184
+ int off = i * bytesPerFrame;
185
+ for (int c = 0; c < channels; c++, off += bits / 8) {
186
+ if (isFloat) v += BitConverter.ToSingle(raw, off);
187
+ else if (bits == 16) v += BitConverter.ToInt16(raw, off) / 32768.0;
188
+ else v += BitConverter.ToInt32(raw, off) / 2147483648.0;
189
+ }
190
+ v /= channels;
191
+ }
192
+ // Giảm mẫu bằng trung bình từng khoảng (lọc thông thấp thô — đủ cho nhận dạng giọng nói).
193
+ sum += v; n++; acc += step;
194
+ if (acc >= 1) {
195
+ double m = sum / n; acc -= 1; sum = 0; n = 0;
196
+ if (m > 1) m = 1; if (m < -1) m = -1;
197
+ if (outCount >= outBuf.Length) { wav.Write(outBuf, outCount); outCount = 0; }
198
+ outBuf[outCount++] = (short)(m * 32767);
199
+ levelSum += m * m; levelCount++;
200
+ }
201
+ }
202
+ if (outCount > 0) wav.Write(outBuf, outCount);
203
+ capture.ReleaseBuffer(frames);
204
+ total += (int)frames;
205
+ }
206
+ return total;
207
+ }
208
+
209
+ /** Im lặng theo đồng hồ khi loopback không gửi gói (máy không phát tiếng). */
210
+ public void PadTo(long expected) {
211
+ long missing = expected - wav.Samples;
212
+ if (missing > WavWriter.Rate / 5) wav.WriteSilence(missing);
213
+ }
214
+
215
+ public double TakeLevel() {
216
+ double r = levelCount > 0 ? Math.Sqrt(levelSum / levelCount) : 0;
217
+ levelSum = 0; levelCount = 0;
218
+ return Math.Round(r, 4);
219
+ }
220
+
221
+ public long Samples { get { return wav.Samples; } }
222
+
223
+ public void Close() {
224
+ try { client.Stop(); } catch { }
225
+ wav.Close();
226
+ }
227
+ }
228
+
229
+ public static class Screen {
230
+ public static Bitmap Grab(int monitor) {
231
+ Rectangle r = monitor < 0 ? SystemInformation.VirtualScreen : System.Windows.Forms.Screen.AllScreens[Math.Min(monitor, System.Windows.Forms.Screen.AllScreens.Length - 1)].Bounds;
232
+ var bmp = new Bitmap(r.Width, r.Height, PixelFormat.Format24bppRgb);
233
+ using (var g = Graphics.FromImage(bmp)) g.CopyFromScreen(r.Left, r.Top, 0, 0, r.Size);
234
+ return bmp;
235
+ }
236
+
237
+ public static Bitmap Scale(Bitmap src, int maxWidth) {
238
+ if (src.Width <= maxWidth) return src;
239
+ int h = (int)Math.Round(src.Height * (double)maxWidth / src.Width);
240
+ var dst = new Bitmap(maxWidth, h, PixelFormat.Format24bppRgb);
241
+ using (var g = Graphics.FromImage(dst)) { g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBilinear; g.DrawImage(src, 0, 0, maxWidth, h); }
242
+ src.Dispose();
243
+ return dst;
244
+ }
245
+
246
+ public static byte[] Jpeg(Bitmap bmp, int quality) {
247
+ var codec = Array.Find(ImageCodecInfo.GetImageEncoders(), c => c.MimeType == "image/jpeg");
248
+ var p = new EncoderParameters(1);
249
+ p.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, (long)quality);
250
+ using (var ms = new MemoryStream()) { bmp.Save(ms, codec, p); return ms.ToArray(); }
251
+ }
252
+
253
+ /** Ảnh thu nhỏ xám 64x36 để so màn hình có đổi không. */
254
+ public static byte[] Thumb(Bitmap src) {
255
+ var t = new byte[64 * 36];
256
+ using (var small = new Bitmap(64, 36, PixelFormat.Format24bppRgb)) {
257
+ using (var g = Graphics.FromImage(small)) g.DrawImage(src, 0, 0, 64, 36);
258
+ for (int y = 0; y < 36; y++) for (int x = 0; x < 64; x++) { var c = small.GetPixel(x, y); t[y * 64 + x] = (byte)((c.R * 3 + c.G * 6 + c.B) / 10); }
259
+ }
260
+ return t;
261
+ }
262
+
263
+ public static double Diff(byte[] a, byte[] b) {
264
+ if (a == null || b == null) return 255;
265
+ long s = 0;
266
+ for (int i = 0; i < a.Length; i++) s += Math.Abs(a[i] - b[i]);
267
+ return (double)s / a.Length;
268
+ }
269
+
270
+ public static void Snap(string argsJson) {
271
+ Native.SetProcessDPIAware();
272
+ var a = Out.Parse(argsJson);
273
+ int monitor = a.ContainsKey("monitor") ? Convert.ToInt32(a["monitor"]) : -1;
274
+ int maxWidth = a.ContainsKey("max_width") ? Convert.ToInt32(a["max_width"]) : 1600;
275
+ int quality = a.ContainsKey("quality") ? Convert.ToInt32(a["quality"]) : 70;
276
+ var res = Out.Msg("snap");
277
+ var monitors = new List<object>();
278
+ var all = System.Windows.Forms.Screen.AllScreens;
279
+ for (int i = 0; i < all.Length; i++) {
280
+ var m = new Dictionary<string, object>();
281
+ m["index"] = i; m["primary"] = all[i].Primary; m["width"] = all[i].Bounds.Width; m["height"] = all[i].Bounds.Height; m["left"] = all[i].Bounds.Left; m["top"] = all[i].Bounds.Top;
282
+ monitors.Add(m);
283
+ }
284
+ using (var bmp = Scale(Grab(monitor), Math.Max(320, Math.Min(maxWidth, 3840)))) {
285
+ var img = new Dictionary<string, object>();
286
+ img["mime"] = "image/jpeg"; img["base64"] = Convert.ToBase64String(Jpeg(bmp, quality)); img["width"] = bmp.Width; img["height"] = bmp.Height;
287
+ res["image"] = img;
288
+ }
289
+ res["monitors"] = monitors;
290
+ Out.Send(res);
291
+ }
292
+ }
293
+
294
+ public static class Recorder {
295
+ static volatile bool stopping;
296
+
297
+ public static void Run(string argsJson) {
298
+ Native.SetProcessDPIAware();
299
+ var a = Out.Parse(argsJson);
300
+ string dir = (string)a["dir"];
301
+ bool screens = !a.ContainsKey("screens") || Convert.ToBoolean(a["screens"]);
302
+ int screenEvery = a.ContainsKey("screens_every_sec") ? Convert.ToInt32(a["screens_every_sec"]) : 15;
303
+ int maxScreens = a.ContainsKey("max_screens") ? Convert.ToInt32(a["max_screens"]) : 300;
304
+ Directory.CreateDirectory(dir);
305
+ if (screens) Directory.CreateDirectory(Path.Combine(dir, "screens"));
306
+
307
+ AudioStream sys = null, mic = null;
308
+ try { sys = AudioStream.Open("system", true, Path.Combine(dir, "system.wav")); }
309
+ catch (Exception e) { var w = Out.Msg("warn"); w["what"] = "system"; w["error"] = e.Message; Out.Send(w); }
310
+ try { mic = AudioStream.Open("mic", false, Path.Combine(dir, "mic.wav")); }
311
+ catch (Exception e) { var w = Out.Msg("warn"); w["what"] = "mic"; w["error"] = e.Message; Out.Send(w); }
312
+ if (sys == null && mic == null) { var f = Out.Msg("error"); f["error"] = "No audio device could be opened"; Out.Send(f); return; }
313
+
314
+ var reader = new Thread(() => {
315
+ try { string line; while ((line = Console.In.ReadLine()) != null) { if (line.Trim() == "stop") break; } } catch { }
316
+ stopping = true;
317
+ });
318
+ reader.IsBackground = true;
319
+ reader.Start();
320
+
321
+ var ready = Out.Msg("ready"); ready["system"] = sys != null; ready["mic"] = mic != null; Out.Send(ready);
322
+ var clock = System.Diagnostics.Stopwatch.StartNew();
323
+ long nextLevel = 1000, nextWindows = 0, nextScreen = 2000;
324
+ byte[] lastThumb = null;
325
+ int screenCount = 0;
326
+ while (!stopping) {
327
+ long expected = clock.ElapsedMilliseconds * WavWriter.Rate / 1000;
328
+ if (sys != null && sys.Pump() == 0) sys.PadTo(expected);
329
+ if (mic != null && mic.Pump() == 0) mic.PadTo(expected);
330
+ long ms = clock.ElapsedMilliseconds;
331
+ if (ms >= nextLevel) {
332
+ nextLevel += 1000;
333
+ var l = Out.Msg("level"); l["secs"] = ms / 1000; l["system"] = sys != null ? sys.TakeLevel() : 0; l["mic"] = mic != null ? mic.TakeLevel() : 0;
334
+ Out.Send(l);
335
+ }
336
+ if (ms >= nextWindows) {
337
+ nextWindows = ms + 10000;
338
+ var titles = new List<object>();
339
+ Native.EnumWindows((h, p) => {
340
+ if (titles.Count >= 200 || !Native.IsWindowVisible(h)) return true;
341
+ var sb = new StringBuilder(512);
342
+ if (Native.GetWindowText(h, sb, 512) > 0) titles.Add(sb.ToString());
343
+ return true;
344
+ }, IntPtr.Zero);
345
+ var wmsg = Out.Msg("windows"); wmsg["titles"] = titles; Out.Send(wmsg);
346
+ }
347
+ if (screens && ms >= nextScreen && screenCount < maxScreens) {
348
+ nextScreen = ms + screenEvery * 1000;
349
+ try {
350
+ using (var full = Screen.Grab(-1)) {
351
+ var thumb = Screen.Thumb(full);
352
+ if (Screen.Diff(thumb, lastThumb) > 6) {
353
+ lastThumb = thumb;
354
+ long secs = ms / 1000;
355
+ string name = string.Format("{0:D2}-{1:D2}-{2:D2}.jpg", secs / 3600, (secs / 60) % 60, secs % 60);
356
+ using (var scaled = Screen.Scale(new Bitmap(full), 1600)) File.WriteAllBytes(Path.Combine(dir, "screens", name), Screen.Jpeg(scaled, 70));
357
+ screenCount++;
358
+ var s = Out.Msg("screen"); s["file"] = name; s["secs"] = secs; Out.Send(s);
359
+ }
360
+ }
361
+ } catch (Exception e) { var w = Out.Msg("warn"); w["what"] = "screen"; w["error"] = e.Message; Out.Send(w); }
362
+ }
363
+ Thread.Sleep(10);
364
+ }
365
+ long end = clock.ElapsedMilliseconds * WavWriter.Rate / 1000;
366
+ if (sys != null) { sys.Pump(); sys.PadTo(end); sys.Close(); }
367
+ if (mic != null) { mic.Pump(); mic.PadTo(end); mic.Close(); }
368
+ var done = Out.Msg("done"); done["secs"] = clock.ElapsedMilliseconds / 1000; done["system"] = sys != null; done["mic"] = mic != null; done["screens"] = screenCount;
369
+ Out.Send(done);
370
+ }
371
+ }
372
+ }
373
+ `;
374
+
375
+ export const MEDIA_HOST_PS1 = String.raw`
376
+ $ErrorActionPreference = 'Stop'
377
+ $dll = $env:AIVIN_MEDIA_DLL
378
+ $src = $env:AIVIN_MEDIA_SRC
379
+ $refs = @('System.Drawing', 'System.Windows.Forms', 'System.Web.Extensions')
380
+ foreach ($r in $refs) { Add-Type -AssemblyName $r }
381
+ if ($dll -and (Test-Path -LiteralPath $dll)) {
382
+ Add-Type -Path $dll
383
+ } else {
384
+ Add-Type -TypeDefinition ([IO.File]::ReadAllText($src)) -ReferencedAssemblies $refs -OutputAssembly $dll -OutputType Library
385
+ Add-Type -Path $dll
386
+ }
387
+ try {
388
+ if ($env:AIVIN_MEDIA_MODE -eq 'snap') { [AivinMedia.Screen]::Snap($env:AIVIN_MEDIA_ARGS) } else { [AivinMedia.Recorder]::Run($env:AIVIN_MEDIA_ARGS) }
389
+ } catch {
390
+ $m = @{ t = 'error'; error = $_.Exception.Message } | ConvertTo-Json -Compress
391
+ [Console]::Out.WriteLine($m)
392
+ exit 1
393
+ }
394
+ `;
@@ -0,0 +1,259 @@
1
+ import fs from 'fs';
2
+
3
+ /**
4
+ * Biên bản sau buổi ghi (29/10/2026): ghi xong mới xử lý một thể — đọc `system.wav` + `mic.wav` (16 kHz mono 16-bit, cùng mốc thời gian), trộn
5
+ * thành một luồng, cắt đoạn ~30 s tại chỗ im nhất quanh mốc cắt (không cắt giữa câu), bỏ đoạn im lặng, rồi gửi từng đoạn qua `stt(wav)` — chính
6
+ * `device:stt` ô hỏi của linh vật dùng (BE không cần thêm gì). Đoạn BE chê dài (`audio_too_big`) thì chia đôi.
7
+ */
8
+
9
+ export const SAMPLE_RATE = 16000;
10
+ const FRAME = SAMPLE_RATE / 10; // 100 ms
11
+ export const CHUNK_SEC = 30;
12
+ const CUT_WINDOW_SEC = 3;
13
+ const MIN_SPLIT_SEC = 4;
14
+ /** RMS (0..1) dưới mức này cả đoạn = im lặng, không gửi. */
15
+ const SILENCE_RMS = 0.006;
16
+
17
+ /** Đầu đọc WAV PCM 16-bit mono: tìm chunk `data`, đọc theo mẫu. Tệp không có → đọc ra toàn 0. */
18
+ export function openWav(file) {
19
+ let fd = null;
20
+ let dataOffset = 44;
21
+ let samples = 0;
22
+ try {
23
+ fd = fs.openSync(file, 'r');
24
+ const head = Buffer.alloc(4096);
25
+ const n = fs.readSync(fd, head, 0, head.length, 0);
26
+ let p = 12;
27
+ while (p + 8 <= n) {
28
+ const id = head.toString('ascii', p, p + 4);
29
+ const size = head.readUInt32LE(p + 4);
30
+ if (id === 'data') { dataOffset = p + 8; break; }
31
+ p += 8 + size + (size % 2);
32
+ }
33
+ const bytes = fs.fstatSync(fd).size - dataOffset;
34
+ samples = Math.max(0, Math.floor(bytes / 2));
35
+ } catch {
36
+ if (fd !== null) fs.closeSync(fd);
37
+ fd = null;
38
+ }
39
+ return {
40
+ samples,
41
+ read(start, count) {
42
+ const out = new Int16Array(Math.max(0, count));
43
+ if (fd === null || start >= samples) return out;
44
+ const n = Math.min(count, samples - start);
45
+ const buf = Buffer.alloc(n * 2);
46
+ fs.readSync(fd, buf, 0, buf.length, dataOffset + start * 2);
47
+ for (let i = 0; i < n; i++) out[i] = buf.readInt16LE(i * 2);
48
+ return out;
49
+ },
50
+ close() { if (fd !== null) fs.closeSync(fd); fd = null; },
51
+ };
52
+ }
53
+
54
+ /** Cộng hai luồng (cắt đỉnh). */
55
+ export function mix(a, b) {
56
+ const out = new Int16Array(Math.max(a.length, b.length));
57
+ for (let i = 0; i < out.length; i++) {
58
+ const v = (a[i] || 0) + (b[i] || 0);
59
+ out[i] = v > 32767 ? 32767 : v < -32768 ? -32768 : v;
60
+ }
61
+ return out;
62
+ }
63
+
64
+ export function rms(samples, from = 0, to = samples.length) {
65
+ let s = 0;
66
+ for (let i = from; i < to; i++) s += samples[i] * samples[i];
67
+ return to > from ? Math.sqrt(s / (to - from)) / 32768 : 0;
68
+ }
69
+
70
+ /** Điểm cắt: khung 100 ms im nhất trong [lo, hi) (chỉ số mẫu tương đối trong `samples`). */
71
+ export function quietestCut(samples, lo, hi) {
72
+ let best = hi;
73
+ let bestRms = Infinity;
74
+ for (let p = lo; p + FRAME <= hi; p += FRAME) {
75
+ const r = rms(samples, p, p + FRAME);
76
+ if (r < bestRms) { bestRms = r; best = p + FRAME / 2; }
77
+ }
78
+ return Math.min(best, samples.length);
79
+ }
80
+
81
+ export function wavBuffer(samples) {
82
+ const data = samples.length * 2;
83
+ const buf = Buffer.alloc(44 + data);
84
+ buf.write('RIFF', 0, 'ascii'); buf.writeUInt32LE(36 + data, 4); buf.write('WAVE', 8, 'ascii');
85
+ buf.write('fmt ', 12, 'ascii'); buf.writeUInt32LE(16, 16); buf.writeUInt16LE(1, 20); buf.writeUInt16LE(1, 22);
86
+ buf.writeUInt32LE(SAMPLE_RATE, 24); buf.writeUInt32LE(SAMPLE_RATE * 2, 28); buf.writeUInt16LE(2, 32); buf.writeUInt16LE(16, 34);
87
+ buf.write('data', 36, 'ascii'); buf.writeUInt32LE(data, 40);
88
+ for (let i = 0; i < samples.length; i++) buf.writeInt16LE(samples[i], 44 + i * 2);
89
+ return buf;
90
+ }
91
+
92
+ /** Khung 100 ms: bên nào đang nói (chỉ số nguồn) — `null` = im. Micro thường lọt tiếng loa (không đeo tai nghe) nên phải lớn hơn hẳn mới tính
93
+ * là chủ máy nói. */
94
+ const FRAME_SPEECH_RMS = 0.008;
95
+ function frameSides(parts, frames) {
96
+ const sides = new Array(frames).fill(null);
97
+ for (let f = 0; f < frames; f++) {
98
+ const e = parts.map((p) => rms(p, f * FRAME, (f + 1) * FRAME));
99
+ if (Math.max(...e) < FRAME_SPEECH_RMS) continue;
100
+ sides[f] = e[1] > e[0] * 2 ? 1 : 0;
101
+ }
102
+ return sides;
103
+ }
104
+
105
+ const MIN_TURN_FRAMES = 40; // đoạn ít nhất 4 s trước khi cắt theo người nói
106
+ const TURN_CONFIRM_FRAMES = 15; // bên mới phải nói ≥ 1,5 s (12/15 khung) mới tính là đổi lượt
107
+
108
+ /** Khung đầu tiên (≥ MIN_TURN_FRAMES) mà bên kia bắt đầu một lượt nói thật — lùi về khung im gần nhất cho đường cắt sạch. */
109
+ function turnChange(sides, limit) {
110
+ let current = null;
111
+ for (let f = 0; f < limit; f++) {
112
+ const s = sides[f];
113
+ if (s === null) continue;
114
+ if (current === null) { current = s; continue; }
115
+ if (s === current) continue;
116
+ let same = 0;
117
+ for (let g = f; g < Math.min(f + TURN_CONFIRM_FRAMES, sides.length); g++) if (sides[g] === s) same++;
118
+ if (same < TURN_CONFIRM_FRAMES * 0.8) continue;
119
+ if (f < MIN_TURN_FRAMES) { current = s; continue; }
120
+ for (let b = f - 1; b > f - 10 && b > 0; b--) if (sides[b] === null) return b + 1;
121
+ return f;
122
+ }
123
+ return null;
124
+ }
125
+
126
+ /** Bên nói chính của đoạn: một bên chiếm ≥ 70 % khung có tiếng, không thì `null` (cả hai cùng nói / xen kẽ nhanh). */
127
+ function majoritySide(sides, from, to) {
128
+ const count = [0, 0];
129
+ for (let f = from; f < to; f++) if (sides[f] !== null) count[sides[f]]++;
130
+ const total = count[0] + count[1];
131
+ if (!total) return null;
132
+ if (count[0] / total >= 0.7) return 0;
133
+ if (count[1] / total >= 0.7) return 1;
134
+ return null;
135
+ }
136
+
137
+ /**
138
+ * Các đoạn cần chuyển chữ của bản ghi — `[{ start, end, silent?, speaker? }]` (giây). Đọc dần (không nạp cả tệp hàng trăm MB).
139
+ * Hai nguồn + `labels` (`[âm thanh máy, micro]`): cắt thêm ở chỗ đổi lượt nói giữa hai bên và gắn `speaker` = nhãn của bên nói chính.
140
+ */
141
+ export function planChunks({ sources, chunkSec = CHUNK_SEC, labels = null }) {
142
+ const total = Math.max(...sources.map((s) => s.samples), 0);
143
+ const chunk = chunkSec * SAMPLE_RATE;
144
+ const win = CUT_WINDOW_SEC * SAMPLE_RATE;
145
+ const bySpeaker = !!labels && sources.length === 2;
146
+ const chunks = [];
147
+ let pos = 0;
148
+ while (pos < total) {
149
+ const want = Math.min(chunk + win, total - pos);
150
+ const parts = sources.map((s) => s.read(pos, want));
151
+ const mixed = parts.reduce((acc, p) => mix(acc, p), new Int16Array(want));
152
+ let cut = pos + want >= total ? want : quietestCut(mixed, Math.max(FRAME, chunk - win), want);
153
+ let speaker;
154
+ if (bySpeaker) {
155
+ const sides = frameSides(parts, Math.floor(want / FRAME));
156
+ const turn = turnChange(sides, Math.floor(cut / FRAME));
157
+ if (turn !== null) cut = turn * FRAME;
158
+ const side = majoritySide(sides, 0, Math.floor(cut / FRAME));
159
+ speaker = side === null ? null : labels[side];
160
+ }
161
+ const silent = rms(mixed, 0, cut) < SILENCE_RMS;
162
+ chunks.push({ start: pos / SAMPLE_RATE, end: (pos + cut) / SAMPLE_RATE, silent, ...(bySpeaker && !silent ? { speaker } : {}) });
163
+ pos += Math.max(cut, FRAME);
164
+ }
165
+ return chunks;
166
+ }
167
+
168
+ const readMixed = (sources, start, end) => {
169
+ const from = Math.round(start * SAMPLE_RATE);
170
+ const count = Math.round((end - start) * SAMPLE_RATE);
171
+ return sources.reduce((acc, s) => mix(acc, s.read(from, count)), new Int16Array(count));
172
+ };
173
+
174
+ /**
175
+ * Chuyển chữ cả bản ghi. `stt(wavBuffer) → { ok, text?, error? }` (lỗi mạng thì ném). `onProgress({ done, total })`. Trả các đoạn có chữ
176
+ * `[{ start, end, text }]` và đoạn hỏng `failed: [{ start, end, error }]`. `signal` huỷ giữa chừng (giữ phần đã xong).
177
+ */
178
+ export async function transcribeRecording({ files, stt, onProgress = () => {}, signal, retries = 2, chunkSec = CHUNK_SEC, labels = null }) {
179
+ const sources = files.map(openWav);
180
+ try {
181
+ const plan = planChunks({ sources, chunkSec, labels });
182
+ const speech = plan.filter((c) => !c.silent);
183
+ const segments = [];
184
+ const failed = [];
185
+ let done = 0;
186
+ const run = async (start, end, speaker) => {
187
+ let lastError = 'failed';
188
+ for (let attempt = 0; attempt <= retries; attempt++) {
189
+ if (signal?.aborted) return;
190
+ let res;
191
+ try {
192
+ res = await stt(wavBuffer(readMixed(sources, start, end)));
193
+ } catch (e) {
194
+ lastError = e?.message || String(e);
195
+ await new Promise((r) => setTimeout(r, 1000 * (attempt + 1)));
196
+ continue;
197
+ }
198
+ if (res?.ok) {
199
+ const text = String(res.text || '').trim();
200
+ if (text) segments.push({ start, end, text, ...(speaker ? { speaker } : {}) });
201
+ return;
202
+ }
203
+ lastError = res?.error || 'failed';
204
+ if (lastError === 'audio_too_big' && end - start > MIN_SPLIT_SEC * 2) {
205
+ const mid = (start + end) / 2;
206
+ await run(start, mid, speaker);
207
+ await run(mid, end, speaker);
208
+ return;
209
+ }
210
+ if (lastError === 'not_understood' || lastError === 'empty') return; // đoạn không có lời nói
211
+ }
212
+ failed.push({ start, end, error: lastError });
213
+ };
214
+ for (const c of speech) {
215
+ if (signal?.aborted) break;
216
+ await run(c.start, c.end, c.speaker);
217
+ done++;
218
+ onProgress({ done, total: speech.length });
219
+ }
220
+ segments.sort((a, b) => a.start - b.start);
221
+ return { segments, failed, chunks: speech.length, seconds: Math.max(...sources.map((s) => s.samples), 0) / SAMPLE_RATE };
222
+ } finally {
223
+ for (const s of sources) s.close();
224
+ }
225
+ }
226
+
227
+ export function clock(sec) {
228
+ const s = Math.max(0, Math.floor(sec));
229
+ const hh = Math.floor(s / 3600);
230
+ const mm = String(Math.floor(s / 60) % 60).padStart(2, '0');
231
+ const ss = String(s % 60).padStart(2, '0');
232
+ return hh ? `${hh}:${mm}:${ss}` : `${mm}:${ss}`;
233
+ }
234
+
235
+ /** Nhãn người nói trong biên bản: `me` = chủ máy (micro), `others` = người khác (âm thanh máy). */
236
+ export const Speaker = Object.freeze({ ME: 'me', OTHERS: 'others' });
237
+ const speakerName = (key, vi) => (key === Speaker.ME ? (vi ? 'Chủ máy' : 'Me') : vi ? 'Người khác' : 'Others');
238
+
239
+ /** Biên bản Markdown: mốc thời gian + lời nói, ảnh màn hình chen đúng chỗ, đoạn không chuyển được ghi rõ. */
240
+ export function formatTranscript({ title, startedAt, seconds, segments, failed = [], screens = [], lang = 'vi' }) {
241
+ const vi = lang !== 'en';
242
+ const rows = [
243
+ ...segments.map((s) => ({ at: s.start, line: `**[${clock(s.start)}]** ${s.speaker ? `**${speakerName(s.speaker, vi)}:** ` : ''}${s.text}` })),
244
+ ...screens.map((f) => ({ at: f.secs, line: `**[${clock(f.secs)}]** _(${vi ? 'ảnh màn hình' : 'screenshot'}: screens/${f.file})_` })),
245
+ ...failed.map((f) => ({ at: f.start, line: `**[${clock(f.start)}–${clock(f.end)}]** _(${vi ? 'không chuyển được đoạn này thành chữ' : 'this part could not be transcribed'}: ${f.error})_` })),
246
+ ].sort((a, b) => a.at - b.at);
247
+ const when = startedAt ? new Date(startedAt) : null;
248
+ const head = [
249
+ `# ${title || (vi ? 'Cuộc họp' : 'Meeting')}`,
250
+ '',
251
+ `- ${vi ? 'Bắt đầu' : 'Started'}: ${when ? when.toLocaleString(vi ? 'vi-VN' : 'en-US') : '?'}`,
252
+ `- ${vi ? 'Thời lượng' : 'Duration'}: ${clock(seconds)}`,
253
+ `- ${vi ? 'Nguồn' : 'Source'}: ${vi ? 'âm thanh máy (người khác) + micro (chủ máy), chuyển chữ tự động — có thể sai tên riêng / số; nhãn người nói theo micro / loa, không tách từng người khác nhau' : "computer sound (others) + microphone (owner), automatic transcription — names / numbers may be wrong; speaker labels come from mic vs. speaker, the others are not told apart"}`,
254
+ '',
255
+ '---',
256
+ '',
257
+ ];
258
+ return `${head.join('\n')}${rows.length ? rows.map((r) => r.line).join('\n\n') : vi ? '_(Không có lời nói nào được ghi lại.)_' : '_(No speech was recorded.)_'}\n`;
259
+ }