@aivin-labs/cli 1.0.8 → 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 (51) hide show
  1. package/README.md +25 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1912 -1780
  4. package/bin/lib/browserAutomation.mjs +232 -469
  5. package/bin/lib/localBrowser.mjs +345 -0
  6. package/bin/lib/remote/activityLog.mjs +1 -1
  7. package/bin/lib/remote/autoStart.mjs +174 -14
  8. package/bin/lib/remote/browserTunnel.mjs +142 -31
  9. package/bin/lib/remote/callLedger.mjs +1 -1
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +87 -5
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/codingAgents.mjs +293 -0
  14. package/bin/lib/remote/constants.mjs +61 -0
  15. package/bin/lib/remote/dailyBrowser.mjs +1 -1
  16. package/bin/lib/remote/desktop/index.mjs +272 -0
  17. package/bin/lib/remote/desktop/linux.mjs +144 -0
  18. package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
  19. package/bin/lib/remote/desktop/mac.mjs +187 -0
  20. package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
  21. package/bin/lib/remote/desktop/strings.mjs +74 -0
  22. package/bin/lib/remote/desktop/traySource.mjs +527 -0
  23. package/bin/lib/remote/docText.mjs +1 -1
  24. package/bin/lib/remote/fileIndexer.mjs +1 -1
  25. package/bin/lib/remote/gui/index.mjs +93 -12
  26. package/bin/lib/remote/gui/windowsHostSource.mjs +280 -28
  27. package/bin/lib/remote/idempotency.mjs +1 -1
  28. package/bin/lib/remote/localPolicy.mjs +9 -2
  29. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  30. package/bin/lib/remote/mascot/ask.mjs +768 -0
  31. package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
  32. package/bin/lib/remote/mascot/assets.mjs +825 -216
  33. package/bin/lib/remote/mascot/bot.mjs +372 -0
  34. package/bin/lib/remote/mascot/hostSource.mjs +498 -101
  35. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  36. package/bin/lib/remote/mascot/index.mjs +199 -28
  37. package/bin/lib/remote/mascot/labels.mjs +2 -3
  38. package/bin/lib/remote/mascot/rigSource.mjs +609 -0
  39. package/bin/lib/remote/mascot/strings.mjs +204 -18
  40. package/bin/lib/remote/mascot/ui.mjs +104 -0
  41. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  42. package/bin/lib/remote/meeting/index.mjs +415 -0
  43. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  44. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  45. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  46. package/bin/lib/remote/tabGroups.mjs +209 -0
  47. package/bin/lib/remote/toolHandlers.mjs +15 -0
  48. package/docs/AIVIN_MASCOT.md +116 -0
  49. package/docs/CLI.md +142 -11
  50. package/docs/media/aivin-mascot-states.mp4 +0 -0
  51. package/package.json +1 -1
