t3-code-qqbot 1.2.2 → 1.2.3
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 +2 -2
- package/dist/bridge.mjs +396 -96
- package/dist/cli.mjs +197 -85
- package/dist/publish.mjs +1 -1
- package/docs/SETUP.md +4 -4
- package/package.json +1 -1
- package/scripts/install-windows-task.ps1 +44 -10
- package/scripts/start-windows.ps1 +4 -17
package/dist/cli.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
// src/cli.ts
|
|
4
4
|
import { spawn } from "node:child_process";
|
|
5
|
+
import { createWriteStream } from "node:fs";
|
|
5
6
|
import { mkdir as mkdir3, readdir, readFile as readFile5, rename as rename2, unlink as unlink2, writeFile as writeFile3 } from "node:fs/promises";
|
|
6
7
|
import { homedir as homedir3, tmpdir } from "node:os";
|
|
7
8
|
import { dirname as dirname5, extname, join as join5, resolve as resolve4 } from "node:path";
|
|
@@ -19,7 +20,8 @@ var MAX_ATTACHMENT_BYTES = 12 * 1024 * 1024;
|
|
|
19
20
|
var digest = (value) => createHash("sha256").update(value).digest("hex");
|
|
20
21
|
|
|
21
22
|
// src/config.ts
|
|
22
|
-
var APP_VERSION = "1.2.
|
|
23
|
+
var APP_VERSION = "1.2.3";
|
|
24
|
+
var SELF_UPDATE_EXIT_CODE = 75;
|
|
23
25
|
var DEFAULT_ATTACHMENT_HOSTS = [
|
|
24
26
|
"multimedia.nt.qq.com.cn",
|
|
25
27
|
"multimedia.nt.qq.com",
|
|
@@ -413,7 +415,7 @@ async function runQrBotLogin(options = {}) {
|
|
|
413
415
|
import { execFile } from "node:child_process";
|
|
414
416
|
import { mkdir, unlink, writeFile } from "node:fs/promises";
|
|
415
417
|
import { homedir } from "node:os";
|
|
416
|
-
import { join as join2, resolve as resolve2 } from "node:path";
|
|
418
|
+
import { dirname as dirname2, join as join2, resolve as resolve2 } from "node:path";
|
|
417
419
|
import { promisify } from "node:util";
|
|
418
420
|
var execFileAsync = promisify(execFile);
|
|
419
421
|
var DEFAULT_LINUX_SERVICE = "t3-code-qqbot";
|
|
@@ -455,32 +457,32 @@ function renderSystemdUnit(options) {
|
|
|
455
457
|
""
|
|
456
458
|
].join("\n");
|
|
457
459
|
}
|
|
458
|
-
function
|
|
459
|
-
|
|
460
|
+
function vbsStringLiteral(value) {
|
|
461
|
+
if (/[\r\n]/.test(value)) {
|
|
462
|
+
throw new Error(`Invalid multiline value for Windows launcher: ${JSON.stringify(value)}`);
|
|
463
|
+
}
|
|
464
|
+
return `"${value.replace(/"/g, '""')}"`;
|
|
465
|
+
}
|
|
466
|
+
function renderWindowsLauncherVbs(options) {
|
|
460
467
|
return [
|
|
461
|
-
"
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
"
|
|
472
|
-
"
|
|
473
|
-
' $text = if ($_ -is [System.Management.Automation.ErrorRecord]) { $_.ToString() } else { "$_" }',
|
|
474
|
-
" Add-Content -LiteralPath $LogPath -Encoding utf8 -Value ('[{0:yyyy-MM-dd HH:mm:ss}] {1}' -f [DateTime]::Now, $text)",
|
|
475
|
-
" }",
|
|
476
|
-
" $code = $LASTEXITCODE",
|
|
477
|
-
"} finally {",
|
|
478
|
-
" $ErrorActionPreference = $prev",
|
|
479
|
-
"}",
|
|
480
|
-
"exit $code",
|
|
468
|
+
"Option Explicit",
|
|
469
|
+
"Dim sh, nodePath, cliEntry, configPath, logPath, cmd, exitCode",
|
|
470
|
+
'Set sh = CreateObject("WScript.Shell")',
|
|
471
|
+
`sh.CurrentDirectory = ${vbsStringLiteral(options.workingDir)}`,
|
|
472
|
+
'sh.Environment("Process")("NODE_NO_WARNINGS") = "1"',
|
|
473
|
+
`nodePath = ${vbsStringLiteral(options.nodePath)}`,
|
|
474
|
+
`cliEntry = ${vbsStringLiteral(options.cliEntry)}`,
|
|
475
|
+
`configPath = ${vbsStringLiteral(options.configPath)}`,
|
|
476
|
+
`logPath = ${vbsStringLiteral(options.logPath)}`,
|
|
477
|
+
'cmd = """" & nodePath & """ """ & cliEntry & """ start --supervise --config """ & configPath & """ --log-file """ & logPath & """"',
|
|
478
|
+
"exitCode = sh.Run(cmd, 0, True)",
|
|
479
|
+
"WScript.Quit exitCode",
|
|
481
480
|
""
|
|
482
481
|
].join("\r\n");
|
|
483
482
|
}
|
|
483
|
+
function encodeUtf16LeWithBom(content) {
|
|
484
|
+
return Buffer.concat([Buffer.from([255, 254]), Buffer.from(content, "utf16le")]);
|
|
485
|
+
}
|
|
484
486
|
async function runPsEncoded(script) {
|
|
485
487
|
const encoded = Buffer.from(script, "utf16le").toString("base64");
|
|
486
488
|
const psExe = join2(process.env.WINDIR || "C:\\Windows", "System32", "WindowsPowerShell", "v1.0", "powershell.exe");
|
|
@@ -502,25 +504,53 @@ async function probeBridgeHealth(host, port) {
|
|
|
502
504
|
}
|
|
503
505
|
async function runWindowsServiceAction(action, options) {
|
|
504
506
|
const psSingle = (value) => `'${value.replace(/'/g, "''")}'`;
|
|
507
|
+
const stopProcessesScript = (targets) => {
|
|
508
|
+
const literals = targets.map((t) => psSingle(t)).join(", ");
|
|
509
|
+
return `
|
|
510
|
+
$targets = @(${literals})
|
|
511
|
+
$skipPids = @($PID, ${process.pid})
|
|
512
|
+
Get-CimInstance Win32_Process -Filter "Name='wscript.exe' OR Name='node.exe' OR Name='powershell.exe'" -ErrorAction SilentlyContinue |
|
|
513
|
+
Where-Object {
|
|
514
|
+
if (-not $_.CommandLine -or ($skipPids -contains $_.ProcessId)) { return $false }
|
|
515
|
+
foreach ($needle in $targets) {
|
|
516
|
+
if ($needle -and $_.CommandLine.IndexOf($needle, [System.StringComparison]::OrdinalIgnoreCase) -ge 0) {
|
|
517
|
+
return $true
|
|
518
|
+
}
|
|
519
|
+
}
|
|
520
|
+
return $false
|
|
521
|
+
} |
|
|
522
|
+
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
|
|
523
|
+
`;
|
|
524
|
+
};
|
|
505
525
|
if (action === "install") {
|
|
506
526
|
const config = await loadConfig(options.configPath);
|
|
507
527
|
await mkdir(config.stateDir, { recursive: true });
|
|
508
|
-
const
|
|
509
|
-
const
|
|
528
|
+
const launcherPath = join2(config.stateDir, "run-service.vbs");
|
|
529
|
+
const legacyPs1Path = join2(config.stateDir, "run-service.ps1");
|
|
530
|
+
const logPath = join2(config.stateDir, "service.log");
|
|
531
|
+
const launcherContent = renderWindowsLauncherVbs({
|
|
510
532
|
nodePath: process.execPath,
|
|
511
533
|
cliEntry: options.cliEntry,
|
|
512
534
|
configPath: config.configPath,
|
|
513
|
-
|
|
535
|
+
workingDir: config.configDir,
|
|
536
|
+
logPath
|
|
514
537
|
});
|
|
515
|
-
await writeFile(
|
|
516
|
-
|
|
538
|
+
await writeFile(launcherPath, encodeUtf16LeWithBom(launcherContent));
|
|
539
|
+
await unlink(legacyPs1Path).catch(() => {
|
|
540
|
+
});
|
|
541
|
+
const wscriptExe = join2(process.env.WINDIR || "C:\\Windows", "System32", "wscript.exe");
|
|
517
542
|
const registerScript = `
|
|
518
543
|
$ErrorActionPreference = 'Stop'
|
|
519
544
|
$taskName = ${psSingle(options.taskName)}
|
|
520
|
-
$
|
|
521
|
-
$
|
|
545
|
+
$existing = Get-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
|
|
546
|
+
if ($existing) {
|
|
547
|
+
Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
|
|
548
|
+
}
|
|
549
|
+
${stopProcessesScript([config.configPath, launcherPath, legacyPs1Path])}
|
|
550
|
+
$wscriptExe = ${psSingle(wscriptExe)}
|
|
551
|
+
$launcher = ${psSingle(launcherPath)}
|
|
522
552
|
$workDir = ${psSingle(config.configDir)}
|
|
523
|
-
$action = New-ScheduledTaskAction -Execute $
|
|
553
|
+
$action = New-ScheduledTaskAction -Execute $wscriptExe -Argument "//B //Nologo \`"$launcher\`"" -WorkingDirectory $workDir
|
|
524
554
|
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
|
|
525
555
|
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries -RestartCount 999 -RestartInterval (New-TimeSpan -Minutes 1) -ExecutionTimeLimit ([TimeSpan]::Zero)
|
|
526
556
|
Register-ScheduledTask -TaskName $taskName -Action $action -Trigger $trigger -Settings $settings -Description 'T3 Code QQBot Bridge & Official WebSocket Gateway' -Force | Out-Null
|
|
@@ -528,22 +558,20 @@ Start-ScheduledTask -TaskName $taskName
|
|
|
528
558
|
Write-Output "INSTALLED_AND_STARTED"
|
|
529
559
|
`;
|
|
530
560
|
await runPsEncoded(registerScript);
|
|
531
|
-
console.log(`Installed & started Windows background service "${options.taskName}".`);
|
|
532
|
-
console.log(` Config:
|
|
533
|
-
console.log(`
|
|
534
|
-
console.log(` Logs:
|
|
535
|
-
console.log(`
|
|
536
|
-
console.log(`
|
|
561
|
+
console.log(`Installed & started Windows background service "${options.taskName}" (GUI zero-window wscript launcher).`);
|
|
562
|
+
console.log(` Config: ${config.configPath}`);
|
|
563
|
+
console.log(` Launcher: ${launcherPath}`);
|
|
564
|
+
console.log(` Logs: ${logPath}`);
|
|
565
|
+
console.log(` ${join2(config.stateDir, "bridge.log")}`);
|
|
566
|
+
console.log(` ${join2(config.stateDir, "gateway.log")}`);
|
|
537
567
|
return;
|
|
538
568
|
}
|
|
539
|
-
const stopProcessesScript = (configPath) => `
|
|
540
|
-
$cfg = ${psSingle(configPath)}
|
|
541
|
-
Get-CimInstance Win32_Process -Filter "Name='node.exe' OR Name='powershell.exe'" -ErrorAction SilentlyContinue |
|
|
542
|
-
Where-Object { $_.CommandLine -and $_.CommandLine.IndexOf($cfg, [System.StringComparison]::OrdinalIgnoreCase) -ge 0 -and $_.ProcessId -ne $PID } |
|
|
543
|
-
ForEach-Object { Stop-Process -Id $_.ProcessId -Force -ErrorAction SilentlyContinue }
|
|
544
|
-
`;
|
|
545
569
|
if (action === "stop" || action === "uninstall") {
|
|
546
570
|
const absConfig = resolve2(options.configPath);
|
|
571
|
+
const config = await loadConfig(absConfig).catch(() => null);
|
|
572
|
+
const stateDir = config?.stateDir ?? join2(dirname2(absConfig), "state");
|
|
573
|
+
const launcherPath = join2(stateDir, "run-service.vbs");
|
|
574
|
+
const legacyPs1Path = join2(stateDir, "run-service.ps1");
|
|
547
575
|
const script = `
|
|
548
576
|
$ErrorActionPreference = 'Stop'
|
|
549
577
|
$taskName = ${psSingle(options.taskName)}
|
|
@@ -552,15 +580,14 @@ if ($task) {
|
|
|
552
580
|
Stop-ScheduledTask -TaskName $taskName -ErrorAction SilentlyContinue
|
|
553
581
|
${action === "uninstall" ? "Unregister-ScheduledTask -TaskName $taskName -Confirm:$false" : ""}
|
|
554
582
|
}
|
|
555
|
-
${stopProcessesScript(absConfig)}
|
|
583
|
+
${stopProcessesScript([absConfig, launcherPath, legacyPs1Path])}
|
|
556
584
|
`;
|
|
557
585
|
await runPsEncoded(script);
|
|
558
586
|
if (action === "uninstall") {
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
}
|
|
587
|
+
await unlink(launcherPath).catch(() => {
|
|
588
|
+
});
|
|
589
|
+
await unlink(legacyPs1Path).catch(() => {
|
|
590
|
+
});
|
|
564
591
|
console.log(`Uninstalled Windows background service "${options.taskName}".`);
|
|
565
592
|
} else {
|
|
566
593
|
console.log(`Stopped Windows background service "${options.taskName}".`);
|
|
@@ -1691,32 +1718,32 @@ function getSiblingEntry(name) {
|
|
|
1691
1718
|
return join5(import.meta.dirname, `${name}${currentExt}`);
|
|
1692
1719
|
}
|
|
1693
1720
|
function printHelp() {
|
|
1694
|
-
console.log(`t3-code-qqbot v${APP_VERSION} \u2014
|
|
1721
|
+
console.log(`t3-code-qqbot v${APP_VERSION} \u2014 \u8DE8\u5E73\u53F0\uFF08Windows & Linux\uFF09T3 Code \u5B98\u65B9 QQ \u673A\u5668\u4EBA\u63D2\u4EF6
|
|
1695
1722
|
|
|
1696
|
-
|
|
1697
|
-
t3-qqbot
|
|
1698
|
-
node dist/cli.mjs
|
|
1723
|
+
\u7528\u6CD5\uFF1A
|
|
1724
|
+
t3-qqbot <\u547D\u4EE4> [\u9009\u9879]
|
|
1725
|
+
node dist/cli.mjs <\u547D\u4EE4> [\u9009\u9879]
|
|
1699
1726
|
|
|
1700
|
-
|
|
1701
|
-
init [--dir
|
|
1702
|
-
|
|
1703
|
-
login [--config
|
|
1704
|
-
config [show|set
|
|
1705
|
-
|
|
1706
|
-
start [--config
|
|
1707
|
-
|
|
1708
|
-
service <install|uninstall|status|start|stop|restart> [--config
|
|
1709
|
-
|
|
1710
|
-
bridge [--config
|
|
1711
|
-
gateway [--config
|
|
1712
|
-
bind --scope <c2c:...|group:...> [--workspace
|
|
1713
|
-
|
|
1714
|
-
doctor [--config
|
|
1715
|
-
recover <runId> [--config
|
|
1727
|
+
\u5E38\u7528\u547D\u4EE4\uFF1A
|
|
1728
|
+
init [--dir <\u76EE\u5F55>] [--force] [--yes]
|
|
1729
|
+
\u4EA4\u4E92\u5F0F\u5B89\u88C5\u5411\u5BFC\uFF08\u626B\u7801/\u624B\u52A8\u586B\u51ED\u636E\u3001\u53EF\u9009\u9879\u3001\u7ED1\u5B9A\u4E0E\u5F00\u673A\u81EA\u5B88\u62A4\uFF1B--yes \u8DF3\u8FC7\u4EA4\u4E92\uFF09
|
|
1730
|
+
login [--config <\u8DEF\u5F84>] \u7EC8\u7AEF\u626B\u7801\u4E00\u952E\u7ED1\u5B9A QQ \u673A\u5668\u4EBA\uFF08\u81EA\u52A8\u83B7\u53D6 AppID\u3001AppSecret \u4E0E user_openid\uFF09
|
|
1731
|
+
config [show|set <\u952E> <\u503C>] [--config <\u8DEF\u5F84>]
|
|
1732
|
+
\u6253\u5F00\u4EA4\u4E92\u5F0F\u914D\u7F6E\u83DC\u5355\uFF08\u6216\u76F4\u63A5\u67E5\u770B/\u4FEE\u6539\u5355\u9879\u914D\u7F6E\uFF09
|
|
1733
|
+
start [--config <\u8DEF\u5F84>] [--supervise] [--log-file <\u8DEF\u5F84>]
|
|
1734
|
+
\u4E00\u952E\u540C\u65F6\u542F\u52A8\u6865\u63A5\u4E0E QQ \u7F51\u5173\uFF08--supervise \u5D29\u6E83\u81EA\u52A8\u91CD\u542F\uFF1B--log-file \u5C06\u8F93\u51FA\u5E26\u65F6\u95F4\u6233\u5199\u5165\u6587\u4EF6\uFF09
|
|
1735
|
+
service <install|uninstall|status|start|stop|restart> [--config <\u8DEF\u5F84>] [--name <\u540D\u79F0>]
|
|
1736
|
+
\u6CE8\u518C\u4E0E\u7BA1\u7406\u672C\u673A\u540E\u53F0\u81EA\u5B88\u62A4\uFF08Windows \u8BA1\u5212\u4EFB\u52A1 / Linux systemd --user\uFF09
|
|
1737
|
+
bridge [--config <\u8DEF\u5F84>] \u4EC5\u542F\u52A8 T3 \u6865\u63A5 HTTP \u670D\u52A1
|
|
1738
|
+
gateway [--config <\u8DEF\u5F84>] \u4EC5\u542F\u52A8 QQ \u5B98\u65B9 WebSocket \u7F51\u5173
|
|
1739
|
+
bind --scope <c2c:...|group:...> [--workspace <\u76EE\u5F55>] [--thread <\u4F1A\u8BDDID>] [--install-media-mcp] [--config <\u8DEF\u5F84>]
|
|
1740
|
+
\u6821\u9A8C\u5E76\u7ED1\u5B9A QQ \u4F1A\u8BDD\u5230 T3 \u5DE5\u4F5C\u533A\u6216\u6307\u5B9A\u4F1A\u8BDD
|
|
1741
|
+
doctor [--config <\u8DEF\u5F84>] \u6267\u884C 6 \u6B65\u5168\u94FE\u8DEF\u4F53\u68C0\u4E0E\u8FDE\u901A\u6027\u6D4B\u8BD5
|
|
1742
|
+
recover <runId> [--config <\u8DEF\u5F84>] \u5BF9\u5DF2\u4E2D\u65AD\u56DE\u4F20\u7684\u6307\u5B9A T3 runId \u8865\u53D1 QQ \u56DE\u590D
|
|
1716
1743
|
|
|
1717
|
-
|
|
1718
|
-
--config
|
|
1719
|
-
--help, -h
|
|
1744
|
+
\u901A\u7528\u9009\u9879\uFF1A
|
|
1745
|
+
--config <\u8DEF\u5F84> \u6307\u5B9A config.json \u8DEF\u5F84\uFF08\u9ED8\u8BA4 ./config.json \u6216 $T3_QQBOT_CONFIG\uFF09
|
|
1746
|
+
--help, -h \u663E\u793A\u672C\u5E2E\u52A9\u4FE1\u606F
|
|
1720
1747
|
`);
|
|
1721
1748
|
}
|
|
1722
1749
|
async function cmdInit(flags) {
|
|
@@ -1757,9 +1784,70 @@ async function waitForBridgeOrExit(url, childExitPromise, timeoutMs = 1e4) {
|
|
|
1757
1784
|
}
|
|
1758
1785
|
return { ready: false, exitedEarly };
|
|
1759
1786
|
}
|
|
1760
|
-
|
|
1787
|
+
function formatLocalLogTimestamp(date = /* @__PURE__ */ new Date()) {
|
|
1788
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
1789
|
+
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())} ${pad(date.getHours())}:${pad(date.getMinutes())}:${pad(date.getSeconds())}`;
|
|
1790
|
+
}
|
|
1791
|
+
async function createServiceFileLogger(logFilePath) {
|
|
1792
|
+
const absPath = resolve4(logFilePath);
|
|
1793
|
+
await mkdir3(dirname5(absPath), { recursive: true });
|
|
1794
|
+
const ws = createWriteStream(absPath, { flags: "a", encoding: "utf8" });
|
|
1795
|
+
ws.on("error", () => {
|
|
1796
|
+
});
|
|
1797
|
+
const writeLine = (line) => {
|
|
1798
|
+
if (ws.destroyed || ws.writableEnded) return;
|
|
1799
|
+
ws.write(`[${formatLocalLogTimestamp()}] ${line}
|
|
1800
|
+
`);
|
|
1801
|
+
};
|
|
1802
|
+
const attach = (stream) => {
|
|
1803
|
+
if (!stream) return;
|
|
1804
|
+
stream.setEncoding("utf8");
|
|
1805
|
+
let pending = "";
|
|
1806
|
+
stream.on("data", (chunk) => {
|
|
1807
|
+
pending += chunk;
|
|
1808
|
+
const lines = pending.split(/\r?\n/);
|
|
1809
|
+
pending = lines.pop() ?? "";
|
|
1810
|
+
for (const line of lines) {
|
|
1811
|
+
if (line.length > 0) writeLine(line);
|
|
1812
|
+
}
|
|
1813
|
+
});
|
|
1814
|
+
stream.on("end", () => {
|
|
1815
|
+
if (pending.length > 0) {
|
|
1816
|
+
writeLine(pending);
|
|
1817
|
+
pending = "";
|
|
1818
|
+
}
|
|
1819
|
+
});
|
|
1820
|
+
};
|
|
1821
|
+
const close = () => new Promise((resolveClose) => {
|
|
1822
|
+
if (ws.destroyed || ws.writableEnded) {
|
|
1823
|
+
resolveClose();
|
|
1824
|
+
return;
|
|
1825
|
+
}
|
|
1826
|
+
ws.end(() => resolveClose());
|
|
1827
|
+
});
|
|
1828
|
+
return { writeLine, attach, close };
|
|
1829
|
+
}
|
|
1830
|
+
async function cmdStart(configPath, supervise = false, logFilePath) {
|
|
1831
|
+
const logger = logFilePath ? await createServiceFileLogger(logFilePath) : void 0;
|
|
1832
|
+
const logInfo = (message) => {
|
|
1833
|
+
if (logger) logger.writeLine(message);
|
|
1834
|
+
else console.info(message);
|
|
1835
|
+
};
|
|
1836
|
+
const logError = (message) => {
|
|
1837
|
+
if (logger) logger.writeLine(message);
|
|
1838
|
+
else console.error(message);
|
|
1839
|
+
};
|
|
1761
1840
|
if (!supervise) {
|
|
1762
|
-
|
|
1841
|
+
try {
|
|
1842
|
+
await runStartOnce(configPath, logger);
|
|
1843
|
+
} catch (error) {
|
|
1844
|
+
if (logger) {
|
|
1845
|
+
logError(`Fatal: ${error instanceof Error ? error.message : String(error)}`);
|
|
1846
|
+
}
|
|
1847
|
+
throw error;
|
|
1848
|
+
} finally {
|
|
1849
|
+
await logger?.close();
|
|
1850
|
+
}
|
|
1763
1851
|
return;
|
|
1764
1852
|
}
|
|
1765
1853
|
let stopping = false;
|
|
@@ -1773,14 +1861,14 @@ async function cmdStart(configPath, supervise = false) {
|
|
|
1773
1861
|
while (!stopping) {
|
|
1774
1862
|
const startedAt = Date.now();
|
|
1775
1863
|
try {
|
|
1776
|
-
await runStartOnce(configPath);
|
|
1864
|
+
await runStartOnce(configPath, logger);
|
|
1777
1865
|
if (stopping) break;
|
|
1778
1866
|
} catch (error) {
|
|
1779
1867
|
if (stopping) break;
|
|
1780
1868
|
const uptimeMs = Date.now() - startedAt;
|
|
1781
1869
|
consecutiveFailures = uptimeMs > 6e4 ? 1 : consecutiveFailures + 1;
|
|
1782
1870
|
const backoffMs = Math.min(3e4, 3e3 * Math.pow(2, consecutiveFailures - 1));
|
|
1783
|
-
|
|
1871
|
+
logError(
|
|
1784
1872
|
`Supervisor caught failure (${error instanceof Error ? error.message : String(error)}); restarting in ${backoffMs / 1e3}s...`
|
|
1785
1873
|
);
|
|
1786
1874
|
await sleep(backoffMs);
|
|
@@ -1789,19 +1877,32 @@ async function cmdStart(configPath, supervise = false) {
|
|
|
1789
1877
|
} finally {
|
|
1790
1878
|
process.off("SIGINT", markStop);
|
|
1791
1879
|
process.off("SIGTERM", markStop);
|
|
1880
|
+
await logger?.close();
|
|
1792
1881
|
}
|
|
1793
1882
|
}
|
|
1794
|
-
async function runStartOnce(configPath) {
|
|
1883
|
+
async function runStartOnce(configPath, logger) {
|
|
1884
|
+
const logInfo = (message) => {
|
|
1885
|
+
if (logger) logger.writeLine(message);
|
|
1886
|
+
else console.info(message);
|
|
1887
|
+
};
|
|
1888
|
+
const logError = (message) => {
|
|
1889
|
+
if (logger) logger.writeLine(message);
|
|
1890
|
+
else console.error(message);
|
|
1891
|
+
};
|
|
1795
1892
|
const config = await loadConfig(configPath);
|
|
1796
1893
|
await loadCredentials(config);
|
|
1797
1894
|
const bridgeEntry = getSiblingEntry("bridge");
|
|
1798
1895
|
const gatewayEntry = getSiblingEntry("gateway");
|
|
1799
|
-
|
|
1896
|
+
logInfo(`Starting T3 QQBot bridge (${bridgeEntry})...`);
|
|
1800
1897
|
const bridgeChild = spawn(process.execPath, [bridgeEntry, config.configPath], {
|
|
1801
|
-
stdio: "inherit",
|
|
1898
|
+
stdio: logger ? ["ignore", "pipe", "pipe"] : "inherit",
|
|
1802
1899
|
env: process.env,
|
|
1803
1900
|
windowsHide: true
|
|
1804
1901
|
});
|
|
1902
|
+
if (logger) {
|
|
1903
|
+
logger.attach(bridgeChild.stdout);
|
|
1904
|
+
logger.attach(bridgeChild.stderr);
|
|
1905
|
+
}
|
|
1805
1906
|
const bridgeExitPromise = new Promise((resolveExit) => {
|
|
1806
1907
|
bridgeChild.once("exit", (code, signal) => resolveExit({ code, signal }));
|
|
1807
1908
|
});
|
|
@@ -1818,12 +1919,16 @@ async function runStartOnce(configPath) {
|
|
|
1818
1919
|
}
|
|
1819
1920
|
throw new Error(`Bridge failed to start listening on ${healthUrl}`);
|
|
1820
1921
|
}
|
|
1821
|
-
|
|
1922
|
+
logInfo(`Starting T3 QQBot gateway (${gatewayEntry})...`);
|
|
1822
1923
|
const gatewayChild = spawn(process.execPath, [gatewayEntry, config.configPath], {
|
|
1823
|
-
stdio: "inherit",
|
|
1924
|
+
stdio: logger ? ["ignore", "pipe", "pipe"] : "inherit",
|
|
1824
1925
|
env: process.env,
|
|
1825
1926
|
windowsHide: true
|
|
1826
1927
|
});
|
|
1928
|
+
if (logger) {
|
|
1929
|
+
logger.attach(gatewayChild.stdout);
|
|
1930
|
+
logger.attach(gatewayChild.stderr);
|
|
1931
|
+
}
|
|
1827
1932
|
const gatewayExitPromise = new Promise((resolveExit) => {
|
|
1828
1933
|
gatewayChild.once("exit", (code, signal) => resolveExit({ code, signal }));
|
|
1829
1934
|
});
|
|
@@ -1859,8 +1964,14 @@ async function runStartOnce(configPath) {
|
|
|
1859
1964
|
void bridgeExitPromise.then(({ code, signal }) => {
|
|
1860
1965
|
if (shuttingDown) return;
|
|
1861
1966
|
shuttingDown = true;
|
|
1967
|
+
if (code === SELF_UPDATE_EXIT_CODE) {
|
|
1968
|
+
logInfo(`Bridge requested graceful self-update restart (code=${code}); restarting immediately...`);
|
|
1969
|
+
terminateChildren(false);
|
|
1970
|
+
void Promise.race([gatewayExitPromise, sleep(2e3)]).then(() => finish());
|
|
1971
|
+
return;
|
|
1972
|
+
}
|
|
1862
1973
|
const err = new Error(`Bridge exited unexpectedly (code=${code}, signal=${signal})`);
|
|
1863
|
-
|
|
1974
|
+
logError(err.message);
|
|
1864
1975
|
terminateChildren(false);
|
|
1865
1976
|
void Promise.race([gatewayExitPromise, sleep(2e3)]).then(() => finish(err));
|
|
1866
1977
|
});
|
|
@@ -1868,7 +1979,7 @@ async function runStartOnce(configPath) {
|
|
|
1868
1979
|
if (shuttingDown) return;
|
|
1869
1980
|
shuttingDown = true;
|
|
1870
1981
|
const err = new Error(`Gateway exited unexpectedly (code=${code}, signal=${signal})`);
|
|
1871
|
-
|
|
1982
|
+
logError(err.message);
|
|
1872
1983
|
terminateChildren(false);
|
|
1873
1984
|
void Promise.race([bridgeExitPromise, sleep(2e3)]).then(() => finish(err));
|
|
1874
1985
|
});
|
|
@@ -2149,7 +2260,8 @@ async function main() {
|
|
|
2149
2260
|
return;
|
|
2150
2261
|
}
|
|
2151
2262
|
if (command === "start") {
|
|
2152
|
-
|
|
2263
|
+
const logFile = typeof flags.get("log-file") === "string" ? String(flags.get("log-file")) : void 0;
|
|
2264
|
+
await cmdStart(configPath, flags.get("supervise") === true, logFile);
|
|
2153
2265
|
return;
|
|
2154
2266
|
}
|
|
2155
2267
|
if (command === "service") {
|
package/dist/publish.mjs
CHANGED
package/docs/SETUP.md
CHANGED
|
@@ -96,14 +96,14 @@ mkdir -p ~/t3-qqbot && cd ~/t3-qqbot
|
|
|
96
96
|
|
|
97
97
|
- **Windows(PowerShell)**:
|
|
98
98
|
```powershell
|
|
99
|
-
Expand-Archive -Path .\t3-code-qqbot-v1.2.
|
|
100
|
-
cd C:\Tools\t3-code-qqbot-v1.2.
|
|
99
|
+
Expand-Archive -Path .\t3-code-qqbot-v1.2.3.zip -DestinationPath C:\Tools\
|
|
100
|
+
cd C:\Tools\t3-code-qqbot-v1.2.3
|
|
101
101
|
npm ci --omit=dev
|
|
102
102
|
```
|
|
103
103
|
- **Linux(Bash)**:
|
|
104
104
|
```bash
|
|
105
105
|
mkdir -p ~/t3-code-qqbot
|
|
106
|
-
tar -xzf t3-code-qqbot-v1.2.
|
|
106
|
+
tar -xzf t3-code-qqbot-v1.2.3.tar.gz -C ~/t3-code-qqbot --strip-components=1
|
|
107
107
|
cd ~/t3-code-qqbot
|
|
108
108
|
npm ci --omit=dev
|
|
109
109
|
```
|
|
@@ -301,7 +301,7 @@ t3-qqbot service uninstall
|
|
|
301
301
|
```
|
|
302
302
|
|
|
303
303
|
底层行为:
|
|
304
|
-
- **Windows**:在当前用户下免管理员权限注册 Windows 计划任务(`T3 Code QQBot
|
|
304
|
+
- **Windows**:在当前用户下免管理员权限注册 Windows 计划任务(`T3 Code QQBot`),通过 GUI 子系统宿主 `wscript.exe` 与 `state\run-service.vbs`(`SW_HIDE`)直接无窗拉起 `node.exe` 运行 `start --supervise --log-file`,在 Windows 10 及 Windows 11(默认 Windows Terminal)下均彻底零黑框弹窗、零任务栏残留;崩溃自动指数退避拉起,全部日志原生落盘至 `state\service.log`、`state\bridge.log` 与 `state\gateway.log`。执行 `t3-qqbot service stop` / `uninstall` 时会自动一并清理宿主与子进程,不留端口占用残留。
|
|
305
305
|
- **Linux**:自动生成并启用 `~/.config/systemd/user/t3-code-qqbot.service`(含 `Restart=always`、`RestartSec=5`、`KillMode=control-group`)。如需在退出 SSH 后持续运行,按安装完成时的提示执行一次 `sudo loginctl enable-linger "$USER"` 即可;日志通过 `journalctl --user -u t3-code-qqbot.service -f` 查看。
|
|
306
306
|
|
|
307
307
|
*(仓库 `scripts/` 目录下仍保留手工脚本模板 `install-windows-task.ps1` 与 `t3-code-qqbot.service` 供定制参考。)*
|
package/package.json
CHANGED
|
@@ -28,22 +28,56 @@ if (-not (Test-Path -LiteralPath $cliEntry)) {
|
|
|
28
28
|
throw "Missing $cliEntry. Build or extract a release package first."
|
|
29
29
|
}
|
|
30
30
|
|
|
31
|
-
$
|
|
32
|
-
|
|
33
|
-
|
|
31
|
+
$config = Get-Content -LiteralPath $ConfigPath -Raw -Encoding utf8 | ConvertFrom-Json
|
|
32
|
+
$stateDir = $config.stateDir
|
|
33
|
+
if (-not $stateDir) {
|
|
34
|
+
$stateDir = './state'
|
|
34
35
|
}
|
|
36
|
+
if (-not [System.IO.Path]::IsPathRooted($stateDir)) {
|
|
37
|
+
$stateDir = Join-Path (Split-Path -Parent $ConfigPath) $stateDir
|
|
38
|
+
}
|
|
39
|
+
$stateDir = [System.IO.Path]::GetFullPath($stateDir)
|
|
40
|
+
New-Item -Path $stateDir -ItemType Directory -Force | Out-Null
|
|
41
|
+
|
|
42
|
+
$logPath = Join-Path $stateDir 'service.log'
|
|
43
|
+
$launcherPath = Join-Path $stateDir 'run-service.vbs'
|
|
44
|
+
$workDir = Split-Path -Parent $ConfigPath
|
|
45
|
+
|
|
46
|
+
function Escape-VbsString([string]$Value) {
|
|
47
|
+
return '"' + ($Value -replace '"', '""') + '"'
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
$vbsContent = @(
|
|
51
|
+
'Option Explicit',
|
|
52
|
+
'Dim sh, nodePath, cliEntry, configPath, logPath, cmd, exitCode',
|
|
53
|
+
'Set sh = CreateObject("WScript.Shell")',
|
|
54
|
+
("sh.CurrentDirectory = " + (Escape-VbsString $workDir)),
|
|
55
|
+
'sh.Environment("Process")("NODE_NO_WARNINGS") = "1"',
|
|
56
|
+
("nodePath = " + (Escape-VbsString $NodePath)),
|
|
57
|
+
("cliEntry = " + (Escape-VbsString $cliEntry)),
|
|
58
|
+
("configPath = " + (Escape-VbsString $ConfigPath)),
|
|
59
|
+
("logPath = " + (Escape-VbsString $logPath)),
|
|
60
|
+
'cmd = """" & nodePath & """ """ & cliEntry & """ start --supervise --config """ & configPath & """ --log-file """ & logPath & """"',
|
|
61
|
+
'exitCode = sh.Run(cmd, 0, True)',
|
|
62
|
+
'WScript.Quit exitCode',
|
|
63
|
+
''
|
|
64
|
+
) -join "`r`n"
|
|
65
|
+
|
|
66
|
+
$utf16LeBom = New-Object System.Text.UnicodeEncoding($false, $true)
|
|
67
|
+
[System.IO.File]::WriteAllText($launcherPath, $vbsContent, $utf16LeBom)
|
|
35
68
|
|
|
36
|
-
|
|
69
|
+
# Use GUI-subsystem wscript.exe instead of CUI powershell.exe so Windows 10/11 (including Windows Terminal) never spawns a visible window.
|
|
70
|
+
$wscriptExe = Join-Path $env:WINDIR 'System32\wscript.exe'
|
|
37
71
|
$action = New-ScheduledTaskAction `
|
|
38
|
-
-Execute $
|
|
39
|
-
-Argument "
|
|
40
|
-
-WorkingDirectory $
|
|
72
|
+
-Execute $wscriptExe `
|
|
73
|
+
-Argument "//B //Nologo `"$launcherPath`"" `
|
|
74
|
+
-WorkingDirectory $workDir
|
|
41
75
|
|
|
42
76
|
$trigger = New-ScheduledTaskTrigger -AtLogOn -User $env:USERNAME
|
|
43
77
|
$settings = New-ScheduledTaskSettingsSet `
|
|
44
78
|
-AllowStartIfOnBatteries `
|
|
45
79
|
-DontStopIfGoingOnBatteries `
|
|
46
|
-
-RestartCount
|
|
80
|
+
-RestartCount 999 `
|
|
47
81
|
-RestartInterval (New-TimeSpan -Minutes 1) `
|
|
48
82
|
-ExecutionTimeLimit ([TimeSpan]::Zero)
|
|
49
83
|
|
|
@@ -55,6 +89,6 @@ Register-ScheduledTask `
|
|
|
55
89
|
-Description 'T3 Code QQBot Bridge & Official WebSocket Gateway' `
|
|
56
90
|
-Force | Out-Null
|
|
57
91
|
|
|
58
|
-
Write-Host "Registered Windows Scheduled Task '$TaskName' (Node $nodeVer)."
|
|
59
|
-
Write-Host "Logs will be written to
|
|
92
|
+
Write-Host "Registered zero-window Windows Scheduled Task '$TaskName' (Node $nodeVer, wscript launcher: $launcherPath)."
|
|
93
|
+
Write-Host "Logs will be written to $logPath, state\bridge.log, and state\gateway.log."
|
|
60
94
|
Write-Host "Start it now with: Start-ScheduledTask -TaskName '$TaskName'"
|
|
@@ -35,21 +35,8 @@ if (-not [System.IO.Path]::IsPathRooted($stateDir)) {
|
|
|
35
35
|
New-Item -Path $stateDir -ItemType Directory -Force | Out-Null
|
|
36
36
|
$logPath = Join-Path $stateDir 'service.log'
|
|
37
37
|
|
|
38
|
+
# Foreground/manual Windows runner. For zero-window background startup, use `t3-qqbot service install`
|
|
39
|
+
# or `scripts\install-windows-task.ps1` (which registers GUI-subsystem wscript.exe + run-service.vbs).
|
|
38
40
|
$env:NODE_NO_WARNINGS = '1'
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
# switch to Continue around the native command so warnings never abort the service.
|
|
42
|
-
$previousPreference = $ErrorActionPreference
|
|
43
|
-
$ErrorActionPreference = 'Continue'
|
|
44
|
-
try {
|
|
45
|
-
& $NodePath $cliEntry start --config $ConfigPath 2>&1 | ForEach-Object {
|
|
46
|
-
$text = if ($_ -is [System.Management.Automation.ErrorRecord]) { $_.ToString() } else { "$_" }
|
|
47
|
-
$line = '[{0:yyyy-MM-dd HH:mm:ss}] {1}' -f [DateTime]::Now, $text
|
|
48
|
-
Add-Content -LiteralPath $logPath -Encoding utf8 -Value $line
|
|
49
|
-
}
|
|
50
|
-
$exitCode = $LASTEXITCODE
|
|
51
|
-
} finally {
|
|
52
|
-
$ErrorActionPreference = $previousPreference
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
exit $exitCode
|
|
41
|
+
& $NodePath $cliEntry start --supervise --config $ConfigPath --log-file $logPath
|
|
42
|
+
exit $LASTEXITCODE
|