@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.
- package/README.md +288 -216
- package/bin/assets/aivin-mascot.png +0 -0
- package/bin/cli.mjs +551 -5
- package/bin/lib/browserAutomation.mjs +384 -614
- package/bin/lib/browserTui.mjs +276 -251
- package/bin/lib/cancellation.mjs +61 -0
- package/bin/lib/localBrowser.mjs +345 -0
- package/bin/lib/mcpProxy.mjs +869 -837
- package/bin/lib/missionStream.mjs +696 -691
- package/bin/lib/releaseKeys.mjs +9 -0
- package/bin/lib/remote/activityLog.mjs +68 -0
- package/bin/lib/remote/autoStart.mjs +617 -0
- package/bin/lib/remote/autoUpdate.mjs +129 -0
- package/bin/lib/remote/brand.mjs +60 -0
- package/bin/lib/remote/browserTunnel.mjs +403 -0
- package/bin/lib/remote/callLedger.mjs +134 -0
- package/bin/lib/remote/cdpPolicy.mjs +79 -0
- package/bin/lib/remote/client.mjs +808 -0
- package/bin/lib/remote/clipboard.mjs +138 -0
- package/bin/lib/remote/codingAgents.mjs +293 -0
- package/bin/lib/remote/constants.mjs +234 -0
- package/bin/lib/remote/credentials.mjs +208 -0
- package/bin/lib/remote/daemonLock.mjs +86 -0
- package/bin/lib/remote/dailyBrowser.mjs +371 -0
- package/bin/lib/remote/desktop/index.mjs +272 -0
- package/bin/lib/remote/desktop/linux.mjs +144 -0
- package/bin/lib/remote/desktop/linuxTraySource.mjs +427 -0
- package/bin/lib/remote/desktop/mac.mjs +187 -0
- package/bin/lib/remote/desktop/macTraySource.mjs +292 -0
- package/bin/lib/remote/desktop/strings.mjs +74 -0
- package/bin/lib/remote/desktop/traySource.mjs +527 -0
- package/bin/lib/remote/deviceMemory.mjs +246 -0
- package/bin/lib/remote/deviceProfile.mjs +142 -0
- package/bin/lib/remote/deviceWatches.mjs +138 -0
- package/bin/lib/remote/docText.mjs +117 -0
- package/bin/lib/remote/fileIndexer.mjs +399 -0
- package/bin/lib/remote/gui/index.mjs +326 -0
- package/bin/lib/remote/gui/officeHostSource.mjs +393 -0
- package/bin/lib/remote/gui/windowsHost.mjs +109 -0
- package/bin/lib/remote/gui/windowsHostSource.mjs +1156 -0
- package/bin/lib/remote/httpTransfer.mjs +89 -0
- package/bin/lib/remote/idempotency.mjs +135 -0
- package/bin/lib/remote/keepAwake.mjs +100 -0
- package/bin/lib/remote/localConfirm.mjs +268 -0
- package/bin/lib/remote/localPolicy.mjs +256 -0
- package/bin/lib/remote/mascot/adpcm.mjs +70 -0
- package/bin/lib/remote/mascot/ask.mjs +768 -0
- package/bin/lib/remote/mascot/askHostSource.mjs +512 -0
- package/bin/lib/remote/mascot/assets.mjs +827 -0
- package/bin/lib/remote/mascot/bot.mjs +372 -0
- package/bin/lib/remote/mascot/hostSource.mjs +759 -0
- package/bin/lib/remote/mascot/hotkey.mjs +66 -0
- package/bin/lib/remote/mascot/index.mjs +493 -0
- package/bin/lib/remote/mascot/labels.mjs +82 -0
- package/bin/lib/remote/mascot/rigSource.mjs +609 -0
- package/bin/lib/remote/mascot/strings.mjs +375 -0
- package/bin/lib/remote/mascot/ui.mjs +104 -0
- package/bin/lib/remote/mascot/voiceSource.mjs +584 -0
- package/bin/lib/remote/meeting/index.mjs +415 -0
- package/bin/lib/remote/meeting/recorder.mjs +109 -0
- package/bin/lib/remote/meeting/recorderSource.mjs +394 -0
- package/bin/lib/remote/meeting/transcribe.mjs +259 -0
- package/bin/lib/remote/memberFsPool.mjs +134 -0
- package/bin/lib/remote/memberFsWorker.mjs +60 -0
- package/bin/lib/remote/mission.mjs +156 -0
- package/bin/lib/remote/missionQuestion.mjs +63 -0
- package/bin/lib/remote/multiUser.mjs +344 -0
- package/bin/lib/remote/netProxy.mjs +145 -0
- package/bin/lib/remote/notify.mjs +58 -0
- package/bin/lib/remote/office/index.mjs +90 -0
- package/bin/lib/remote/policyCommand.mjs +93 -0
- package/bin/lib/remote/processes.mjs +217 -0
- package/bin/lib/remote/sandbox.mjs +221 -0
- package/bin/lib/remote/schedule.mjs +213 -0
- package/bin/lib/remote/scheduler.mjs +124 -0
- package/bin/lib/remote/tabGroups.mjs +209 -0
- package/bin/lib/remote/textIndex.mjs +131 -0
- package/bin/lib/remote/tokenStore.mjs +77 -0
- package/bin/lib/remote/toolHandlers.mjs +741 -0
- package/bin/lib/remote/undoStore.mjs +242 -0
- package/bin/lib/remoteControl.mjs +26 -0
- package/bin/lib/scaffold.mjs +654 -653
- package/bin/lib/selfUpdate.mjs +71 -0
- package/bin/lib/update/binarySwap.mjs +63 -0
- package/bin/lib/update/constants.mjs +56 -0
- package/bin/lib/update/download.mjs +145 -0
- package/bin/lib/update/signature.mjs +42 -0
- package/bin/lib/update/state.mjs +205 -0
- package/bin/lib/update/versions.mjs +60 -0
- package/docs/AIVIN_MASCOT.md +116 -0
- package/docs/CLI.md +1484 -1299
- package/docs/media/aivin-mascot-states.mp4 +0 -0
- package/package.json +71 -62
|
@@ -0,0 +1,144 @@
|
|
|
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 { LINUX_LAUNCHER_SH, LINUX_TRAY_PY } from './linuxTraySource.mjs';
|
|
9
|
+
import { trayStrings } from './strings.mjs';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Aivin trên màn hình Linux (29/10/2026): mục "Aivin" trong menu ứng dụng (~/.local/share/applications — GNOME Activities, KDE, XFCE…
|
|
13
|
+
* tìm được), tự khởi động bằng ~/.config/autostart/aivin.desktop — "Startup Applications" (GNOME), Autostart (KDE)… liệt kê và bật / tắt
|
|
14
|
+
* được; một cơ chế duy nhất (bản cũ ghi aivin-remote.desktop chạy thẳng daemon, gỡ khi cài). Khay: linuxTraySource.mjs.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const dataHome = (env = process.env) => env.XDG_DATA_HOME || path.join(os.homedir(), '.local', 'share');
|
|
18
|
+
const configHome = (env = process.env) => env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config');
|
|
19
|
+
export const linuxAppEntryPath = (env) => path.join(dataHome(env), 'applications', 'aivin.desktop');
|
|
20
|
+
export const linuxAutostartPath = (env) => path.join(configHome(env), 'autostart', 'aivin.desktop');
|
|
21
|
+
const LEGACY_AUTOSTART = (env) => path.join(configHome(env), 'autostart', 'aivin-remote.desktop');
|
|
22
|
+
export const LINUX_LAUNCHER_FILE = path.join(DESKTOP_DIR, 'aivin-desktop.sh');
|
|
23
|
+
const TRAY_FILE = path.join(DESKTOP_DIR, 'tray.py');
|
|
24
|
+
const LOGO_FILE = path.join(DESKTOP_DIR, 'logo.png');
|
|
25
|
+
/** Bản sao mục autostart: menu khay bật lại = chép lại (GNOME Tweaks xoá hẳn tệp khi tắt). */
|
|
26
|
+
const AUTOSTART_COPY_FILE = path.join(DESKTOP_DIR, 'autostart.desktop');
|
|
27
|
+
|
|
28
|
+
const shq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
29
|
+
|
|
30
|
+
/** Một đối số của dòng Exec= (Desktop Entry spec): bọc nháy kép, thoát " ` $ \ — rồi thoát \ lần nữa vì giá trị chuỗi cũng thoát \. */
|
|
31
|
+
export function desktopExecArg(s) {
|
|
32
|
+
const quoted = `"${String(s).replace(/(["`$\\])/g, '\\$1')}"`;
|
|
33
|
+
return quoted.replace(/\\/g, '\\\\');
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** Có phiên màn hình (X11 / Wayland) — không có (máy chủ, SSH) thì tự khởi động bằng systemd như trước. */
|
|
37
|
+
export function hasLinuxDesktopSession(env = process.env) {
|
|
38
|
+
return Boolean(env.DISPLAY || env.WAYLAND_DISPLAY || env.XDG_CURRENT_DESKTOP);
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
export function linuxDesktopEntry({ launcher = LINUX_LAUNCHER_FILE, icon = LOGO_FILE, lang = 'en', autostart = false } = {}) {
|
|
42
|
+
const s = trayStrings(lang, 'linux');
|
|
43
|
+
return [
|
|
44
|
+
'[Desktop Entry]',
|
|
45
|
+
'Type=Application',
|
|
46
|
+
'Version=1.0',
|
|
47
|
+
'Name=AIVIN Bot CLI',
|
|
48
|
+
`Comment=${s.shortcut}`,
|
|
49
|
+
`Exec=${desktopExecArg(launcher)}${autostart ? ' --autostart' : ''}`,
|
|
50
|
+
`Icon=${icon}`,
|
|
51
|
+
'Terminal=false',
|
|
52
|
+
'Categories=Utility;Network;',
|
|
53
|
+
'Keywords=aivin;ai;agent;assistant;',
|
|
54
|
+
'StartupNotify=false',
|
|
55
|
+
...(autostart ? ['X-GNOME-Autostart-enabled=true', 'Hidden=false'] : []),
|
|
56
|
+
].join('\n') + '\n';
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export function linuxLauncherScript({ runScript, home = REMOTE_CONFIG_DIR } = {}) {
|
|
60
|
+
return LINUX_LAUNCHER_SH
|
|
61
|
+
.replace('@@LOG@@', shq(path.join(home, 'remote-service.log')))
|
|
62
|
+
.replace('@@TRAY@@', shq(path.join(home, 'desktop', 'tray.py')))
|
|
63
|
+
.replace('@@CREDS@@', shq(path.join(home, 'device-credentials.json')))
|
|
64
|
+
.replace('@@RUN@@', shq(runScript));
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function linuxTraySource(home = REMOTE_CONFIG_DIR) {
|
|
68
|
+
return LINUX_TRAY_PY.replace('@@HOME@@', JSON.stringify(home));
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** Tắt = Hidden=true / X-GNOME-Autostart-enabled=false (như các trình quản lý khởi động ghi), hoặc đã bị xoá. */
|
|
72
|
+
export function isAutostartEnabled(text) {
|
|
73
|
+
if (text == null) return false;
|
|
74
|
+
return !/^Hidden\s*=\s*true\s*$/m.test(text) && !/^X-GNOME-Autostart-enabled\s*=\s*false\s*$/m.test(text);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function linuxStartupState() {
|
|
78
|
+
let text = null;
|
|
79
|
+
try { text = fs.readFileSync(linuxAutostartPath(), 'utf8'); } catch { /* chưa có / đã bị xoá */ }
|
|
80
|
+
return { registered: text != null, enabled: isAutostartEnabled(text) };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
export function setLinuxStartup(enabled) {
|
|
84
|
+
const file = linuxAutostartPath();
|
|
85
|
+
if (enabled) {
|
|
86
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
87
|
+
fs.copyFileSync(AUTOSTART_COPY_FILE, file);
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
let text;
|
|
91
|
+
try { text = fs.readFileSync(file, 'utf8'); } catch { return; }
|
|
92
|
+
fs.writeFileSync(file, text.replace(/^X-GNOME-Autostart-enabled=.*$/m, 'X-GNOME-Autostart-enabled=false').replace(/^Hidden=.*$/m, 'Hidden=true'));
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** python3 + PyGObject + AppIndicator có trên máy không (chỉ để báo ở `aivin desktop`). */
|
|
96
|
+
export function linuxTrayAvailable() {
|
|
97
|
+
const probe = "import gi\ntry:\n gi.require_version('AyatanaAppIndicator3','0.1')\nexcept ValueError:\n gi.require_version('AppIndicator3','0.1')";
|
|
98
|
+
try {
|
|
99
|
+
execFileSync('python3', ['-c', probe], { stdio: 'ignore', timeout: 15_000 });
|
|
100
|
+
return true;
|
|
101
|
+
} catch {
|
|
102
|
+
return false;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
export function launchLinuxTray({ mode = TrayLaunch.OPEN } = {}) {
|
|
107
|
+
const args = mode === TrayLaunch.OPEN ? [] : [`--${mode}`];
|
|
108
|
+
spawn('/bin/sh', [LINUX_LAUNCHER_FILE, ...args], { detached: true, stdio: 'ignore' }).unref();
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
export function installLinuxDesktop({ runScript, lang = 'en', autostart = true, launch = true, launchMode = TrayLaunch.INSTALLED }) {
|
|
112
|
+
fs.mkdirSync(DESKTOP_DIR, { recursive: true });
|
|
113
|
+
const autostartFile = linuxAutostartPath();
|
|
114
|
+
fs.writeFileSync(LAUNCH_CONFIG_FILE, launchConfigText({
|
|
115
|
+
argv: ['/bin/sh', runScript], lang, platform: 'linux', extra: { autostart: autostartFile, autostart_copy: AUTOSTART_COPY_FILE },
|
|
116
|
+
}));
|
|
117
|
+
fs.writeFileSync(LOGO_FILE, Buffer.from(AIVIN_LOGO_PNG_BASE64, 'base64'));
|
|
118
|
+
fs.writeFileSync(TRAY_FILE, linuxTraySource());
|
|
119
|
+
fs.writeFileSync(LINUX_LAUNCHER_FILE, linuxLauncherScript({ runScript }), { mode: 0o755 });
|
|
120
|
+
fs.chmodSync(LINUX_LAUNCHER_FILE, 0o755);
|
|
121
|
+
const entry = linuxAppEntryPath();
|
|
122
|
+
fs.mkdirSync(path.dirname(entry), { recursive: true });
|
|
123
|
+
fs.writeFileSync(entry, linuxDesktopEntry({ lang }));
|
|
124
|
+
fs.writeFileSync(AUTOSTART_COPY_FILE, linuxDesktopEntry({ lang, autostart: true }));
|
|
125
|
+
fs.rmSync(LEGACY_AUTOSTART(), { force: true });
|
|
126
|
+
if (autostart) setLinuxStartup(true);
|
|
127
|
+
try { execFileSync('update-desktop-database', [path.dirname(entry)], { stdio: 'ignore', timeout: 15_000 }); } catch { /* không bắt buộc */ }
|
|
128
|
+
if (launch) launchLinuxTray({ mode: launchMode });
|
|
129
|
+
return { exe: LINUX_LAUNCHER_FILE, shortcut: entry, built: true, autostart: linuxStartupState().enabled };
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
export function isLinuxDesktopInstalled() {
|
|
133
|
+
return fs.existsSync(LINUX_LAUNCHER_FILE) && fs.existsSync(LAUNCH_CONFIG_FILE);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
export function uninstallLinuxDesktop({ wait = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms) } = {}) {
|
|
137
|
+
if (fs.existsSync(LINUX_LAUNCHER_FILE)) {
|
|
138
|
+
try { execFileSync('/bin/sh', [LINUX_LAUNCHER_FILE, '--quit'], { stdio: 'ignore', timeout: 15_000 }); } catch { /* không chạy */ }
|
|
139
|
+
wait(3000);
|
|
140
|
+
}
|
|
141
|
+
for (const file of [linuxAutostartPath(), linuxAppEntryPath()]) fs.rmSync(file, { force: true });
|
|
142
|
+
fs.rmSync(DESKTOP_DIR, { recursive: true, force: true });
|
|
143
|
+
return { removed: true };
|
|
144
|
+
}
|
|
@@ -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
|
+
`;
|