@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.
Files changed (63) hide show
  1. package/README.md +41 -0
  2. package/bin/assets/aivin-mascot.png +0 -0
  3. package/bin/cli.mjs +1979 -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 +187 -37
  9. package/bin/lib/remote/callLedger.mjs +74 -15
  10. package/bin/lib/remote/cdpPolicy.mjs +14 -1
  11. package/bin/lib/remote/client.mjs +174 -11
  12. package/bin/lib/remote/clipboard.mjs +138 -0
  13. package/bin/lib/remote/cloudFiles.mjs +53 -0
  14. package/bin/lib/remote/codingAgents.mjs +293 -0
  15. package/bin/lib/remote/constants.mjs +78 -0
  16. package/bin/lib/remote/dailyBrowser.mjs +9 -3
  17. package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
  18. package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
  19. package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
  20. package/bin/lib/remote/desktop/index.mjs +309 -0
  21. package/bin/lib/remote/desktop/linux.mjs +144 -0
  22. package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -0
  23. package/bin/lib/remote/desktop/mac.mjs +187 -0
  24. package/bin/lib/remote/desktop/macTraySource.mjs +295 -0
  25. package/bin/lib/remote/desktop/strings.mjs +74 -0
  26. package/bin/lib/remote/desktop/traySource.mjs +541 -0
  27. package/bin/lib/remote/deviceProfile.mjs +1 -0
  28. package/bin/lib/remote/docText.mjs +86 -1
  29. package/bin/lib/remote/fileIndexer.mjs +757 -399
  30. package/bin/lib/remote/folderRules.mjs +140 -0
  31. package/bin/lib/remote/gui/index.mjs +208 -18
  32. package/bin/lib/remote/gui/windowsHost.mjs +9 -2
  33. package/bin/lib/remote/gui/windowsHostSource.mjs +444 -49
  34. package/bin/lib/remote/idempotency.mjs +50 -21
  35. package/bin/lib/remote/localPolicy.mjs +17 -4
  36. package/bin/lib/remote/mascot/adpcm.mjs +70 -0
  37. package/bin/lib/remote/mascot/ask.mjs +768 -0
  38. package/bin/lib/remote/mascot/askHostSource.mjs +530 -0
  39. package/bin/lib/remote/mascot/assets.mjs +825 -216
  40. package/bin/lib/remote/mascot/bot.mjs +397 -0
  41. package/bin/lib/remote/mascot/hostSource.mjs +500 -103
  42. package/bin/lib/remote/mascot/hotkey.mjs +66 -0
  43. package/bin/lib/remote/mascot/index.mjs +199 -28
  44. package/bin/lib/remote/mascot/labels.mjs +2 -3
  45. package/bin/lib/remote/mascot/rigSource.mjs +614 -0
  46. package/bin/lib/remote/mascot/strings.mjs +204 -18
  47. package/bin/lib/remote/mascot/ui.mjs +104 -0
  48. package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
  49. package/bin/lib/remote/meeting/index.mjs +415 -0
  50. package/bin/lib/remote/meeting/recorder.mjs +109 -0
  51. package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
  52. package/bin/lib/remote/meeting/transcribe.mjs +259 -0
  53. package/bin/lib/remote/osSearch.mjs +107 -0
  54. package/bin/lib/remote/sqliteDb.mjs +51 -0
  55. package/bin/lib/remote/tabGroups.mjs +209 -0
  56. package/bin/lib/remote/toolHandlers.mjs +788 -726
  57. package/bin/lib/remoteControl.mjs +26 -26
  58. package/docs/AIVIN_MASCOT.md +130 -0
  59. package/docs/CLI.md +1504 -1353
  60. package/docs/media/aivin-mascot-live.gif +0 -0
  61. package/docs/media/aivin-mascot-live.png +0 -0
  62. package/docs/media/aivin-remote-architecture.svg +102 -0
  63. package/package.json +71 -71
