@aivin-labs/cli 1.0.11 → 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 (41) hide show
  1. package/README.md +16 -0
  2. package/bin/cli.mjs +67 -0
  3. package/bin/lib/remote/browserTunnel.mjs +47 -8
  4. package/bin/lib/remote/callLedger.mjs +73 -14
  5. package/bin/lib/remote/client.mjs +89 -8
  6. package/bin/lib/remote/cloudFiles.mjs +53 -0
  7. package/bin/lib/remote/constants.mjs +17 -0
  8. package/bin/lib/remote/dailyBrowser.mjs +8 -2
  9. package/bin/lib/remote/desktop/desktopCast.mjs +198 -0
  10. package/bin/lib/remote/desktop/desktopCastSource.mjs +514 -0
  11. package/bin/lib/remote/desktop/desktopWebRtc.mjs +95 -0
  12. package/bin/lib/remote/desktop/index.mjs +44 -7
  13. package/bin/lib/remote/desktop/linux.mjs +1 -1
  14. package/bin/lib/remote/desktop/linuxTraySource.mjs +434 -427
  15. package/bin/lib/remote/desktop/mac.mjs +2 -2
  16. package/bin/lib/remote/desktop/macTraySource.mjs +295 -292
  17. package/bin/lib/remote/desktop/traySource.mjs +541 -527
  18. package/bin/lib/remote/deviceProfile.mjs +1 -0
  19. package/bin/lib/remote/docText.mjs +85 -0
  20. package/bin/lib/remote/fileIndexer.mjs +757 -399
  21. package/bin/lib/remote/folderRules.mjs +140 -0
  22. package/bin/lib/remote/gui/index.mjs +126 -17
  23. package/bin/lib/remote/gui/windowsHost.mjs +9 -2
  24. package/bin/lib/remote/gui/windowsHostSource.mjs +194 -51
  25. package/bin/lib/remote/idempotency.mjs +49 -20
  26. package/bin/lib/remote/localPolicy.mjs +8 -2
  27. package/bin/lib/remote/mascot/askHostSource.mjs +18 -0
  28. package/bin/lib/remote/mascot/bot.mjs +29 -4
  29. package/bin/lib/remote/mascot/hostSource.mjs +4 -4
  30. package/bin/lib/remote/mascot/rigSource.mjs +12 -7
  31. package/bin/lib/remote/osSearch.mjs +107 -0
  32. package/bin/lib/remote/sqliteDb.mjs +51 -0
  33. package/bin/lib/remote/toolHandlers.mjs +788 -741
  34. package/bin/lib/remoteControl.mjs +26 -26
  35. package/docs/AIVIN_MASCOT.md +14 -0
  36. package/docs/CLI.md +1504 -1484
  37. package/docs/media/aivin-mascot-live.gif +0 -0
  38. package/docs/media/aivin-mascot-live.png +0 -0
  39. package/docs/media/aivin-remote-architecture.svg +102 -0
  40. package/package.json +71 -71
  41. package/docs/media/aivin-mascot-states.mp4 +0 -0
@@ -1,427 +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
- 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
- `;
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
+ `;