@@ -0,0 +1,427 @@
1
+ /**
2
+ * Aivin trên màn hình Linux (29/10/2026) — biểu tượng khay qua AppIndicator (Ubuntu / KDE / phần lớn môi trường có khay; GNOME cần tiện
3
+ * ích AppIndicator) bằng python3 + PyGObject có sẵn trên đa số bản desktop. Không có AppIndicator / GTK / màn hình → vẫn chạy, chỉ giữ
4
+ * daemon chạy (không biểu tượng). Không có python3 → kịch bản sh khởi chạy tự lặp giữ daemon. Như Aivin.exe: mã 0 → chờ tới khi máy rảnh lại,
5
+ * 75 → chạy lại ngay, khác → giãn dần tới 5 phút (tự lùi bản nằm trong aivin-remote-run.sh). `@@HOME@@` = thư mục cấu hình (chuỗi JSON).
6
+ */
7
+ export const LINUX_TRAY_PY = String.raw`#!/usr/bin/env python3
8
+ # Aivin tray (Linux): AppIndicator icon + keeps aivin-remote-run.sh running. Falls back to no icon when GTK / AppIndicator is missing.
9
+ import calendar
10
+ import json
11
+ import os
12
+ import shutil
13
+ import signal
14
+ import subprocess
15
+ import sys
16
+ import time
17
+
18
+ HOME = @@HOME@@
19
+ CREDS = os.path.join(HOME, 'device-credentials.json')
20
+ LOCK = os.path.join(HOME, 'remote-daemon.lock')
21
+ PAUSED = os.path.join(HOME, 'remote-paused')
22
+ DESK = os.path.join(HOME, 'desktop')
23
+ CFG = os.path.join(DESK, 'launch.cfg')
24
+ LOGO = os.path.join(DESK, 'logo.png')
25
+ LOGO_GREY = os.path.join(DESK, 'logo-grey.png')
26
+ TRAY_LOCK = os.path.join(DESK, 'tray.lock')
27
+ OPEN_REQ = os.path.join(DESK, 'open-request')
28
+ QUIT_REQ = os.path.join(DESK, 'quit-request')
29
+ RESTART_CODE = 75
30
+
31
+
32
+ def load_cfg():
33
+ cfg = {'exe': None, 'args': [], 's': {}, 'extra': {}}
34
+ try:
35
+ with open(CFG, encoding='utf-8') as f:
36
+ for line in f.read().splitlines():
37
+ k, sep, v = line.partition('=')
38
+ if not sep or not k:
39
+ continue
40
+ if k == 'exe':
41
+ cfg['exe'] = v
42
+ elif k == 'arg':
43
+ cfg['args'].append(v)
44
+ elif k.startswith('s.'):
45
+ cfg['s'][k[2:]] = v
46
+ else:
47
+ cfg['extra'][k] = v
48
+ except OSError:
49
+ pass
50
+ return cfg
51
+
52
+
53
+ def mtime(path):
54
+ try:
55
+ return os.stat(path).st_mtime
56
+ except OSError:
57
+ return 0
58
+
59
+
60
+ def touch(path):
61
+ with open(path, 'w') as f:
62
+ f.write(str(time.time()))
63
+
64
+
65
+ def notify(text):
66
+ if shutil.which('notify-send'):
67
+ subprocess.Popen(['notify-send', '-i', LOGO, 'AIVIN Bot CLI', text], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
68
+
69
+
70
+ def pid_alive(pid):
71
+ try:
72
+ os.kill(pid, 0)
73
+ return True
74
+ except PermissionError:
75
+ return True
76
+ except (OSError, ValueError):
77
+ return False
78
+
79
+
80
+ class Supervisor:
81
+ def __init__(self):
82
+ self.cfg = load_cfg()
83
+ self.child = None
84
+ self.child_pid = 0
85
+ self.started = 0
86
+ self.next_start = 0
87
+ self.delay = 10
88
+ self.pairing = False
89
+ self.was_paired = os.path.exists(CREDS)
90
+ self.seen_open = mtime(OPEN_REQ)
91
+ self.seen_quit = mtime(QUIT_REQ)
92
+ self.on_open = None
93
+ self.on_quit = None
94
+
95
+ def t(self, key):
96
+ return self.cfg['s'].get(key, key)
97
+
98
+ def lock_held(self):
99
+ try:
100
+ with open(LOCK, encoding='utf-8') as f:
101
+ d = json.load(f)
102
+ pid = int(d.get('pid') or 0)
103
+ if self.child is None and pid == self.child_pid:
104
+ return False
105
+ beat = str(d.get('beat_at') or d.get('started_at') or '')
106
+ if beat:
107
+ at = calendar.timegm(time.strptime(beat[:19], '%Y-%m-%dT%H:%M:%S'))
108
+ if time.time() - at > 90:
109
+ return False
110
+ return pid > 0 and pid_alive(pid)
111
+ except (OSError, ValueError):
112
+ return False
113
+
114
+ def running(self):
115
+ return (self.child is not None and self.child.poll() is None) or self.lock_held()
116
+
117
+ def backoff(self):
118
+ self.next_start = time.time() + self.delay
119
+ self.delay = min(self.delay * 2, 300)
120
+
121
+ def start(self, code=None):
122
+ self.cfg = load_cfg()
123
+ if not self.cfg['exe']:
124
+ return
125
+ args = [self.cfg['exe']] + self.cfg['args'] + (['--code', code] if code else [])
126
+ try:
127
+ self.child = subprocess.Popen(args, cwd=os.path.expanduser('~'), stdin=subprocess.DEVNULL, start_new_session=True)
128
+ self.child_pid = self.child.pid
129
+ self.started = time.time()
130
+ self.pairing = bool(code)
131
+ except OSError:
132
+ self.child = None
133
+ self.backoff()
134
+
135
+ def on_exit(self, rc):
136
+ secs = time.time() - self.started
137
+ self.child = None
138
+ was_pairing, self.pairing = self.pairing, False
139
+ if was_pairing and not os.path.exists(CREDS):
140
+ notify(self.t('pairFailed'))
141
+ return
142
+ if rc == 0:
143
+ self.next_start = time.time() + 60
144
+ elif rc == RESTART_CODE:
145
+ self.next_start = time.time() + 1
146
+ else:
147
+ if secs > 300:
148
+ self.delay = 10
149
+ self.backoff()
150
+
151
+ def kill(self):
152
+ c, self.child = self.child, None
153
+ if c is None or c.poll() is not None:
154
+ return
155
+ try:
156
+ os.killpg(c.pid, signal.SIGTERM)
157
+ c.wait(timeout=10)
158
+ except (OSError, subprocess.TimeoutExpired):
159
+ try:
160
+ os.killpg(c.pid, signal.SIGKILL)
161
+ except OSError:
162
+ pass
163
+
164
+ def start_now(self):
165
+ if self.child is None and not self.lock_held():
166
+ self.next_start = 0
167
+ self.delay = 10
168
+
169
+ def tick(self):
170
+ if mtime(QUIT_REQ) > self.seen_quit:
171
+ self.seen_quit = mtime(QUIT_REQ)
172
+ if self.on_quit:
173
+ self.on_quit()
174
+ return
175
+ if self.child is not None:
176
+ rc = self.child.poll()
177
+ if rc is not None:
178
+ self.on_exit(rc)
179
+ paired = os.path.exists(CREDS)
180
+ if paired and not self.was_paired:
181
+ notify(self.t('connected'))
182
+ self.was_paired = paired
183
+ if self.child is None and paired and time.time() >= self.next_start and not self.lock_held():
184
+ self.start()
185
+ req = mtime(OPEN_REQ)
186
+ if req > self.seen_open:
187
+ self.seen_open = req
188
+ if self.on_open:
189
+ self.on_open()
190
+
191
+
192
+ def startup_file(sup):
193
+ return sup.cfg['extra'].get('autostart')
194
+
195
+
196
+ def startup_enabled(sup):
197
+ path = startup_file(sup)
198
+ try:
199
+ with open(path, encoding='utf-8') as f:
200
+ text = f.read()
201
+ except (OSError, TypeError):
202
+ return False
203
+ return 'Hidden=true' not in text and 'X-GNOME-Autostart-enabled=false' not in text
204
+
205
+
206
+ def set_startup(sup, on):
207
+ path, copy = startup_file(sup), sup.cfg['extra'].get('autostart_copy')
208
+ if not path:
209
+ return
210
+ try:
211
+ if on:
212
+ os.makedirs(os.path.dirname(path), exist_ok=True)
213
+ shutil.copyfile(copy, path)
214
+ elif os.path.exists(path):
215
+ with open(path, encoding='utf-8') as f:
216
+ text = f.read()
217
+ text = text.replace('X-GNOME-Autostart-enabled=true', 'X-GNOME-Autostart-enabled=false').replace('Hidden=false', 'Hidden=true')
218
+ with open(path, 'w', encoding='utf-8') as f:
219
+ f.write(text)
220
+ except OSError:
221
+ pass
222
+
223
+
224
+ def gtk_ui(sup):
225
+ """Biểu tượng khay. None khi không có màn hình / GTK / AppIndicator (khi đó chạy không biểu tượng)."""
226
+ if not (os.environ.get('DISPLAY') or os.environ.get('WAYLAND_DISPLAY')):
227
+ return None
228
+ try:
229
+ import gi
230
+ gi.require_version('Gtk', '3.0')
231
+ gi.require_version('GdkPixbuf', '2.0')
232
+ try:
233
+ gi.require_version('AyatanaAppIndicator3', '0.1')
234
+ from gi.repository import AyatanaAppIndicator3 as AppIndicator
235
+ except (ValueError, ImportError):
236
+ gi.require_version('AppIndicator3', '0.1')
237
+ from gi.repository import AppIndicator3 as AppIndicator
238
+ from gi.repository import GdkPixbuf, GLib, Gtk
239
+ except (ImportError, ValueError):
240
+ return None
241
+
242
+ try:
243
+ pb = GdkPixbuf.Pixbuf.new_from_file(LOGO)
244
+ grey = pb.copy()
245
+ pb.saturate_and_pixelate(grey, 0.0, False)
246
+ grey.save(LOGO_GREY, 'png')
247
+ except Exception:
248
+ pass
249
+
250
+ t = sup.t
251
+ ind = AppIndicator.Indicator.new('aivin', LOGO, AppIndicator.IndicatorCategory.APPLICATION_STATUS)
252
+ ind.set_status(AppIndicator.IndicatorStatus.ACTIVE)
253
+ ind.set_title('AIVIN Bot CLI')
254
+ menu = Gtk.Menu()
255
+ status = Gtk.MenuItem(label='AIVIN Bot CLI')
256
+ status.set_sensitive(False)
257
+ connect = Gtk.MenuItem(label=t('connect'))
258
+ pause = Gtk.MenuItem(label=t('pause'))
259
+ startup = Gtk.CheckMenuItem(label=t('startup'))
260
+ folder = Gtk.MenuItem(label=t('folder'))
261
+ quit_item = Gtk.MenuItem(label=t('quit'))
262
+ for item in (status, Gtk.SeparatorMenuItem(), connect, pause, startup, folder, Gtk.SeparatorMenuItem(), quit_item):
263
+ menu.append(item)
264
+ state = {'icon': None, 'syncing': False, 'dialog': False}
265
+
266
+ def refresh():
267
+ paired, paused, up = os.path.exists(CREDS), os.path.exists(PAUSED), sup.running()
268
+ text = t('connecting' if sup.pairing else 'notPaired') if not paired else t('stopped') if not up else t('paused') if paused else t('running')
269
+ status.set_label(text)
270
+ icon = LOGO if paired and up and not paused else (LOGO_GREY if os.path.exists(LOGO_GREY) else LOGO)
271
+ if icon != state['icon']:
272
+ state['icon'] = icon
273
+ ind.set_icon_full(icon, 'Aivin - ' + text)
274
+ connect.set_visible(not paired)
275
+ pause.set_label(t('resume' if paused else 'pause'))
276
+ pause.set_visible(paired)
277
+ state['syncing'] = True
278
+ startup.set_active(startup_enabled(sup))
279
+ state['syncing'] = False
280
+
281
+ def ask_code(*_):
282
+ if state['dialog']:
283
+ return
284
+ state['dialog'] = True
285
+ d = Gtk.Dialog(title='AIVIN Bot CLI')
286
+ d.add_buttons(t('pairCancel'), Gtk.ResponseType.CANCEL, t('pairOk'), Gtk.ResponseType.OK)
287
+ d.set_default_response(Gtk.ResponseType.OK)
288
+ d.set_keep_above(True)
289
+ box = d.get_content_area()
290
+ box.set_spacing(10)
291
+ box.set_border_width(14)
292
+ label = Gtk.Label(label=t('pairPrompt'))
293
+ label.set_line_wrap(True)
294
+ label.set_max_width_chars(48)
295
+ entry = Gtk.Entry()
296
+ entry.set_activates_default(True)
297
+ box.pack_start(label, False, False, 0)
298
+ box.pack_start(entry, False, False, 0)
299
+ d.show_all()
300
+ response = d.run()
301
+ code = entry.get_text().strip().upper()
302
+ d.destroy()
303
+ state['dialog'] = False
304
+ if response == Gtk.ResponseType.OK and code:
305
+ sup.kill()
306
+ sup.start(code)
307
+ refresh()
308
+
309
+ def toggle_pause(*_):
310
+ try:
311
+ if os.path.exists(PAUSED):
312
+ os.remove(PAUSED)
313
+ else:
314
+ with open(PAUSED, 'w') as f:
315
+ f.write(time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()))
316
+ except OSError:
317
+ pass
318
+ refresh()
319
+
320
+ def toggle_startup(item):
321
+ if not state['syncing']:
322
+ set_startup(sup, item.get_active())
323
+ refresh()
324
+
325
+ def open_folder(*_):
326
+ opener = shutil.which('xdg-open')
327
+ if opener:
328
+ subprocess.Popen([opener, HOME], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
329
+
330
+ def quit_app(*_):
331
+ sup.kill()
332
+ Gtk.main_quit()
333
+
334
+ def open_aivin():
335
+ if not os.path.exists(CREDS):
336
+ ask_code()
337
+ else:
338
+ sup.start_now()
339
+ notify(t('running') if sup.running() else t('stopped'))
340
+
341
+ connect.connect('activate', ask_code)
342
+ pause.connect('activate', toggle_pause)
343
+ startup.connect('toggled', toggle_startup)
344
+ folder.connect('activate', open_folder)
345
+ quit_item.connect('activate', quit_app)
346
+ menu.show_all()
347
+ ind.set_menu(menu)
348
+ sup.on_open = open_aivin
349
+ sup.on_quit = quit_app
350
+
351
+ def on_tick():
352
+ sup.tick()
353
+ refresh()
354
+ return True
355
+
356
+ GLib.timeout_add_seconds(2, on_tick)
357
+ refresh()
358
+
359
+ class Ui:
360
+ open = staticmethod(open_aivin)
361
+
362
+ @staticmethod
363
+ def run():
364
+ Gtk.main()
365
+ return Ui
366
+
367
+
368
+ def main(argv):
369
+ import fcntl
370
+ os.makedirs(DESK, exist_ok=True)
371
+ lock = open(TRAY_LOCK, 'w')
372
+ try:
373
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
374
+ except OSError:
375
+ # Đã có một bản chạy: mở lần nữa = mở Aivin; --quit = bảo bản đó thoát.
376
+ if '--quit' in argv:
377
+ touch(QUIT_REQ)
378
+ elif '--autostart' not in argv and '--installed' not in argv:
379
+ touch(OPEN_REQ)
380
+ return 0
381
+ if '--quit' in argv:
382
+ return 0
383
+ sup = Supervisor()
384
+ signal.signal(signal.SIGTERM, lambda *_: (sup.kill(), sys.exit(0)))
385
+ ui = gtk_ui(sup)
386
+ sup.tick()
387
+ if ui is None:
388
+ stop = []
389
+ sup.on_quit = lambda: (sup.kill(), stop.append(True))
390
+ while not stop:
391
+ time.sleep(2)
392
+ sup.tick()
393
+ return 0
394
+ if '--installed' in argv:
395
+ notify(sup.t('firstRun' if sup.was_paired else 'connectHint'))
396
+ elif '--autostart' not in argv:
397
+ ui.open()
398
+ ui.run()
399
+ return 0
400
+
401
+
402
+ if __name__ == '__main__':
403
+ sys.exit(main(sys.argv[1:]))
404
+ `;
405
+
406
+ /**
407
+ * Kịch bản mở Aivin (menu ứng dụng, autostart). Có python3 → khay; không thì tự lặp giữ daemon (chỉ khi đã ghép máy — chưa ghép thì
408
+ * daemon không tự kết nối được, chạy lặp vô ích). `@@…@@` thay bằng đường dẫn đã bọc nháy đơn.
409
+ */
410
+ export const LINUX_LAUNCHER_SH = `#!/bin/sh
411
+ # Aivin desktop app (Linux): tray icon + keeps \`aivin remote start\` running (tray.py); without python3, keeps it running without an icon.
412
+ exec >>@@LOG@@ 2>&1
413
+ if command -v python3 >/dev/null 2>&1; then exec python3 @@TRAY@@ "$@"; fi
414
+ case " $* " in *" --quit "*) exit 0 ;; esac
415
+ delay=10
416
+ while [ -f @@CREDS@@ ]; do
417
+ started=$(date +%s)
418
+ /bin/sh @@RUN@@
419
+ rc=$?
420
+ [ "$rc" -eq 0 ] && exit 0
421
+ if [ "$rc" -eq 75 ]; then sleep 1; continue; fi
422
+ [ $(( $(date +%s) - started )) -gt 300 ] && delay=10
423
+ sleep "$delay"
424
+ delay=$(( delay * 2 ))
425
+ [ "$delay" -gt 300 ] && delay=300
426
+ done
427
+ `;
@@ -0,0 +1,187 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import { posix as path } from 'path';
4
+ import { execFileSync, spawn } from 'child_process';
5
+ import { REMOTE_CONFIG_DIR } from '../constants.mjs';
6
+ import { AIVIN_LOGO_PNG_BASE64 } from '../brand.mjs';
7
+ import { DESKTOP_DIR, LAUNCH_CONFIG_FILE, TrayLaunch, launchConfigText } from './index.mjs';
8
+ import { MAC_TRAY_JS } from './macTraySource.mjs';
9
+
10
+ /**
11
+ * Aivin trên macOS (29/10/2026): gói ~/Applications/Aivin.app (Spotlight / Launchpad tìm được "Aivin") chạy biểu tượng thanh menu
12
+ * (macTraySource.mjs); LaunchAgent com.aivin.remote mở app lúc đăng nhập — AssociatedBundleIdentifiers để System Settings → General →
13
+ * Login Items hiện "Aivin" kèm biểu tượng (không phải "sh") và bật / tắt được ở đó. Nhãn giữ com.aivin.remote như trước (detectSupervisor
14
+ * nhận ra tiến trình cũ theo nhãn), cài đè lên LaunchAgent cũ chạy thẳng aivin-remote-run.sh.
15
+ */
16
+
17
+ export const MAC_BUNDLE_ID = 'vn.aivin.desktop';
18
+ export const MAC_AGENT_LABEL = 'com.aivin.remote';
19
+
20
+ export const macAppPath = (home = os.homedir()) => path.join(home, 'Applications', 'Aivin.app');
21
+ export const macAppExecutable = (app = macAppPath()) => path.join(app, 'Contents', 'MacOS', 'Aivin');
22
+ export const macAgentPath = (home = os.homedir()) => path.join(home, 'Library', 'LaunchAgents', `${MAC_AGENT_LABEL}.plist`);
23
+ /** Bản sao LaunchAgent: menu "Mở khi đăng nhập" chép lại vào ~/Library/LaunchAgents khi bật lại. */
24
+ const AGENT_COPY_FILE = path.join(DESKTOP_DIR, `${MAC_AGENT_LABEL}.plist`);
25
+
26
+ const xml = (s) => String(s).replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');
27
+
28
+ /** .icns chứa nguyên ảnh PNG 64×64 (icp6 = 64 px, ic11 = 32 px @2x) — macOS 10.8+. */
29
+ export function pngToIcns(png) {
30
+ const entries = ['icp6', 'ic11'].map((type) => {
31
+ const head = Buffer.alloc(8);
32
+ head.write(type, 0, 'ascii');
33
+ head.writeUInt32BE(png.length + 8, 4);
34
+ return Buffer.concat([head, png]);
35
+ });
36
+ const body = Buffer.concat(entries);
37
+ const head = Buffer.alloc(8);
38
+ head.write('icns', 0, 'ascii');
39
+ head.writeUInt32BE(body.length + 8, 4);
40
+ return Buffer.concat([head, body]);
41
+ }
42
+
43
+ /** LSUIElement: không có biểu tượng trên Dock, chỉ ở thanh menu. */
44
+ export function macInfoPlist() {
45
+ return `<?xml version="1.0" encoding="UTF-8"?>
46
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
47
+ <plist version="1.0">
48
+ <dict>
49
+ <key>CFBundleName</key>
50
+ <string>AIVIN Bot CLI</string>
51
+ <key>CFBundleDisplayName</key>
52
+ <string>AIVIN Bot CLI</string>
53
+ <key>CFBundleIdentifier</key>
54
+ <string>${MAC_BUNDLE_ID}</string>
55
+ <key>CFBundleExecutable</key>
56
+ <string>Aivin</string>
57
+ <key>CFBundleIconFile</key>
58
+ <string>aivin</string>
59
+ <key>CFBundlePackageType</key>
60
+ <string>APPL</string>
61
+ <key>CFBundleShortVersionString</key>
62
+ <string>1.0.0</string>
63
+ <key>CFBundleVersion</key>
64
+ <string>1</string>
65
+ <key>LSUIElement</key>
66
+ <true/>
67
+ <key>LSMinimumSystemVersion</key>
68
+ <string>10.13</string>
69
+ <key>NSHighResolutionCapable</key>
70
+ <true/>
71
+ </dict>
72
+ </plist>
73
+ `;
74
+ }
75
+
76
+ export const MAC_APP_LAUNCHER = `#!/bin/sh
77
+ # Aivin menu bar app: the menu bar icon + keeps \`aivin remote start\` running (Resources/tray.js, JavaScript for Automation).
78
+ exec /usr/bin/osascript -l JavaScript "$(dirname "$0")/../Resources/tray.js" "$@"
79
+ `;
80
+
81
+ /** LaunchAgent: mở app lúc đăng nhập (chỉ phiên có màn hình), mở lại khi app sập (thoát khác 0); Thoát ở menu = mã 0 → không mở lại. */
82
+ export function macAgentPlist({ app = macAppPath(), logFile = path.join(REMOTE_CONFIG_DIR, 'remote-service.log') } = {}) {
83
+ return `<?xml version="1.0" encoding="UTF-8"?>
84
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
85
+ <plist version="1.0">
86
+ <dict>
87
+ <key>Label</key>
88
+ <string>${MAC_AGENT_LABEL}</string>
89
+ <key>ProgramArguments</key>
90
+ <array>
91
+ <string>${xml(macAppExecutable(app))}</string>
92
+ <string>--autostart</string>
93
+ </array>
94
+ <key>AssociatedBundleIdentifiers</key>
95
+ <array>
96
+ <string>${MAC_BUNDLE_ID}</string>
97
+ </array>
98
+ <key>RunAtLoad</key>
99
+ <true/>
100
+ <key>KeepAlive</key>
101
+ <dict>
102
+ <key>SuccessfulExit</key>
103
+ <false/>
104
+ </dict>
105
+ <key>ThrottleInterval</key>
106
+ <integer>10</integer>
107
+ <key>LimitLoadToSessionType</key>
108
+ <string>Aqua</string>
109
+ <key>ProcessType</key>
110
+ <string>Interactive</string>
111
+ <key>StandardOutPath</key>
112
+ <string>${xml(logFile)}</string>
113
+ <key>StandardErrorPath</key>
114
+ <string>${xml(logFile)}</string>
115
+ </dict>
116
+ </plist>
117
+ `;
118
+ }
119
+
120
+ export function macTraySource(home = REMOTE_CONFIG_DIR) {
121
+ return MAC_TRAY_JS.replace('@@HOME@@', JSON.stringify(home));
122
+ }
123
+
124
+ /** Dựng / làm mới Aivin.app (ghi đè cả gói: mã + biểu tượng đổi theo bản CLI), báo LaunchServices để Spotlight thấy ngay. */
125
+ export function writeMacApp({ app = macAppPath(), home = REMOTE_CONFIG_DIR } = {}) {
126
+ const contents = path.join(app, 'Contents');
127
+ fs.mkdirSync(path.join(contents, 'MacOS'), { recursive: true });
128
+ fs.mkdirSync(path.join(contents, 'Resources'), { recursive: true });
129
+ fs.writeFileSync(path.join(contents, 'Info.plist'), macInfoPlist());
130
+ fs.writeFileSync(path.join(contents, 'Resources', 'tray.js'), macTraySource(home));
131
+ fs.writeFileSync(path.join(contents, 'Resources', 'aivin.icns'), pngToIcns(Buffer.from(AIVIN_LOGO_PNG_BASE64, 'base64')));
132
+ const exe = macAppExecutable(app);
133
+ fs.writeFileSync(exe, MAC_APP_LAUNCHER, { mode: 0o755 });
134
+ fs.chmodSync(exe, 0o755);
135
+ const lsregister = '/System/Library/Frameworks/CoreServices.framework/Frameworks/LaunchServices.framework/Support/lsregister';
136
+ try { execFileSync(lsregister, ['-f', app], { stdio: 'ignore', timeout: 15_000 }); } catch { /* Spotlight tự lập chỉ mục sau */ }
137
+ return app;
138
+ }
139
+
140
+ export function macStartupState() {
141
+ const registered = fs.existsSync(macAgentPath());
142
+ return { registered, enabled: registered };
143
+ }
144
+
145
+ export function setMacStartup(enabled) {
146
+ if (enabled) fs.copyFileSync(AGENT_COPY_FILE, macAgentPath());
147
+ else fs.rmSync(macAgentPath(), { force: true });
148
+ }
149
+
150
+ /** `open` qua LaunchServices: app độc lập với cửa sổ terminal; đang chạy thì macOS gửi "mở lại" → app mở Aivin. */
151
+ export function launchMacTray({ app = macAppPath(), mode = TrayLaunch.OPEN } = {}) {
152
+ const args = mode === TrayLaunch.OPEN ? [app] : [app, '--args', `--${mode}`];
153
+ spawn('/usr/bin/open', args, { detached: true, stdio: 'ignore' }).unref();
154
+ }
155
+
156
+ /** `runScript` = aivin-remote-run.sh (autoStart.mjs ghi, dấu supervisor = tray) — app chạy nó, kèm `--code` khi kết nối bằng mã. */
157
+ export function installMacDesktop({ runScript, lang = 'en', autostart = true, launch = true, launchMode = TrayLaunch.INSTALLED }) {
158
+ fs.mkdirSync(DESKTOP_DIR, { recursive: true });
159
+ const agent = macAgentPath();
160
+ fs.writeFileSync(LAUNCH_CONFIG_FILE, launchConfigText({ argv: ['/bin/sh', runScript], lang, platform: 'darwin', extra: { agent, agent_copy: AGENT_COPY_FILE } }));
161
+ fs.writeFileSync(path.join(DESKTOP_DIR, 'logo.png'), Buffer.from(AIVIN_LOGO_PNG_BASE64, 'base64'));
162
+ const app = writeMacApp();
163
+ fs.writeFileSync(AGENT_COPY_FILE, macAgentPlist({ app }));
164
+ if (autostart) {
165
+ fs.mkdirSync(path.dirname(agent), { recursive: true });
166
+ setMacStartup(true);
167
+ }
168
+ if (launch) launchMacTray({ app, mode: launchMode });
169
+ return { exe: app, shortcut: app, built: true, autostart: macStartupState().enabled };
170
+ }
171
+
172
+ export function isMacDesktopInstalled() {
173
+ return fs.existsSync(macAppExecutable()) && fs.existsSync(LAUNCH_CONFIG_FILE);
174
+ }
175
+
176
+ /** Gỡ: bảo app thoát (dừng daemon nó giữ), xoá LaunchAgent, Aivin.app, desktop\. */
177
+ export function uninstallMacDesktop({ wait = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) } = {}) {
178
+ const exe = macAppExecutable();
179
+ if (fs.existsSync(exe)) {
180
+ try { execFileSync(exe, ['--quit'], { stdio: 'ignore', timeout: 15_000 }); } catch { /* không chạy */ }
181
+ wait(3000);
182
+ }
183
+ fs.rmSync(macAgentPath(), { force: true });
184
+ fs.rmSync(macAppPath(), { recursive: true, force: true });
185
+ fs.rmSync(DESKTOP_DIR, { recursive: true, force: true });
186
+ return { removed: !fs.existsSync(macAppPath()) };
187
+ }