@@ -0,0 +1,434 @@
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
+ # Listener sập: mở lại sau 2 s, rồi gấp đôi (tối đa 5 phút) nếu sập liên tục.
21
+ FIRST_DELAY = 2
22
+ LOCK = os.path.join(HOME, 'remote-daemon.lock')
23
+ PAUSED = os.path.join(HOME, 'remote-paused')
24
+ DESK = os.path.join(HOME, 'desktop')
25
+ CFG = os.path.join(DESK, 'launch.cfg')
26
+ LOGO = os.path.join(DESK, 'logo.png')
27
+ LOGO_GREY = os.path.join(DESK, 'logo-grey.png')
28
+ TRAY_LOCK = os.path.join(DESK, 'tray.lock')
29
+ OPEN_REQ = os.path.join(DESK, 'open-request')
30
+ QUIT_REQ = os.path.join(DESK, 'quit-request')
31
+ RESTART_CODE = 75
32
+
33
+
34
+ def load_cfg():
35
+ cfg = {'exe': None, 'args': [], 's': {}, 'extra': {}}
36
+ try:
37
+ with open(CFG, encoding='utf-8') as f:
38
+ for line in f.read().splitlines():
39
+ k, sep, v = line.partition('=')
40
+ if not sep or not k:
41
+ continue
42
+ if k == 'exe':
43
+ cfg['exe'] = v
44
+ elif k == 'arg':
45
+ cfg['args'].append(v)
46
+ elif k.startswith('s.'):
47
+ cfg['s'][k[2:]] = v
48
+ else:
49
+ cfg['extra'][k] = v
50
+ except OSError:
51
+ pass
52
+ return cfg
53
+
54
+
55
+ def mtime(path):
56
+ try:
57
+ return os.stat(path).st_mtime
58
+ except OSError:
59
+ return 0
60
+
61
+
62
+ def touch(path):
63
+ with open(path, 'w') as f:
64
+ f.write(str(time.time()))
65
+
66
+
67
+ def notify(text):
68
+ if shutil.which('notify-send'):
69
+ subprocess.Popen(['notify-send', '-i', LOGO, 'AIVIN Bot', text], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
70
+
71
+
72
+ def pid_alive(pid):
73
+ try:
74
+ os.kill(pid, 0)
75
+ return True
76
+ except PermissionError:
77
+ return True
78
+ except (OSError, ValueError):
79
+ return False
80
+
81
+
82
+ class Supervisor:
83
+ def __init__(self):
84
+ self.cfg = load_cfg()
85
+ self.child = None
86
+ self.child_pid = 0
87
+ self.started = 0
88
+ self.next_start = 0
89
+ self.delay = FIRST_DELAY
90
+ self.pairing = False
91
+ self.was_paired = os.path.exists(CREDS)
92
+ self.seen_open = mtime(OPEN_REQ)
93
+ self.seen_quit = mtime(QUIT_REQ)
94
+ self.on_open = None
95
+ self.on_quit = None
96
+
97
+ def t(self, key):
98
+ return self.cfg['s'].get(key, key)
99
+
100
+ def lock_held(self):
101
+ try:
102
+ with open(LOCK, encoding='utf-8') as f:
103
+ d = json.load(f)
104
+ pid = int(d.get('pid') or 0)
105
+ if self.child is None and pid == self.child_pid:
106
+ return False
107
+ beat = str(d.get('beat_at') or d.get('started_at') or '')
108
+ if beat:
109
+ at = calendar.timegm(time.strptime(beat[:19], '%Y-%m-%dT%H:%M:%S'))
110
+ if time.time() - at > 90:
111
+ return False
112
+ return pid > 0 and pid_alive(pid)
113
+ except (OSError, ValueError):
114
+ return False
115
+
116
+ def running(self):
117
+ return (self.child is not None and self.child.poll() is None) or self.lock_held()
118
+
119
+ def backoff(self):
120
+ self.next_start = time.time() + self.delay
121
+ self.delay = min(self.delay * 2, 300)
122
+
123
+ def start(self, code=None):
124
+ self.cfg = load_cfg()
125
+ if not self.cfg['exe']:
126
+ return
127
+ args = [self.cfg['exe']] + self.cfg['args'] + (['--code', code] if code else [])
128
+ try:
129
+ self.child = subprocess.Popen(args, cwd=os.path.expanduser('~'), stdin=subprocess.DEVNULL, start_new_session=True)
130
+ self.child_pid = self.child.pid
131
+ self.started = time.time()
132
+ self.pairing = bool(code)
133
+ except OSError:
134
+ self.child = None
135
+ self.backoff()
136
+
137
+ def on_exit(self, rc):
138
+ secs = time.time() - self.started
139
+ self.child = None
140
+ was_pairing, self.pairing = self.pairing, False
141
+ if was_pairing and not os.path.exists(CREDS):
142
+ notify(self.t('pairFailed'))
143
+ return
144
+ if rc == 0:
145
+ # Dừng có chủ đích (thu hồi, ghép lại, cửa sổ khác nhận việc): chờ ngắn; thoát 0 liền nhau (hai máy chung token) thì giãn dần.
146
+ if secs < 30:
147
+ self.backoff()
148
+ else:
149
+ self.delay = FIRST_DELAY
150
+ self.next_start = time.time() + FIRST_DELAY
151
+ elif rc == RESTART_CODE:
152
+ self.next_start = time.time() + 1
153
+ else:
154
+ if secs > 300:
155
+ self.delay = FIRST_DELAY
156
+ self.backoff()
157
+
158
+ def kill(self):
159
+ c, self.child = self.child, None
160
+ if c is None or c.poll() is not None:
161
+ return
162
+ try:
163
+ os.killpg(c.pid, signal.SIGTERM)
164
+ c.wait(timeout=10)
165
+ except (OSError, subprocess.TimeoutExpired):
166
+ try:
167
+ os.killpg(c.pid, signal.SIGKILL)
168
+ except OSError:
169
+ pass
170
+
171
+ def start_now(self):
172
+ if self.child is None and not self.lock_held():
173
+ self.next_start = 0
174
+ self.delay = FIRST_DELAY
175
+
176
+ def tick(self):
177
+ if mtime(QUIT_REQ) > self.seen_quit:
178
+ self.seen_quit = mtime(QUIT_REQ)
179
+ if self.on_quit:
180
+ self.on_quit()
181
+ return
182
+ if self.child is not None:
183
+ rc = self.child.poll()
184
+ if rc is not None:
185
+ self.on_exit(rc)
186
+ paired = os.path.exists(CREDS)
187
+ if paired and not self.was_paired:
188
+ notify(self.t('connected'))
189
+ self.was_paired = paired
190
+ if self.child is None and paired and time.time() >= self.next_start and not self.lock_held():
191
+ self.start()
192
+ req = mtime(OPEN_REQ)
193
+ if req > self.seen_open:
194
+ self.seen_open = req
195
+ if self.on_open:
196
+ self.on_open()
197
+
198
+
199
+ def startup_file(sup):
200
+ return sup.cfg['extra'].get('autostart')
201
+
202
+
203
+ def startup_enabled(sup):
204
+ path = startup_file(sup)
205
+ try:
206
+ with open(path, encoding='utf-8') as f:
207
+ text = f.read()
208
+ except (OSError, TypeError):
209
+ return False
210
+ return 'Hidden=true' not in text and 'X-GNOME-Autostart-enabled=false' not in text
211
+
212
+
213
+ def set_startup(sup, on):
214
+ path, copy = startup_file(sup), sup.cfg['extra'].get('autostart_copy')
215
+ if not path:
216
+ return
217
+ try:
218
+ if on:
219
+ os.makedirs(os.path.dirname(path), exist_ok=True)
220
+ shutil.copyfile(copy, path)
221
+ elif os.path.exists(path):
222
+ with open(path, encoding='utf-8') as f:
223
+ text = f.read()
224
+ text = text.replace('X-GNOME-Autostart-enabled=true', 'X-GNOME-Autostart-enabled=false').replace('Hidden=false', 'Hidden=true')
225
+ with open(path, 'w', encoding='utf-8') as f:
226
+ f.write(text)
227
+ except OSError:
228
+ pass
229
+
230
+
231
+ def gtk_ui(sup):
232
+ """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)."""
233
+ if not (os.environ.get('DISPLAY') or os.environ.get('WAYLAND_DISPLAY')):
234
+ return None
235
+ try:
236
+ import gi
237
+ gi.require_version('Gtk', '3.0')
238
+ gi.require_version('GdkPixbuf', '2.0')
239
+ try:
240
+ gi.require_version('AyatanaAppIndicator3', '0.1')
241
+ from gi.repository import AyatanaAppIndicator3 as AppIndicator
242
+ except (ValueError, ImportError):
243
+ gi.require_version('AppIndicator3', '0.1')
244
+ from gi.repository import AppIndicator3 as AppIndicator
245
+ from gi.repository import GdkPixbuf, GLib, Gtk
246
+ except (ImportError, ValueError):
247
+ return None
248
+
249
+ try:
250
+ pb = GdkPixbuf.Pixbuf.new_from_file(LOGO)
251
+ grey = pb.copy()
252
+ pb.saturate_and_pixelate(grey, 0.0, False)
253
+ grey.save(LOGO_GREY, 'png')
254
+ except Exception:
255
+ pass
256
+
257
+ t = sup.t
258
+ ind = AppIndicator.Indicator.new('aivin', LOGO, AppIndicator.IndicatorCategory.APPLICATION_STATUS)
259
+ ind.set_status(AppIndicator.IndicatorStatus.ACTIVE)
260
+ ind.set_title('AIVIN Bot')
261
+ menu = Gtk.Menu()
262
+ status = Gtk.MenuItem(label='AIVIN Bot')
263
+ status.set_sensitive(False)
264
+ connect = Gtk.MenuItem(label=t('connect'))
265
+ pause = Gtk.MenuItem(label=t('pause'))
266
+ startup = Gtk.CheckMenuItem(label=t('startup'))
267
+ folder = Gtk.MenuItem(label=t('folder'))
268
+ quit_item = Gtk.MenuItem(label=t('quit'))
269
+ for item in (status, Gtk.SeparatorMenuItem(), connect, pause, startup, folder, Gtk.SeparatorMenuItem(), quit_item):
270
+ menu.append(item)
271
+ state = {'icon': None, 'syncing': False, 'dialog': False}
272
+
273
+ def refresh():
274
+ paired, paused, up = os.path.exists(CREDS), os.path.exists(PAUSED), sup.running()
275
+ 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')
276
+ status.set_label(text)
277
+ icon = LOGO if paired and up and not paused else (LOGO_GREY if os.path.exists(LOGO_GREY) else LOGO)
278
+ if icon != state['icon']:
279
+ state['icon'] = icon
280
+ ind.set_icon_full(icon, 'Aivin - ' + text)
281
+ connect.set_visible(not paired)
282
+ pause.set_label(t('resume' if paused else 'pause'))
283
+ pause.set_visible(paired)
284
+ state['syncing'] = True
285
+ startup.set_active(startup_enabled(sup))
286
+ state['syncing'] = False
287
+
288
+ def ask_code(*_):
289
+ if state['dialog']:
290
+ return
291
+ state['dialog'] = True
292
+ d = Gtk.Dialog(title='AIVIN Bot')
293
+ d.add_buttons(t('pairCancel'), Gtk.ResponseType.CANCEL, t('pairOk'), Gtk.ResponseType.OK)
294
+ d.set_default_response(Gtk.ResponseType.OK)
295
+ d.set_keep_above(True)
296
+ box = d.get_content_area()
297
+ box.set_spacing(10)
298
+ box.set_border_width(14)
299
+ label = Gtk.Label(label=t('pairPrompt'))
300
+ label.set_line_wrap(True)
301
+ label.set_max_width_chars(48)
302
+ entry = Gtk.Entry()
303
+ entry.set_activates_default(True)
304
+ box.pack_start(label, False, False, 0)
305
+ box.pack_start(entry, False, False, 0)
306
+ d.show_all()
307
+ response = d.run()
308
+ code = entry.get_text().strip().upper()
309
+ d.destroy()
310
+ state['dialog'] = False
311
+ if response == Gtk.ResponseType.OK and code:
312
+ sup.kill()
313
+ sup.start(code)
314
+ refresh()
315
+
316
+ def toggle_pause(*_):
317
+ try:
318
+ if os.path.exists(PAUSED):
319
+ os.remove(PAUSED)
320
+ else:
321
+ with open(PAUSED, 'w') as f:
322
+ f.write(time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime()))
323
+ except OSError:
324
+ pass
325
+ refresh()
326
+
327
+ def toggle_startup(item):
328
+ if not state['syncing']:
329
+ set_startup(sup, item.get_active())
330
+ refresh()
331
+
332
+ def open_folder(*_):
333
+ opener = shutil.which('xdg-open')
334
+ if opener:
335
+ subprocess.Popen([opener, HOME], stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
336
+
337
+ def quit_app(*_):
338
+ sup.kill()
339
+ Gtk.main_quit()
340
+
341
+ def open_aivin():
342
+ if not os.path.exists(CREDS):
343
+ ask_code()
344
+ else:
345
+ sup.start_now()
346
+ notify(t('running') if sup.running() else t('stopped'))
347
+
348
+ connect.connect('activate', ask_code)
349
+ pause.connect('activate', toggle_pause)
350
+ startup.connect('toggled', toggle_startup)
351
+ folder.connect('activate', open_folder)
352
+ quit_item.connect('activate', quit_app)
353
+ menu.show_all()
354
+ ind.set_menu(menu)
355
+ sup.on_open = open_aivin
356
+ sup.on_quit = quit_app
357
+
358
+ def on_tick():
359
+ sup.tick()
360
+ refresh()
361
+ return True
362
+
363
+ GLib.timeout_add_seconds(2, on_tick)
364
+ refresh()
365
+
366
+ class Ui:
367
+ open = staticmethod(open_aivin)
368
+
369
+ @staticmethod
370
+ def run():
371
+ Gtk.main()
372
+ return Ui
373
+
374
+
375
+ def main(argv):
376
+ import fcntl
377
+ os.makedirs(DESK, exist_ok=True)
378
+ lock = open(TRAY_LOCK, 'w')
379
+ try:
380
+ fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
381
+ except OSError:
382
+ # Đã có một bản chạy: mở lần nữa = mở Aivin; --quit = bảo bản đó thoát.
383
+ if '--quit' in argv:
384
+ touch(QUIT_REQ)
385
+ elif '--autostart' not in argv and '--installed' not in argv:
386
+ touch(OPEN_REQ)
387
+ return 0
388
+ if '--quit' in argv:
389
+ return 0
390
+ sup = Supervisor()
391
+ signal.signal(signal.SIGTERM, lambda *_: (sup.kill(), sys.exit(0)))
392
+ ui = gtk_ui(sup)
393
+ sup.tick()
394
+ if ui is None:
395
+ stop = []
396
+ sup.on_quit = lambda: (sup.kill(), stop.append(True))
397
+ while not stop:
398
+ time.sleep(2)
399
+ sup.tick()
400
+ return 0
401
+ if '--installed' in argv:
402
+ notify(sup.t('firstRun' if sup.was_paired else 'connectHint'))
403
+ elif '--autostart' not in argv:
404
+ ui.open()
405
+ ui.run()
406
+ return 0
407
+
408
+
409
+ if __name__ == '__main__':
410
+ sys.exit(main(sys.argv[1:]))
411
+ `;
412
+
413
+ /**
414
+ * 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ì
415
+ * 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.
416
+ */
417
+ export const LINUX_LAUNCHER_SH = `#!/bin/sh
418
+ # Aivin desktop app (Linux): tray icon + keeps \`aivin remote start\` running (tray.py); without python3, keeps it running without an icon.
419
+ exec >>@@LOG@@ 2>&1
420
+ if command -v python3 >/dev/null 2>&1; then exec python3 @@TRAY@@ "$@"; fi
421
+ case " $* " in *" --quit "*) exit 0 ;; esac
422
+ delay=10
423
+ while [ -f @@CREDS@@ ]; do
424
+ started=$(date +%s)
425
+ /bin/sh @@RUN@@
426
+ rc=$?
427
+ [ "$rc" -eq 0 ] && exit 0
428
+ if [ "$rc" -eq 75 ]; then sleep 1; continue; fi
429
+ [ $(( $(date +%s) - started )) -gt 300 ] && delay=10
430
+ sleep "$delay"
431
+ delay=$(( delay * 2 ))
432
+ [ "$delay" -gt 300 ] && delay=300
433
+ done
434
+ `;
@@ -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</string>
51
+ <key>CFBundleDisplayName</key>
52
+ <string>AIVIN Bot</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
+ }