@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,527 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Ứng dụng khay hệ thống Aivin trên Windows (29/10/2026) — `Aivin.exe`, một tệp chạy giao diện (không cửa sổ console) biên dịch trên chính
|
|
3
|
+
* máy người dùng bằng csc của .NET Framework (CodeDom, chỉ cú pháp C# 5: không `$"..."`, không `?.`, không `=>` cho thân hàm). Nó là:
|
|
4
|
+
* - biểu tượng ở khay hệ thống: trạng thái (đang chạy / tạm dừng / chưa kết nối), mở linh vật, tạm dừng, bật / tắt khởi động cùng Windows, thoát;
|
|
5
|
+
* - trình giữ chạy của `aivin remote start` (thay kịch bản VBS): chạy ẩn, mã 0 → thôi tới khi máy rảnh lại, 75 → chạy lại ngay, khác → giãn
|
|
6
|
+
* dần tới 5 phút, tự lùi bản mới sập liên tục (như windowsWatchdogScript);
|
|
7
|
+
* - mục khởi động trong Task Manager → Startup apps (khoá HKCU Run trỏ vào chính nó, tên + biểu tượng lấy từ thông tin phiên bản của tệp).
|
|
8
|
+
* Đọc launch.cfg (desktop/index.mjs) mỗi lần chạy daemon — đổi `--dir` / `--proxy` không cần biên dịch lại. `@@HOME@@` = thư mục cấu hình.
|
|
9
|
+
*/
|
|
10
|
+
export const TRAY_CS = String.raw`using System;
|
|
11
|
+
using System.Collections.Generic;
|
|
12
|
+
using System.Diagnostics;
|
|
13
|
+
using System.Drawing;
|
|
14
|
+
using System.Drawing.Drawing2D;
|
|
15
|
+
using System.Drawing.Imaging;
|
|
16
|
+
using System.Globalization;
|
|
17
|
+
using System.IO;
|
|
18
|
+
using System.Reflection;
|
|
19
|
+
using System.Runtime.InteropServices;
|
|
20
|
+
using System.Text;
|
|
21
|
+
using System.Text.RegularExpressions;
|
|
22
|
+
using System.Threading;
|
|
23
|
+
using System.Windows.Forms;
|
|
24
|
+
using Microsoft.Win32;
|
|
25
|
+
|
|
26
|
+
[assembly: AssemblyTitle("AIVIN Bot CLI")]
|
|
27
|
+
[assembly: AssemblyDescription("Aivin - lets your Aivin agents work on this computer")]
|
|
28
|
+
[assembly: AssemblyCompany("Aivin Labs")]
|
|
29
|
+
[assembly: AssemblyProduct("AIVIN Bot CLI")]
|
|
30
|
+
[assembly: AssemblyCopyright("Aivin Labs")]
|
|
31
|
+
[assembly: AssemblyVersion("@@VERSION@@")]
|
|
32
|
+
[assembly: AssemblyFileVersion("@@VERSION@@")]
|
|
33
|
+
|
|
34
|
+
namespace AivinDesktop {
|
|
35
|
+
static class Program {
|
|
36
|
+
public const string Home = @@HOME@@;
|
|
37
|
+
|
|
38
|
+
[DllImport("user32.dll")]
|
|
39
|
+
static extern bool SetProcessDPIAware();
|
|
40
|
+
|
|
41
|
+
[STAThread]
|
|
42
|
+
static int Main(string[] args) {
|
|
43
|
+
bool autostart = Array.IndexOf(args, "--autostart") >= 0;
|
|
44
|
+
bool installed = Array.IndexOf(args, "--installed") >= 0;
|
|
45
|
+
bool quit = Array.IndexOf(args, "--quit") >= 0;
|
|
46
|
+
string id = ((uint)Home.ToLowerInvariant().GetHashCode()).ToString("x8");
|
|
47
|
+
bool created;
|
|
48
|
+
using (Mutex mutex = new Mutex(true, "Local\\AivinTray-" + id, out created)) {
|
|
49
|
+
if (!created) {
|
|
50
|
+
// Đã có một bản chạy: mở Start menu / Aivin.exe lần nữa = mở Aivin; --quit = bảo bản đó thoát.
|
|
51
|
+
if (quit) Signal("Local\\AivinTrayQuit-" + id);
|
|
52
|
+
else if (!autostart && !installed) Signal("Local\\AivinTrayOpen-" + id);
|
|
53
|
+
return 0;
|
|
54
|
+
}
|
|
55
|
+
if (quit) return 0;
|
|
56
|
+
try { SetProcessDPIAware(); } catch { }
|
|
57
|
+
Application.EnableVisualStyles();
|
|
58
|
+
Application.SetCompatibleTextRenderingDefault(false);
|
|
59
|
+
Application.Run(new TrayApp(id, !autostart && !installed, installed));
|
|
60
|
+
GC.KeepAlive(mutex);
|
|
61
|
+
}
|
|
62
|
+
return 0;
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
static void Signal(string name) {
|
|
66
|
+
try { using (EventWaitHandle e = EventWaitHandle.OpenExisting(name)) e.Set(); } catch { }
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
class Config {
|
|
71
|
+
public string Exe;
|
|
72
|
+
public List<string> Args = new List<string>();
|
|
73
|
+
public string Pending;
|
|
74
|
+
public string Rollback;
|
|
75
|
+
Dictionary<string, string> strings = new Dictionary<string, string>();
|
|
76
|
+
|
|
77
|
+
public static Config Load(string file) {
|
|
78
|
+
Config c = new Config();
|
|
79
|
+
try {
|
|
80
|
+
foreach (string line in File.ReadAllLines(file, Encoding.UTF8)) {
|
|
81
|
+
int i = line.IndexOf('=');
|
|
82
|
+
if (i <= 0) continue;
|
|
83
|
+
string k = line.Substring(0, i), v = line.Substring(i + 1);
|
|
84
|
+
if (k == "exe") c.Exe = v;
|
|
85
|
+
else if (k == "arg") c.Args.Add(v);
|
|
86
|
+
else if (k == "pending") c.Pending = v;
|
|
87
|
+
else if (k == "rollback") c.Rollback = v;
|
|
88
|
+
else if (k.StartsWith("s.")) c.strings[k.Substring(2)] = v.Replace("\\n", "\n");
|
|
89
|
+
}
|
|
90
|
+
} catch { }
|
|
91
|
+
return c;
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
public string T(string key) {
|
|
95
|
+
string v;
|
|
96
|
+
return strings.TryGetValue(key, out v) ? v : key;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
class TrayApp : ApplicationContext {
|
|
101
|
+
const int RestartCode = 75;
|
|
102
|
+
const string RunKey = @"Software\Microsoft\Windows\CurrentVersion\Run";
|
|
103
|
+
const string ApprovedKey = @"Software\Microsoft\Windows\CurrentVersion\Explorer\StartupApproved\Run";
|
|
104
|
+
const string ValueName = "Aivin";
|
|
105
|
+
|
|
106
|
+
static readonly string CredsFile = Path.Combine(Program.Home, "device-credentials.json");
|
|
107
|
+
static readonly string LockFile = Path.Combine(Program.Home, "remote-daemon.lock");
|
|
108
|
+
static readonly string PausedFile = Path.Combine(Program.Home, "remote-paused");
|
|
109
|
+
static readonly string ShowFile = Path.Combine(Program.Home, "mascot-show");
|
|
110
|
+
static readonly string MascotFile = Path.Combine(Program.Home, "mascot.json");
|
|
111
|
+
static readonly string CfgFile = Path.Combine(Program.Home, "desktop", "launch.cfg");
|
|
112
|
+
static readonly string LogoFile = Path.Combine(Program.Home, "desktop", "logo.png");
|
|
113
|
+
static readonly string StateFile = Path.Combine(Program.Home, "desktop", "tray-state.txt");
|
|
114
|
+
static readonly string LogFile = Path.Combine(Program.Home, "remote-service.log");
|
|
115
|
+
static readonly object logLock = new object();
|
|
116
|
+
|
|
117
|
+
/** Nhật ký chung với macOS / Linux: đầu ra của daemon + lúc khay chạy / thấy daemon thoát. Quá 5 MB thì đổi sang .1. */
|
|
118
|
+
static void Log(string line) {
|
|
119
|
+
if (line == null) return;
|
|
120
|
+
lock (logLock) {
|
|
121
|
+
try {
|
|
122
|
+
FileInfo fi = new FileInfo(LogFile);
|
|
123
|
+
if (fi.Exists && fi.Length > 5 * 1024 * 1024) {
|
|
124
|
+
File.Delete(LogFile + ".1");
|
|
125
|
+
File.Move(LogFile, LogFile + ".1");
|
|
126
|
+
}
|
|
127
|
+
File.AppendAllText(LogFile, line + "\r\n");
|
|
128
|
+
} catch { }
|
|
129
|
+
}
|
|
130
|
+
}
|
|
131
|
+
string lastWhy;
|
|
132
|
+
|
|
133
|
+
Config cfg;
|
|
134
|
+
NotifyIcon tray;
|
|
135
|
+
Icon colorIcon, greyIcon, shownIcon;
|
|
136
|
+
ToolStripMenuItem status, open, pause, startup, quit;
|
|
137
|
+
System.Windows.Forms.Timer timer;
|
|
138
|
+
Control invoker;
|
|
139
|
+
EventWaitHandle openEvent, quitEvent;
|
|
140
|
+
Process child;
|
|
141
|
+
DateTime childStarted;
|
|
142
|
+
DateTime nextStart = DateTime.MinValue;
|
|
143
|
+
int delay = 10;
|
|
144
|
+
int fast = 0;
|
|
145
|
+
bool pairing = false;
|
|
146
|
+
bool wasPaired;
|
|
147
|
+
bool quitting = false;
|
|
148
|
+
Form pairForm;
|
|
149
|
+
|
|
150
|
+
public TrayApp(string id, bool interactive, bool hint) {
|
|
151
|
+
invoker = new Control();
|
|
152
|
+
invoker.CreateControl();
|
|
153
|
+
cfg = Config.Load(CfgFile);
|
|
154
|
+
LoadIcons();
|
|
155
|
+
|
|
156
|
+
ContextMenuStrip menu = new ContextMenuStrip();
|
|
157
|
+
status = new ToolStripMenuItem();
|
|
158
|
+
status.Enabled = false;
|
|
159
|
+
open = Item("", delegate { OpenAivin(); });
|
|
160
|
+
open.Font = new Font(open.Font, FontStyle.Bold);
|
|
161
|
+
pause = Item("", delegate { TogglePause(); });
|
|
162
|
+
startup = Item(cfg.T("startup"), delegate { SetStartup(!StartupEnabled()); Refresh(); });
|
|
163
|
+
ToolStripMenuItem folder = Item(cfg.T("folder"), delegate { Run("explorer.exe", Quote(Program.Home)); });
|
|
164
|
+
quit = Item(cfg.T("quit"), delegate { Quit(); });
|
|
165
|
+
menu.Items.AddRange(new ToolStripItem[] { status, new ToolStripSeparator(), open, pause, startup, folder, new ToolStripSeparator(), quit });
|
|
166
|
+
menu.Opening += delegate { Refresh(); };
|
|
167
|
+
|
|
168
|
+
tray = new NotifyIcon();
|
|
169
|
+
tray.ContextMenuStrip = menu;
|
|
170
|
+
tray.Text = "AIVIN Bot CLI";
|
|
171
|
+
tray.Icon = shownIcon = greyIcon;
|
|
172
|
+
tray.MouseClick += delegate(object s, MouseEventArgs e) { if (e.Button == MouseButtons.Left) OpenAivin(); };
|
|
173
|
+
tray.Visible = true;
|
|
174
|
+
|
|
175
|
+
openEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Local\\AivinTrayOpen-" + id);
|
|
176
|
+
quitEvent = new EventWaitHandle(false, EventResetMode.AutoReset, "Local\\AivinTrayQuit-" + id);
|
|
177
|
+
ThreadPool.RegisterWaitForSingleObject(openEvent, delegate { UI(OpenAivin); }, null, -1, false);
|
|
178
|
+
ThreadPool.RegisterWaitForSingleObject(quitEvent, delegate { UI(Quit); }, null, -1, false);
|
|
179
|
+
|
|
180
|
+
timer = new System.Windows.Forms.Timer();
|
|
181
|
+
timer.Interval = 2000;
|
|
182
|
+
timer.Tick += delegate { Tick(); };
|
|
183
|
+
timer.Start();
|
|
184
|
+
|
|
185
|
+
wasPaired = File.Exists(CredsFile);
|
|
186
|
+
Tick();
|
|
187
|
+
if (interactive) {
|
|
188
|
+
if (wasPaired) Balloon(cfg.T("firstRun"), ToolTipIcon.Info);
|
|
189
|
+
OpenAivin();
|
|
190
|
+
} else if (hint) {
|
|
191
|
+
// Vừa cài: chỉ báo ở khay, không bật hộp nhập mã (bộ cài có thể đang ghép máy bằng mã ở cửa sổ của nó).
|
|
192
|
+
Balloon(cfg.T(wasPaired ? "firstRun" : "connectHint"), ToolTipIcon.Info);
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
ToolStripMenuItem Item(string text, EventHandler onClick) {
|
|
197
|
+
ToolStripMenuItem item = new ToolStripMenuItem(text);
|
|
198
|
+
item.Click += onClick;
|
|
199
|
+
return item;
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
void UI(Action action) {
|
|
203
|
+
try { invoker.BeginInvoke(action); } catch { }
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
void Balloon(string text, ToolTipIcon icon) {
|
|
207
|
+
try { tray.ShowBalloonTip(6000, "AIVIN Bot CLI", text, icon); } catch { }
|
|
208
|
+
}
|
|
209
|
+
|
|
210
|
+
// --- Trình giữ chạy --------------------------------------------------------------------------------------------------------------
|
|
211
|
+
|
|
212
|
+
void Tick() {
|
|
213
|
+
if (quitting) return;
|
|
214
|
+
if (child != null && child.HasExited) OnChildExit();
|
|
215
|
+
bool paired = File.Exists(CredsFile);
|
|
216
|
+
if (paired && !wasPaired) Balloon(cfg.T("connected"), ToolTipIcon.Info);
|
|
217
|
+
wasPaired = paired;
|
|
218
|
+
if (child == null && paired && DateTime.Now >= nextStart && LockHolder() == 0) StartChild(null);
|
|
219
|
+
Refresh();
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
void StartChild(string code) {
|
|
223
|
+
cfg = Config.Load(CfgFile);
|
|
224
|
+
if (string.IsNullOrEmpty(cfg.Exe)) return;
|
|
225
|
+
List<string> args = new List<string>(cfg.Args);
|
|
226
|
+
if (code != null) { args.Add("--code"); args.Add(code); }
|
|
227
|
+
StringBuilder line = new StringBuilder();
|
|
228
|
+
foreach (string a in args) { if (line.Length > 0) line.Append(' '); line.Append(Quote(a)); }
|
|
229
|
+
ProcessStartInfo psi = new ProcessStartInfo(cfg.Exe, line.ToString());
|
|
230
|
+
psi.UseShellExecute = false;
|
|
231
|
+
psi.CreateNoWindow = true;
|
|
232
|
+
psi.WorkingDirectory = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
|
|
233
|
+
psi.EnvironmentVariables["AIVIN_SUPERVISOR"] = "tray";
|
|
234
|
+
psi.RedirectStandardOutput = true;
|
|
235
|
+
psi.RedirectStandardError = true;
|
|
236
|
+
psi.StandardOutputEncoding = Encoding.UTF8;
|
|
237
|
+
psi.StandardErrorEncoding = Encoding.UTF8;
|
|
238
|
+
try {
|
|
239
|
+
child = Process.Start(psi);
|
|
240
|
+
child.OutputDataReceived += delegate(object s, DataReceivedEventArgs e) { Log(e.Data); };
|
|
241
|
+
child.ErrorDataReceived += delegate(object s, DataReceivedEventArgs e) { Log(e.Data); };
|
|
242
|
+
child.BeginOutputReadLine();
|
|
243
|
+
child.BeginErrorReadLine();
|
|
244
|
+
childStarted = DateTime.Now;
|
|
245
|
+
pairing = code != null;
|
|
246
|
+
Log(DateTime.Now.ToString("s") + " [tray] started listener (pid " + child.Id + (code != null ? ", connecting with a code" : "") + ")");
|
|
247
|
+
} catch (Exception e) {
|
|
248
|
+
Log(DateTime.Now.ToString("s") + " [tray] could not start the listener: " + e.Message);
|
|
249
|
+
child = null;
|
|
250
|
+
Backoff();
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
void Backoff() {
|
|
255
|
+
nextStart = DateTime.Now.AddSeconds(delay);
|
|
256
|
+
delay = Math.Min(delay * 2, 300);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
void OnChildExit() {
|
|
260
|
+
int rc;
|
|
261
|
+
try { rc = child.ExitCode; } catch { rc = 1; }
|
|
262
|
+
double secs = (DateTime.Now - childStarted).TotalSeconds;
|
|
263
|
+
try { child.WaitForExit(); } catch { }
|
|
264
|
+
Log(DateTime.Now.ToString("s") + " [tray] listener exited with code " + rc + " after " + (int)secs + " s");
|
|
265
|
+
child.Dispose();
|
|
266
|
+
child = null;
|
|
267
|
+
bool wasPairing = pairing;
|
|
268
|
+
pairing = false;
|
|
269
|
+
if (wasPairing && !File.Exists(CredsFile)) {
|
|
270
|
+
Balloon(cfg.T("pairFailed"), ToolTipIcon.Warning);
|
|
271
|
+
return;
|
|
272
|
+
}
|
|
273
|
+
if (rc != 0 && rc != RestartCode && RollBack(secs)) rc = RestartCode;
|
|
274
|
+
// 0 = dừng có chủ đích (thu hồi, đã có cửa sổ khác nhận việc) → chỉ chạy lại khi vẫn còn ghép máy và không ai giữ khoá.
|
|
275
|
+
if (rc == 0) { nextStart = DateTime.Now.AddSeconds(60); return; }
|
|
276
|
+
if (rc == RestartCode) { nextStart = DateTime.Now.AddSeconds(1); return; }
|
|
277
|
+
if (secs > 300) delay = 10;
|
|
278
|
+
Backoff();
|
|
279
|
+
}
|
|
280
|
+
|
|
281
|
+
/** Bản mới (còn chờ xác nhận, có .prev) sập trong 30 s, 3 lần liền → trả bản trước về, ghi phiên bản hỏng cho daemon bỏ qua. */
|
|
282
|
+
bool RollBack(double secs) {
|
|
283
|
+
string exe = cfg.Exe;
|
|
284
|
+
if (string.IsNullOrEmpty(cfg.Pending) || string.IsNullOrEmpty(cfg.Rollback) || string.IsNullOrEmpty(exe)) return false;
|
|
285
|
+
if (secs < 30 && File.Exists(cfg.Pending) && File.Exists(exe + ".prev")) fast++;
|
|
286
|
+
else { fast = 0; return false; }
|
|
287
|
+
if (fast < 3) return false;
|
|
288
|
+
fast = 0;
|
|
289
|
+
try {
|
|
290
|
+
string[] lines = File.ReadAllLines(cfg.Pending);
|
|
291
|
+
string ver = lines.Length > 0 ? lines[0].Trim() : "";
|
|
292
|
+
File.Move(exe, exe + "-" + DateTime.Now.Ticks + ".trash");
|
|
293
|
+
File.Move(exe + ".prev", exe);
|
|
294
|
+
File.WriteAllText(cfg.Rollback, ver + "\r\n");
|
|
295
|
+
File.Delete(cfg.Pending);
|
|
296
|
+
} catch { }
|
|
297
|
+
return true;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
/** PID đang giữ khoá daemon (remote-daemon.lock, xem daemonLock.mjs) — 0 nếu không ai giữ / khoá cũ. */
|
|
301
|
+
static int LockHolder() {
|
|
302
|
+
try {
|
|
303
|
+
string s = File.ReadAllText(LockFile);
|
|
304
|
+
Match m = Regex.Match(s, "\"pid\"\\s*:\\s*(\\d+)");
|
|
305
|
+
if (!m.Success) return 0;
|
|
306
|
+
int pid = int.Parse(m.Groups[1].Value);
|
|
307
|
+
Match b = Regex.Match(s, "\"beat_at\"\\s*:\\s*\"([^\"]+)\"");
|
|
308
|
+
DateTime at;
|
|
309
|
+
if (b.Success && DateTime.TryParse(b.Groups[1].Value, CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out at)
|
|
310
|
+
&& (DateTime.UtcNow - at.ToUniversalTime()).TotalSeconds > 90) return 0;
|
|
311
|
+
using (Process p = Process.GetProcessById(pid)) return pid;
|
|
312
|
+
} catch {
|
|
313
|
+
return 0;
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
bool Running() {
|
|
318
|
+
return (child != null && !child.HasExited) || LockHolder() != 0;
|
|
319
|
+
}
|
|
320
|
+
|
|
321
|
+
void KillChild() {
|
|
322
|
+
Process c = child;
|
|
323
|
+
child = null;
|
|
324
|
+
if (c == null) return;
|
|
325
|
+
try {
|
|
326
|
+
if (!c.HasExited) {
|
|
327
|
+
ProcessStartInfo psi = new ProcessStartInfo("taskkill.exe", "/PID " + c.Id + " /T /F");
|
|
328
|
+
psi.UseShellExecute = false;
|
|
329
|
+
psi.CreateNoWindow = true;
|
|
330
|
+
using (Process k = Process.Start(psi)) k.WaitForExit(5000);
|
|
331
|
+
if (!c.HasExited) c.Kill();
|
|
332
|
+
}
|
|
333
|
+
} catch { }
|
|
334
|
+
c.Dispose();
|
|
335
|
+
}
|
|
336
|
+
|
|
337
|
+
// --- Menu -------------------------------------------------------------------------------------------------------------------------
|
|
338
|
+
|
|
339
|
+
void Refresh() {
|
|
340
|
+
bool paired = File.Exists(CredsFile);
|
|
341
|
+
bool paused = File.Exists(PausedFile);
|
|
342
|
+
bool running = Running();
|
|
343
|
+
string state = !paired ? cfg.T(pairing ? "connecting" : "notPaired")
|
|
344
|
+
: !running ? cfg.T("stopped") : paused ? cfg.T("paused") : cfg.T("running");
|
|
345
|
+
status.Text = state;
|
|
346
|
+
string tip = "Aivin - " + state;
|
|
347
|
+
tray.Text = tip.Length > 63 ? tip.Substring(0, 63) : tip;
|
|
348
|
+
Icon want = paired && running && !paused ? colorIcon : greyIcon;
|
|
349
|
+
if (want != shownIcon) { tray.Icon = want; shownIcon = want; }
|
|
350
|
+
// Ghi trạng thái khi đổi — để chẩn đoán (biểu tượng xám vì sao) mà không phải mở khay.
|
|
351
|
+
string why = "paired=" + paired + " running=" + running + " child=" + (child != null) + " lock=" + LockHolder() + " paused=" + paused;
|
|
352
|
+
if (why != lastWhy) {
|
|
353
|
+
lastWhy = why;
|
|
354
|
+
try { File.AppendAllText(StateFile, DateTime.Now.ToString("s") + " " + (want == colorIcon ? "color" : "grey") + " " + why + "\r\n"); } catch { }
|
|
355
|
+
}
|
|
356
|
+
open.Text = cfg.T(paired ? "open" : "connect");
|
|
357
|
+
pause.Text = cfg.T(paused ? "resume" : "pause");
|
|
358
|
+
pause.Visible = paired;
|
|
359
|
+
startup.Checked = StartupEnabled();
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
/** Mở Aivin: chưa ghép máy → hỏi mã; có rồi → bật + hiện linh vật (như "aivin ui"), chạy daemon ngay nếu đang không chạy. */
|
|
363
|
+
void OpenAivin() {
|
|
364
|
+
if (quitting) return;
|
|
365
|
+
if (!File.Exists(CredsFile)) { ShowPair(); return; }
|
|
366
|
+
try {
|
|
367
|
+
if (File.Exists(MascotFile)) {
|
|
368
|
+
string s = File.ReadAllText(MascotFile);
|
|
369
|
+
string t = Regex.Replace(s, "\"enabled\"\\s*:\\s*false", "\"enabled\": true");
|
|
370
|
+
if (t != s) File.WriteAllText(MascotFile, t);
|
|
371
|
+
}
|
|
372
|
+
long ms = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds;
|
|
373
|
+
File.WriteAllText(ShowFile, ms.ToString(CultureInfo.InvariantCulture));
|
|
374
|
+
} catch { }
|
|
375
|
+
if (child == null && LockHolder() == 0) {
|
|
376
|
+
nextStart = DateTime.MinValue;
|
|
377
|
+
delay = 10;
|
|
378
|
+
Tick();
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
|
|
382
|
+
void TogglePause() {
|
|
383
|
+
try {
|
|
384
|
+
if (File.Exists(PausedFile)) File.Delete(PausedFile);
|
|
385
|
+
else File.WriteAllText(PausedFile, DateTime.UtcNow.ToString("o"));
|
|
386
|
+
} catch { }
|
|
387
|
+
Refresh();
|
|
388
|
+
}
|
|
389
|
+
|
|
390
|
+
void ShowPair() {
|
|
391
|
+
if (pairForm != null) { pairForm.Activate(); return; }
|
|
392
|
+
Form f = new Form();
|
|
393
|
+
f.Text = "AIVIN Bot CLI";
|
|
394
|
+
f.Icon = colorIcon;
|
|
395
|
+
f.Font = SystemFonts.MessageBoxFont;
|
|
396
|
+
f.AutoScaleDimensions = new SizeF(96F, 96F);
|
|
397
|
+
f.AutoScaleMode = AutoScaleMode.Dpi;
|
|
398
|
+
f.FormBorderStyle = FormBorderStyle.FixedDialog;
|
|
399
|
+
f.MaximizeBox = false;
|
|
400
|
+
f.MinimizeBox = false;
|
|
401
|
+
f.StartPosition = FormStartPosition.CenterScreen;
|
|
402
|
+
f.TopMost = true;
|
|
403
|
+
f.ClientSize = new Size(420, 170);
|
|
404
|
+
Label label = new Label();
|
|
405
|
+
label.Text = cfg.T("pairPrompt");
|
|
406
|
+
label.SetBounds(16, 14, 388, 64);
|
|
407
|
+
TextBox box = new TextBox();
|
|
408
|
+
box.SetBounds(16, 84, 388, 24);
|
|
409
|
+
box.CharacterCasing = CharacterCasing.Upper;
|
|
410
|
+
Button ok = new Button();
|
|
411
|
+
ok.Text = cfg.T("pairOk");
|
|
412
|
+
ok.SetBounds(218, 126, 90, 30);
|
|
413
|
+
ok.DialogResult = DialogResult.OK;
|
|
414
|
+
Button cancel = new Button();
|
|
415
|
+
cancel.Text = cfg.T("pairCancel");
|
|
416
|
+
cancel.SetBounds(314, 126, 90, 30);
|
|
417
|
+
cancel.DialogResult = DialogResult.Cancel;
|
|
418
|
+
f.Controls.AddRange(new Control[] { label, box, ok, cancel });
|
|
419
|
+
f.AcceptButton = ok;
|
|
420
|
+
f.CancelButton = cancel;
|
|
421
|
+
pairForm = f;
|
|
422
|
+
DialogResult r = f.ShowDialog();
|
|
423
|
+
string code = box.Text.Trim();
|
|
424
|
+
pairForm = null;
|
|
425
|
+
f.Dispose();
|
|
426
|
+
if (r != DialogResult.OK || code.Length == 0 || quitting) return;
|
|
427
|
+
KillChild();
|
|
428
|
+
StartChild(code);
|
|
429
|
+
Refresh();
|
|
430
|
+
}
|
|
431
|
+
|
|
432
|
+
void Quit() {
|
|
433
|
+
if (quitting) return;
|
|
434
|
+
quitting = true;
|
|
435
|
+
timer.Stop();
|
|
436
|
+
if (pairForm != null) pairForm.Close();
|
|
437
|
+
KillChild();
|
|
438
|
+
tray.Visible = false;
|
|
439
|
+
tray.Dispose();
|
|
440
|
+
ExitThread();
|
|
441
|
+
}
|
|
442
|
+
|
|
443
|
+
// --- Khởi động cùng Windows: cùng chỗ Task Manager → Startup apps bật / tắt --------------------------------------------------------
|
|
444
|
+
|
|
445
|
+
static bool StartupEnabled() {
|
|
446
|
+
try {
|
|
447
|
+
using (RegistryKey k = Registry.CurrentUser.OpenSubKey(RunKey)) {
|
|
448
|
+
if (k == null || k.GetValue(ValueName) == null) return false;
|
|
449
|
+
}
|
|
450
|
+
using (RegistryKey a = Registry.CurrentUser.OpenSubKey(ApprovedKey)) {
|
|
451
|
+
byte[] b = a == null ? null : a.GetValue(ValueName) as byte[];
|
|
452
|
+
return b == null || b.Length == 0 || (b[0] & 1) == 0;
|
|
453
|
+
}
|
|
454
|
+
} catch {
|
|
455
|
+
return false;
|
|
456
|
+
}
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
static void SetStartup(bool on) {
|
|
460
|
+
try {
|
|
461
|
+
if (on) {
|
|
462
|
+
using (RegistryKey k = Registry.CurrentUser.CreateSubKey(RunKey)) k.SetValue(ValueName, Quote(Application.ExecutablePath) + " --autostart");
|
|
463
|
+
}
|
|
464
|
+
byte[] data = new byte[12];
|
|
465
|
+
data[0] = (byte)(on ? 2 : 3);
|
|
466
|
+
if (!on) Array.Copy(BitConverter.GetBytes(DateTime.UtcNow.ToFileTimeUtc()), 0, data, 4, 8);
|
|
467
|
+
using (RegistryKey a = Registry.CurrentUser.CreateSubKey(ApprovedKey)) a.SetValue(ValueName, data, RegistryValueKind.Binary);
|
|
468
|
+
} catch { }
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
// --- Tiện ích ---------------------------------------------------------------------------------------------------------------------
|
|
472
|
+
|
|
473
|
+
static void Run(string file, string args) {
|
|
474
|
+
try { Process.Start(file, args); } catch { }
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
/** Một đối số dòng lệnh Windows (quy tắc CommandLineToArgvW). */
|
|
478
|
+
static string Quote(string a) {
|
|
479
|
+
if (a.Length > 0 && a.IndexOfAny(new char[] { ' ', '\t', '"' }) < 0) return a;
|
|
480
|
+
StringBuilder sb = new StringBuilder("\"");
|
|
481
|
+
int slashes = 0;
|
|
482
|
+
foreach (char ch in a) {
|
|
483
|
+
if (ch == '\\') { slashes++; continue; }
|
|
484
|
+
if (ch == '"') sb.Append('\\', slashes * 2 + 1);
|
|
485
|
+
else sb.Append('\\', slashes);
|
|
486
|
+
slashes = 0;
|
|
487
|
+
sb.Append(ch);
|
|
488
|
+
}
|
|
489
|
+
sb.Append('\\', slashes * 2);
|
|
490
|
+
sb.Append('"');
|
|
491
|
+
return sb.ToString();
|
|
492
|
+
}
|
|
493
|
+
|
|
494
|
+
void LoadIcons() {
|
|
495
|
+
Bitmap src = null;
|
|
496
|
+
try { src = new Bitmap(LogoFile); } catch { }
|
|
497
|
+
if (src == null) {
|
|
498
|
+
try { src = Icon.ExtractAssociatedIcon(Application.ExecutablePath).ToBitmap(); } catch { }
|
|
499
|
+
}
|
|
500
|
+
Size size = SystemInformation.SmallIconSize;
|
|
501
|
+
colorIcon = MakeIcon(src, size, false);
|
|
502
|
+
greyIcon = MakeIcon(src, size, true);
|
|
503
|
+
}
|
|
504
|
+
|
|
505
|
+
static Icon MakeIcon(Bitmap src, Size size, bool grey) {
|
|
506
|
+
if (src == null) return SystemIcons.Application;
|
|
507
|
+
Bitmap bmp = new Bitmap(size.Width, size.Height, PixelFormat.Format32bppArgb);
|
|
508
|
+
using (Graphics g = Graphics.FromImage(bmp)) {
|
|
509
|
+
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
|
|
510
|
+
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
|
|
511
|
+
ImageAttributes attr = new ImageAttributes();
|
|
512
|
+
if (grey) {
|
|
513
|
+
attr.SetColorMatrix(new ColorMatrix(new float[][] {
|
|
514
|
+
new float[] { 0.3f, 0.3f, 0.3f, 0, 0 },
|
|
515
|
+
new float[] { 0.59f, 0.59f, 0.59f, 0, 0 },
|
|
516
|
+
new float[] { 0.11f, 0.11f, 0.11f, 0, 0 },
|
|
517
|
+
new float[] { 0, 0, 0, 0.7f, 0 },
|
|
518
|
+
new float[] { 0, 0, 0, 0, 1 },
|
|
519
|
+
}));
|
|
520
|
+
}
|
|
521
|
+
g.DrawImage(src, new Rectangle(0, 0, size.Width, size.Height), 0, 0, src.Width, src.Height, GraphicsUnit.Pixel, attr);
|
|
522
|
+
}
|
|
523
|
+
return Icon.FromHandle(bmp.GetHicon());
|
|
524
|
+
}
|
|
525
|
+
}
|
|
526
|
+
}
|
|
527
|
+
`;
|