opencode-supertask 0.1.41 → 0.2.1
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/CHANGELOG.md +86 -0
- package/README.md +66 -39
- package/README.zh-CN.md +66 -39
- package/dist/cli/chunk-3PIYMBV3.js +45 -0
- package/dist/cli/chunk-3PIYMBV3.js.map +1 -0
- package/dist/cli/chunk-4FK5KE6G.js +111 -0
- package/dist/cli/chunk-4FK5KE6G.js.map +1 -0
- package/dist/cli/chunk-5VKFECHP.js +412 -0
- package/dist/cli/chunk-5VKFECHP.js.map +1 -0
- package/dist/cli/chunk-AZM76ISG.js +143 -0
- package/dist/cli/chunk-AZM76ISG.js.map +1 -0
- package/dist/cli/chunk-CMEP6IB4.js +9379 -0
- package/dist/cli/chunk-CMEP6IB4.js.map +1 -0
- package/dist/cli/chunk-DF56RPNL.js +65 -0
- package/dist/cli/chunk-DF56RPNL.js.map +1 -0
- package/dist/cli/chunk-DIJEKFBV.js +486 -0
- package/dist/cli/chunk-DIJEKFBV.js.map +1 -0
- package/dist/cli/chunk-DYXFSX5J.js +28 -0
- package/dist/cli/chunk-DYXFSX5J.js.map +1 -0
- package/dist/cli/chunk-EQWICVCJ.js +1701 -0
- package/dist/cli/chunk-EQWICVCJ.js.map +1 -0
- package/dist/cli/chunk-GHXFMJTS.js +42 -0
- package/dist/cli/chunk-GHXFMJTS.js.map +1 -0
- package/dist/cli/chunk-IYYBJHZF.js +28 -0
- package/dist/cli/chunk-IYYBJHZF.js.map +1 -0
- package/dist/cli/chunk-J34FWHQU.js +376 -0
- package/dist/cli/chunk-J34FWHQU.js.map +1 -0
- package/dist/cli/chunk-LX5CBJLP.js +121 -0
- package/dist/cli/chunk-LX5CBJLP.js.map +1 -0
- package/dist/cli/chunk-MVQ2XONT.js +139 -0
- package/dist/cli/chunk-MVQ2XONT.js.map +1 -0
- package/dist/cli/chunk-NCT3ETTK.js +1332 -0
- package/dist/cli/chunk-NCT3ETTK.js.map +1 -0
- package/dist/cli/chunk-YB7MYTE5.js +34 -0
- package/dist/cli/chunk-YB7MYTE5.js.map +1 -0
- package/dist/cli/chunk-YGELD2E5.js +5464 -0
- package/dist/cli/chunk-YGELD2E5.js.map +1 -0
- package/dist/cli/chunk-ZBH7YWXF.js +314 -0
- package/dist/cli/chunk-ZBH7YWXF.js.map +1 -0
- package/dist/cli/config-ED56ZLHY.js +20 -0
- package/dist/cli/config-ED56ZLHY.js.map +1 -0
- package/dist/cli/database-maintenance.service-F3IZU52F.js +16 -0
- package/dist/cli/database-maintenance.service-F3IZU52F.js.map +1 -0
- package/dist/cli/database-output-GH7F6X6D.js +165 -0
- package/dist/cli/database-output-GH7F6X6D.js.map +1 -0
- package/dist/cli/db-H7GIFWS2.js +26 -0
- package/dist/cli/db-H7GIFWS2.js.map +1 -0
- package/dist/cli/doctor-smoke-QXHF7UNN.js +150 -0
- package/dist/cli/doctor-smoke-QXHF7UNN.js.map +1 -0
- package/dist/cli/duration-Q3UMLO6F.js +10 -0
- package/dist/cli/duration-Q3UMLO6F.js.map +1 -0
- package/dist/cli/gateway-BYLLK72W.js +1738 -0
- package/dist/cli/gateway-BYLLK72W.js.map +1 -0
- package/dist/cli/gateway-wake-U4HTV56Q.js +14 -0
- package/dist/cli/gateway-wake-U4HTV56Q.js.map +1 -0
- package/dist/cli/index.js +626 -26583
- package/dist/cli/index.js.map +1 -1
- package/dist/cli/job-templates-RPQJ4XXW.js +21 -0
- package/dist/cli/job-templates-RPQJ4XXW.js.map +1 -0
- package/dist/cli/logs-QD2N62KK.js +316 -0
- package/dist/cli/logs-QD2N62KK.js.map +1 -0
- package/dist/cli/output-2INTEUFQ.js +19 -0
- package/dist/cli/output-2INTEUFQ.js.map +1 -0
- package/dist/cli/pm2-WY644BUO.js +49 -0
- package/dist/cli/pm2-WY644BUO.js.map +1 -0
- package/dist/cli/task-run.service-QMDINJKG.js +15 -0
- package/dist/cli/task-run.service-QMDINJKG.js.map +1 -0
- package/dist/cli/task-template.service-SZBKGLCB.js +12 -0
- package/dist/cli/task-template.service-SZBKGLCB.js.map +1 -0
- package/dist/cli/task.service-ZVDJ6VSQ.js +19 -0
- package/dist/cli/task.service-ZVDJ6VSQ.js.map +1 -0
- package/dist/cli/update-FYD546I2.js +2058 -0
- package/dist/cli/update-FYD546I2.js.map +1 -0
- package/dist/cli/web-J3FJ23FE.js +9833 -0
- package/dist/cli/web-J3FJ23FE.js.map +1 -0
- package/dist/daemon/gateway-diagnostic-runner.js +280 -238
- package/dist/daemon/gateway-diagnostic-runner.js.map +1 -1
- package/dist/gateway/index.d.ts +82 -1
- package/dist/gateway/index.js +9695 -2661
- package/dist/gateway/index.js.map +1 -1
- package/dist/plugin/supertask.d.ts +157 -1
- package/dist/plugin/supertask.js +5056 -1550
- package/dist/plugin/supertask.js.map +1 -1
- package/dist/pm2-cli-CEDhULjk.d.ts +40 -0
- package/dist/web/index.d.ts +36 -34
- package/dist/web/index.js +10283 -3908
- package/dist/web/index.js.map +1 -1
- package/dist/worker/index.d.ts +5 -0
- package/dist/worker/index.js +1989 -331
- package/dist/worker/index.js.map +1 -1
- package/dist/worker/launcher.d.ts +46 -1
- package/dist/worker/launcher.js +218 -68
- package/dist/worker/launcher.js.map +1 -1
- package/drizzle/0009_little_weapon_omega.sql +7 -0
- package/drizzle/meta/0009_snapshot.json +681 -0
- package/drizzle/meta/_journal.json +7 -0
- package/package.json +4 -4
|
@@ -0,0 +1,314 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
LAUNCH_IDENTITY_ARGUMENT,
|
|
5
|
+
TOKEN_GUARDIAN_LAUNCH_PROTOCOL,
|
|
6
|
+
isLaunchIdentity
|
|
7
|
+
} from "./chunk-YB7MYTE5.js";
|
|
8
|
+
|
|
9
|
+
// src/core/process-control.ts
|
|
10
|
+
import { fileURLToPath } from "url";
|
|
11
|
+
import { readFileSync } from "fs";
|
|
12
|
+
import { basename, dirname, resolve } from "path";
|
|
13
|
+
var OS_COMMAND_TIMEOUT_MS = 2e3;
|
|
14
|
+
var OS_COMMAND_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;
|
|
15
|
+
var OS_COMMAND_RESULT_MARKER = "\n\0supertask-os-command-result:";
|
|
16
|
+
var BOUNDED_OS_COMMAND_RUNNER = `
|
|
17
|
+
const { writeSync } = await import('fs');
|
|
18
|
+
let child;
|
|
19
|
+
try {
|
|
20
|
+
child = Bun.spawn(process.argv.slice(2), {
|
|
21
|
+
stdin: 'ignore',
|
|
22
|
+
stdout: 'pipe',
|
|
23
|
+
stderr: 'ignore',
|
|
24
|
+
});
|
|
25
|
+
} catch {
|
|
26
|
+
process.exit(127);
|
|
27
|
+
}
|
|
28
|
+
const terminateGroup = () => {
|
|
29
|
+
if (process.platform !== 'win32') {
|
|
30
|
+
try {
|
|
31
|
+
process.kill(-process.pid, 'SIGKILL');
|
|
32
|
+
} catch {
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
try {
|
|
36
|
+
child.kill('SIGKILL');
|
|
37
|
+
} catch {
|
|
38
|
+
}
|
|
39
|
+
process.exit(1);
|
|
40
|
+
};
|
|
41
|
+
const timer = setTimeout(terminateGroup, ${OS_COMMAND_TIMEOUT_MS});
|
|
42
|
+
try {
|
|
43
|
+
const chunks = [];
|
|
44
|
+
let outputBytes = 0;
|
|
45
|
+
const readOutput = async () => {
|
|
46
|
+
const reader = child.stdout.getReader();
|
|
47
|
+
while (true) {
|
|
48
|
+
const { done, value } = await reader.read();
|
|
49
|
+
if (done) return;
|
|
50
|
+
outputBytes += value.byteLength;
|
|
51
|
+
if (outputBytes > ${OS_COMMAND_MAX_OUTPUT_BYTES}) terminateGroup();
|
|
52
|
+
chunks.push(value);
|
|
53
|
+
}
|
|
54
|
+
};
|
|
55
|
+
const [exitCode] = await Promise.all([child.exited, readOutput()]);
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
for (const chunk of chunks) writeSync(1, chunk);
|
|
58
|
+
writeSync(1, ${JSON.stringify(OS_COMMAND_RESULT_MARKER)} + String(exitCode));
|
|
59
|
+
if (process.platform !== 'win32') terminateGroup();
|
|
60
|
+
process.exit(0);
|
|
61
|
+
} catch {
|
|
62
|
+
clearTimeout(timer);
|
|
63
|
+
terminateGroup();
|
|
64
|
+
}
|
|
65
|
+
`;
|
|
66
|
+
var SUPPORTS_NATIVE_SPAWN_SYNC_TIMEOUT = (() => {
|
|
67
|
+
const version = typeof Bun !== "undefined" ? Bun.version : "";
|
|
68
|
+
const match = /^(\d+)\.(\d+)/.exec(version);
|
|
69
|
+
if (!match) return false;
|
|
70
|
+
const major = Number(match[1]);
|
|
71
|
+
const minor = Number(match[2]);
|
|
72
|
+
return major > 1 || major === 1 && minor >= 2;
|
|
73
|
+
})();
|
|
74
|
+
function runBoundedOsCommand(command, args, captureOutput = true) {
|
|
75
|
+
if (SUPPORTS_NATIVE_SPAWN_SYNC_TIMEOUT) {
|
|
76
|
+
try {
|
|
77
|
+
const result2 = Bun.spawnSync({
|
|
78
|
+
cmd: [command, ...args],
|
|
79
|
+
timeout: OS_COMMAND_TIMEOUT_MS,
|
|
80
|
+
maxBuffer: OS_COMMAND_MAX_OUTPUT_BYTES,
|
|
81
|
+
detached: process.platform !== "win32",
|
|
82
|
+
stdin: "ignore",
|
|
83
|
+
stdout: captureOutput ? "pipe" : "ignore",
|
|
84
|
+
stderr: "ignore"
|
|
85
|
+
});
|
|
86
|
+
if (process.platform !== "win32" && result2.pid > 1) {
|
|
87
|
+
try {
|
|
88
|
+
process.kill(-result2.pid, "SIGKILL");
|
|
89
|
+
} catch {
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
if (result2.signalCode || result2.exitCode === null) {
|
|
93
|
+
return { status: null, stdout: "" };
|
|
94
|
+
}
|
|
95
|
+
return {
|
|
96
|
+
status: result2.exitCode,
|
|
97
|
+
stdout: captureOutput && result2.stdout ? new TextDecoder().decode(result2.stdout) : ""
|
|
98
|
+
};
|
|
99
|
+
} catch {
|
|
100
|
+
return { status: null, stdout: "" };
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
const result = Bun.spawnSync({
|
|
104
|
+
cmd: [
|
|
105
|
+
process.execPath,
|
|
106
|
+
"-e",
|
|
107
|
+
BOUNDED_OS_COMMAND_RUNNER,
|
|
108
|
+
"supertask-os-command",
|
|
109
|
+
command,
|
|
110
|
+
...args
|
|
111
|
+
],
|
|
112
|
+
detached: process.platform !== "win32",
|
|
113
|
+
maxBuffer: OS_COMMAND_MAX_OUTPUT_BYTES + 1024,
|
|
114
|
+
stdin: "ignore",
|
|
115
|
+
stdout: "pipe",
|
|
116
|
+
stderr: "ignore"
|
|
117
|
+
});
|
|
118
|
+
const output = new TextDecoder().decode(result.stdout);
|
|
119
|
+
const markerIndex = output.lastIndexOf(OS_COMMAND_RESULT_MARKER);
|
|
120
|
+
if (markerIndex < 0) return { status: null, stdout: "" };
|
|
121
|
+
const statusText = output.slice(markerIndex + OS_COMMAND_RESULT_MARKER.length);
|
|
122
|
+
if (!/^\d+$/.test(statusText)) return { status: null, stdout: "" };
|
|
123
|
+
return {
|
|
124
|
+
status: Number(statusText),
|
|
125
|
+
stdout: captureOutput ? output.slice(0, markerIndex) : ""
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
function isSafePid(pid) {
|
|
129
|
+
return Number.isInteger(pid) && pid > 1 && pid !== process.pid;
|
|
130
|
+
}
|
|
131
|
+
function absentLeaderResult(pid) {
|
|
132
|
+
return inspectSpawnedProcessTreePresence(pid) === "not-running" ? "not-running" : "inspect-failed";
|
|
133
|
+
}
|
|
134
|
+
function isProcessAlive(pid) {
|
|
135
|
+
if (!Number.isInteger(pid) || pid <= 0) return false;
|
|
136
|
+
try {
|
|
137
|
+
process.kill(pid, 0);
|
|
138
|
+
return true;
|
|
139
|
+
} catch (error) {
|
|
140
|
+
return error instanceof Error && "code" in error && error.code === "EPERM";
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
function inspectSpawnedProcessTreePresence(pid) {
|
|
144
|
+
if (!Number.isInteger(pid) || pid <= 0) return "unknown";
|
|
145
|
+
if (process.platform === "win32") {
|
|
146
|
+
const processIds = inspectWindowsProcessTree(pid);
|
|
147
|
+
if (processIds == null) return "unknown";
|
|
148
|
+
return processIds.length > 0 ? "running" : "not-running";
|
|
149
|
+
}
|
|
150
|
+
try {
|
|
151
|
+
process.kill(-pid, 0);
|
|
152
|
+
return "running";
|
|
153
|
+
} catch (error) {
|
|
154
|
+
if (!(error instanceof Error) || !("code" in error)) return "unknown";
|
|
155
|
+
if (error.code === "EPERM") return "running";
|
|
156
|
+
if (error.code === "ESRCH") return "not-running";
|
|
157
|
+
return "unknown";
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
function inspectLinuxProcProcess(pid) {
|
|
161
|
+
try {
|
|
162
|
+
const stat = readFileSync(`/proc/${pid}/stat`, "utf8");
|
|
163
|
+
const closeParen = stat.lastIndexOf(")");
|
|
164
|
+
if (closeParen < 0) return null;
|
|
165
|
+
const fields = stat.slice(closeParen + 2).trim().split(/\s+/);
|
|
166
|
+
const processGroupId = Number(fields[2]);
|
|
167
|
+
if (!Number.isInteger(processGroupId) || processGroupId <= 0) return null;
|
|
168
|
+
const rawCmdline = readFileSync(`/proc/${pid}/cmdline`);
|
|
169
|
+
if (rawCmdline.byteLength === 0) return null;
|
|
170
|
+
const command = new TextDecoder().decode(rawCmdline).replace(/\0+$/, "").replaceAll("\0", " ").trim();
|
|
171
|
+
if (!command) return null;
|
|
172
|
+
return { processGroupId, command };
|
|
173
|
+
} catch {
|
|
174
|
+
return null;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function inspectUnixProcess(pid) {
|
|
178
|
+
if (process.platform === "linux") {
|
|
179
|
+
const procInfo = inspectLinuxProcProcess(pid);
|
|
180
|
+
if (procInfo) return procInfo;
|
|
181
|
+
}
|
|
182
|
+
const result = runBoundedOsCommand(
|
|
183
|
+
"ps",
|
|
184
|
+
["-o", "pgid=", "-o", "command=", "-p", String(pid)]
|
|
185
|
+
);
|
|
186
|
+
if (result.status !== 0) return null;
|
|
187
|
+
const match = result.stdout.trim().match(/^(\d+)\s+(.+)$/s);
|
|
188
|
+
if (!match) return null;
|
|
189
|
+
return { processGroupId: Number(match[1]), command: match[2] };
|
|
190
|
+
}
|
|
191
|
+
function inspectWindowsCommand(pid) {
|
|
192
|
+
const script = `(Get-CimInstance Win32_Process -Filter "ProcessId = ${pid}").CommandLine`;
|
|
193
|
+
const result = runBoundedOsCommand(
|
|
194
|
+
"powershell.exe",
|
|
195
|
+
["-NoProfile", "-NonInteractive", "-Command", script]
|
|
196
|
+
);
|
|
197
|
+
if (result.status !== 0) return null;
|
|
198
|
+
return result.stdout.trim() || null;
|
|
199
|
+
}
|
|
200
|
+
function inspectWindowsProcessTree(rootPid) {
|
|
201
|
+
const script = `$root=${rootPid}; $all=@(Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId); $ids=New-Object 'System.Collections.Generic.HashSet[int]'; [void]$ids.Add($root); do { $added=$false; foreach($p in $all) { if($ids.Contains([int]$p.ParentProcessId) -and $ids.Add([int]$p.ProcessId)) { $added=$true } } } while($added); $all | Where-Object { $ids.Contains([int]$_.ProcessId) } | Select-Object -ExpandProperty ProcessId`;
|
|
202
|
+
const result = runBoundedOsCommand(
|
|
203
|
+
"powershell.exe",
|
|
204
|
+
["-NoProfile", "-NonInteractive", "-Command", script]
|
|
205
|
+
);
|
|
206
|
+
if (result.status !== 0) return null;
|
|
207
|
+
return result.stdout.split(/\s+/).filter(Boolean).map(Number).filter((pid) => Number.isInteger(pid) && pid > 0);
|
|
208
|
+
}
|
|
209
|
+
function executableName(value) {
|
|
210
|
+
return basename(value).trim().toLowerCase().replace(/\.(?:exe|cmd|bat)$/i, "");
|
|
211
|
+
}
|
|
212
|
+
function commandTokens(command) {
|
|
213
|
+
return command.trim().split(/\s+/).map((token) => token.replace(/^["']|["']$/g, ""));
|
|
214
|
+
}
|
|
215
|
+
function openCodeArgsMatch(args) {
|
|
216
|
+
const agentIndex = args.indexOf("--agent");
|
|
217
|
+
const formatIndex = args.indexOf("--format");
|
|
218
|
+
return args[0] === "run" && agentIndex >= 0 && Boolean(args[agentIndex + 1]) && formatIndex >= 0 && args[formatIndex + 1] === "json";
|
|
219
|
+
}
|
|
220
|
+
function guardianLauncherPath() {
|
|
221
|
+
const extension = import.meta.url.endsWith(".ts") ? "ts" : "js";
|
|
222
|
+
return resolve(dirname(fileURLToPath(import.meta.url)), `../worker/launcher.${extension}`).replaceAll("\\", "/");
|
|
223
|
+
}
|
|
224
|
+
function commandMatches(command, expectedExecutable, launchProtocol, expectedLaunchIdentity) {
|
|
225
|
+
const expectedName = executableName(expectedExecutable);
|
|
226
|
+
if (!expectedName) return false;
|
|
227
|
+
if (launchProtocol === TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {
|
|
228
|
+
if (!isLaunchIdentity(expectedLaunchIdentity)) return false;
|
|
229
|
+
const normalized = command.trim().replaceAll("\\", "/");
|
|
230
|
+
const marker = ` ${guardianLauncherPath()} ${LAUNCH_IDENTITY_ARGUMENT} ${expectedLaunchIdentity} `;
|
|
231
|
+
const markerIndex = normalized.indexOf(marker);
|
|
232
|
+
if (markerIndex <= 0) return false;
|
|
233
|
+
const runtime = normalized.slice(0, markerIndex);
|
|
234
|
+
const runtimeName = executableName(process.execPath);
|
|
235
|
+
const hasRuntime = [runtime, ...runtime.split(/\s+/)].some((token) => executableName(token) === runtimeName || executableName(token) === "bun");
|
|
236
|
+
const invocation = normalized.slice(markerIndex + marker.length);
|
|
237
|
+
const runIndex = invocation.indexOf(" run ");
|
|
238
|
+
if (runIndex <= 0) return false;
|
|
239
|
+
return hasRuntime && executableName(invocation.slice(0, runIndex)) === expectedName && openCodeArgsMatch(commandTokens(invocation.slice(runIndex + 1)));
|
|
240
|
+
}
|
|
241
|
+
if (launchProtocol != null) return false;
|
|
242
|
+
const tokens = commandTokens(command);
|
|
243
|
+
const executableIndex = tokens.findIndex((token, index) => index <= 3 && executableName(token) === expectedName);
|
|
244
|
+
if (executableIndex < 0) return false;
|
|
245
|
+
return openCodeArgsMatch(tokens.slice(executableIndex + 1, executableIndex + 12));
|
|
246
|
+
}
|
|
247
|
+
function identifyGatewayProcess(pid) {
|
|
248
|
+
if (!isProcessAlive(pid)) return "not-running";
|
|
249
|
+
const command = process.platform === "win32" ? inspectWindowsCommand(pid) : inspectUnixProcess(pid)?.command ?? null;
|
|
250
|
+
if (!command) return "unknown";
|
|
251
|
+
const tokens = command.trim().split(/\s+/).map((token) => token.replace(/^['"]|['"]$/g, "").replaceAll("\\", "/"));
|
|
252
|
+
const runtimeName = executableName(process.execPath);
|
|
253
|
+
const hasRuntime = tokens.slice(0, 4).some((token) => executableName(token) === runtimeName || executableName(token) === "bun");
|
|
254
|
+
const hasGatewayEntry = tokens.some((token) => /(?:^|\/)gateway\/index\.(?:js|ts)$/.test(token));
|
|
255
|
+
const cliEntryIndex = tokens.findIndex((token) => /(?:^|\/)cli\/index\.(?:js|ts)$/.test(token));
|
|
256
|
+
const hasCliGatewayCommand = cliEntryIndex >= 0 && tokens.slice(cliEntryIndex + 1).includes("gateway");
|
|
257
|
+
const supertaskIndex = tokens.findIndex((token, index) => index <= 3 && executableName(token) === "supertask");
|
|
258
|
+
const hasBinGatewayCommand = supertaskIndex >= 0 && tokens[supertaskIndex + 1] === "gateway";
|
|
259
|
+
return hasRuntime && (hasGatewayEntry || hasCliGatewayCommand || hasBinGatewayCommand) ? "match" : "mismatch";
|
|
260
|
+
}
|
|
261
|
+
function signalRecordedProcessTreeWithResult(pid, signal, expectedExecutable, launchProtocol = null, expectedLaunchIdentity = null) {
|
|
262
|
+
if (!isSafePid(pid)) return "identity-mismatch";
|
|
263
|
+
if (!isProcessAlive(pid)) return absentLeaderResult(pid);
|
|
264
|
+
if (process.platform === "win32") {
|
|
265
|
+
const command = inspectWindowsCommand(pid);
|
|
266
|
+
if (!command) return isProcessAlive(pid) ? "inspect-failed" : absentLeaderResult(pid);
|
|
267
|
+
if (!commandMatches(
|
|
268
|
+
command,
|
|
269
|
+
expectedExecutable,
|
|
270
|
+
launchProtocol,
|
|
271
|
+
expectedLaunchIdentity
|
|
272
|
+
)) {
|
|
273
|
+
return "identity-mismatch";
|
|
274
|
+
}
|
|
275
|
+
const args = ["/PID", String(pid), "/T"];
|
|
276
|
+
if (signal === "SIGKILL") args.push("/F");
|
|
277
|
+
const status = runBoundedOsCommand("taskkill", args, false).status;
|
|
278
|
+
if (status === 0) return "signalled";
|
|
279
|
+
return isProcessAlive(pid) ? "signal-failed" : absentLeaderResult(pid);
|
|
280
|
+
}
|
|
281
|
+
const info = inspectUnixProcess(pid);
|
|
282
|
+
if (!info) return isProcessAlive(pid) ? "inspect-failed" : absentLeaderResult(pid);
|
|
283
|
+
if (!commandMatches(
|
|
284
|
+
info.command,
|
|
285
|
+
expectedExecutable,
|
|
286
|
+
launchProtocol,
|
|
287
|
+
expectedLaunchIdentity
|
|
288
|
+
)) {
|
|
289
|
+
return "identity-mismatch";
|
|
290
|
+
}
|
|
291
|
+
try {
|
|
292
|
+
if (info.processGroupId === pid) process.kill(-pid, signal);
|
|
293
|
+
else process.kill(pid, signal);
|
|
294
|
+
return "signalled";
|
|
295
|
+
} catch {
|
|
296
|
+
return isProcessAlive(pid) ? "signal-failed" : absentLeaderResult(pid);
|
|
297
|
+
}
|
|
298
|
+
}
|
|
299
|
+
async function waitForSpawnedProcessTreeExit(pid, timeoutMs = 5e3) {
|
|
300
|
+
const deadline = Date.now() + timeoutMs;
|
|
301
|
+
while (inspectSpawnedProcessTreePresence(pid) !== "not-running" && Date.now() < deadline) {
|
|
302
|
+
await Bun.sleep(Math.min(50, deadline - Date.now()));
|
|
303
|
+
}
|
|
304
|
+
return inspectSpawnedProcessTreePresence(pid) === "not-running";
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
export {
|
|
308
|
+
isProcessAlive,
|
|
309
|
+
inspectSpawnedProcessTreePresence,
|
|
310
|
+
identifyGatewayProcess,
|
|
311
|
+
signalRecordedProcessTreeWithResult,
|
|
312
|
+
waitForSpawnedProcessTreeExit
|
|
313
|
+
};
|
|
314
|
+
//# sourceMappingURL=chunk-ZBH7YWXF.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/core/process-control.ts"],"sourcesContent":["import { fileURLToPath } from 'url';\nimport { readFileSync } from 'fs';\nimport { basename, dirname, resolve } from 'path';\nimport {\n isLaunchIdentity,\n LAUNCH_IDENTITY_ARGUMENT,\n TOKEN_GUARDIAN_LAUNCH_PROTOCOL,\n} from '@core/launch-protocol';\n\ninterface ProcessInfo {\n processGroupId: number;\n command: string;\n}\n\nconst OS_COMMAND_TIMEOUT_MS = 2_000;\nconst OS_COMMAND_MAX_OUTPUT_BYTES = 4 * 1024 * 1024;\nconst OS_COMMAND_RESULT_MARKER = '\\n\\0supertask-os-command-result:';\nconst BOUNDED_OS_COMMAND_RUNNER = `\nconst { writeSync } = await import('fs');\nlet child;\ntry {\n child = Bun.spawn(process.argv.slice(2), {\n stdin: 'ignore',\n stdout: 'pipe',\n stderr: 'ignore',\n });\n} catch {\n process.exit(127);\n}\nconst terminateGroup = () => {\n if (process.platform !== 'win32') {\n try {\n process.kill(-process.pid, 'SIGKILL');\n } catch {\n }\n }\n try {\n child.kill('SIGKILL');\n } catch {\n }\n process.exit(1);\n};\nconst timer = setTimeout(terminateGroup, ${OS_COMMAND_TIMEOUT_MS});\ntry {\n const chunks = [];\n let outputBytes = 0;\n const readOutput = async () => {\n const reader = child.stdout.getReader();\n while (true) {\n const { done, value } = await reader.read();\n if (done) return;\n outputBytes += value.byteLength;\n if (outputBytes > ${OS_COMMAND_MAX_OUTPUT_BYTES}) terminateGroup();\n chunks.push(value);\n }\n };\n const [exitCode] = await Promise.all([child.exited, readOutput()]);\n clearTimeout(timer);\n for (const chunk of chunks) writeSync(1, chunk);\n writeSync(1, ${JSON.stringify(OS_COMMAND_RESULT_MARKER)} + String(exitCode));\n if (process.platform !== 'win32') terminateGroup();\n process.exit(0);\n} catch {\n clearTimeout(timer);\n terminateGroup();\n}\n`;\n\nexport type RecordedProcessSignalResult =\n | 'signalled'\n | 'not-running'\n | 'identity-mismatch'\n | 'inspect-failed'\n | 'signal-failed';\n\nexport type GatewayProcessIdentity = 'match' | 'mismatch' | 'unknown' | 'not-running';\nexport type SpawnedProcessTreePresence = 'running' | 'not-running' | 'unknown';\n\nconst SUPPORTS_NATIVE_SPAWN_SYNC_TIMEOUT = (() => {\n const version = typeof Bun !== 'undefined' ? Bun.version : '';\n const match = /^(\\d+)\\.(\\d+)/.exec(version);\n if (!match) return false;\n const major = Number(match[1]);\n const minor = Number(match[2]);\n return major > 1 || (major === 1 && minor >= 2);\n})();\n\nfunction runBoundedOsCommand(\n command: string,\n args: string[],\n captureOutput = true,\n): { status: number | null; stdout: string } {\n if (SUPPORTS_NATIVE_SPAWN_SYNC_TIMEOUT) {\n try {\n const result = Bun.spawnSync({\n cmd: [command, ...args],\n timeout: OS_COMMAND_TIMEOUT_MS,\n maxBuffer: OS_COMMAND_MAX_OUTPUT_BYTES,\n detached: process.platform !== 'win32',\n stdin: 'ignore',\n stdout: captureOutput ? 'pipe' : 'ignore',\n stderr: 'ignore',\n });\n if (process.platform !== 'win32' && result.pid > 1) {\n try {\n process.kill(-result.pid, 'SIGKILL');\n } catch {\n }\n }\n if (result.signalCode || result.exitCode === null) {\n return { status: null, stdout: '' };\n }\n return {\n status: result.exitCode,\n stdout: captureOutput && result.stdout\n ? new TextDecoder().decode(result.stdout)\n : '',\n };\n } catch {\n return { status: null, stdout: '' };\n }\n }\n\n // Bun 1.1.45 ignores child_process.spawnSync timeouts. The helper remains\n // synchronous to callers while enforcing the deadline with Bun.spawn.\n const result = Bun.spawnSync({\n cmd: [\n process.execPath,\n '-e',\n BOUNDED_OS_COMMAND_RUNNER,\n 'supertask-os-command',\n command,\n ...args,\n ],\n detached: process.platform !== 'win32',\n maxBuffer: OS_COMMAND_MAX_OUTPUT_BYTES + 1024,\n stdin: 'ignore',\n stdout: 'pipe',\n stderr: 'ignore',\n });\n const output = new TextDecoder().decode(result.stdout);\n const markerIndex = output.lastIndexOf(OS_COMMAND_RESULT_MARKER);\n if (markerIndex < 0) return { status: null, stdout: '' };\n const statusText = output.slice(markerIndex + OS_COMMAND_RESULT_MARKER.length);\n if (!/^\\d+$/.test(statusText)) return { status: null, stdout: '' };\n return {\n status: Number(statusText),\n stdout: captureOutput ? output.slice(0, markerIndex) : '',\n };\n}\n\nfunction isSafePid(pid: number): boolean {\n return Number.isInteger(pid) && pid > 1 && pid !== process.pid;\n}\n\nfunction absentLeaderResult(pid: number): RecordedProcessSignalResult {\n return inspectSpawnedProcessTreePresence(pid) === 'not-running'\n ? 'not-running'\n : 'inspect-failed';\n}\n\nexport function isProcessAlive(pid: number): boolean {\n if (!Number.isInteger(pid) || pid <= 0) return false;\n try {\n process.kill(pid, 0);\n return true;\n } catch (error) {\n return error instanceof Error && 'code' in error && error.code === 'EPERM';\n }\n}\n\nexport function isSpawnedProcessTreeAlive(pid: number): boolean {\n return inspectSpawnedProcessTreePresence(pid) === 'running';\n}\n\nexport function inspectSpawnedProcessTreePresence(pid: number): SpawnedProcessTreePresence {\n if (!Number.isInteger(pid) || pid <= 0) return 'unknown';\n if (process.platform === 'win32') {\n const processIds = inspectWindowsProcessTree(pid);\n if (processIds == null) return 'unknown';\n return processIds.length > 0 ? 'running' : 'not-running';\n }\n try {\n process.kill(-pid, 0);\n return 'running';\n } catch (error) {\n if (!(error instanceof Error) || !('code' in error)) return 'unknown';\n if (error.code === 'EPERM') return 'running';\n if (error.code === 'ESRCH') return 'not-running';\n return 'unknown';\n }\n}\n\nfunction inspectLinuxProcProcess(pid: number): ProcessInfo | null {\n try {\n const stat = readFileSync(`/proc/${pid}/stat`, 'utf8');\n const closeParen = stat.lastIndexOf(')');\n if (closeParen < 0) return null;\n const fields = stat.slice(closeParen + 2).trim().split(/\\s+/);\n const processGroupId = Number(fields[2]);\n if (!Number.isInteger(processGroupId) || processGroupId <= 0) return null;\n\n const rawCmdline = readFileSync(`/proc/${pid}/cmdline`);\n if (rawCmdline.byteLength === 0) return null;\n const command = new TextDecoder()\n .decode(rawCmdline)\n .replace(/\\0+$/, '')\n .replaceAll('\\0', ' ')\n .trim();\n if (!command) return null;\n return { processGroupId, command };\n } catch {\n return null;\n }\n}\n\nfunction inspectUnixProcess(pid: number): ProcessInfo | null {\n if (process.platform === 'linux') {\n const procInfo = inspectLinuxProcProcess(pid);\n if (procInfo) return procInfo;\n }\n const result = runBoundedOsCommand(\n 'ps',\n ['-o', 'pgid=', '-o', 'command=', '-p', String(pid)],\n );\n if (result.status !== 0) return null;\n const match = result.stdout.trim().match(/^(\\d+)\\s+(.+)$/s);\n if (!match) return null;\n return { processGroupId: Number(match[1]), command: match[2] };\n}\n\nfunction inspectWindowsCommand(pid: number): string | null {\n const script = `(Get-CimInstance Win32_Process -Filter \"ProcessId = ${pid}\").CommandLine`;\n const result = runBoundedOsCommand(\n 'powershell.exe',\n ['-NoProfile', '-NonInteractive', '-Command', script],\n );\n if (result.status !== 0) return null;\n return result.stdout.trim() || null;\n}\n\nfunction inspectWindowsProcessTree(rootPid: number): number[] | null {\n const script = `$root=${rootPid}; $all=@(Get-CimInstance Win32_Process | Select-Object ProcessId,ParentProcessId); $ids=New-Object 'System.Collections.Generic.HashSet[int]'; [void]$ids.Add($root); do { $added=$false; foreach($p in $all) { if($ids.Contains([int]$p.ParentProcessId) -and $ids.Add([int]$p.ProcessId)) { $added=$true } } } while($added); $all | Where-Object { $ids.Contains([int]$_.ProcessId) } | Select-Object -ExpandProperty ProcessId`;\n const result = runBoundedOsCommand(\n 'powershell.exe',\n ['-NoProfile', '-NonInteractive', '-Command', script],\n );\n if (result.status !== 0) return null;\n return result.stdout\n .split(/\\s+/)\n .filter(Boolean)\n .map(Number)\n .filter((pid) => Number.isInteger(pid) && pid > 0);\n}\n\nfunction executableName(value: string): string {\n return basename(value).trim().toLowerCase().replace(/\\.(?:exe|cmd|bat)$/i, '');\n}\n\nfunction commandTokens(command: string): string[] {\n return command\n .trim()\n .split(/\\s+/)\n .map((token) => token.replace(/^[\"']|[\"']$/g, ''));\n}\n\nfunction openCodeArgsMatch(args: string[]): boolean {\n const agentIndex = args.indexOf('--agent');\n const formatIndex = args.indexOf('--format');\n return args[0] === 'run'\n && agentIndex >= 0\n && Boolean(args[agentIndex + 1])\n && formatIndex >= 0\n && args[formatIndex + 1] === 'json';\n}\n\nfunction guardianLauncherPath(): string {\n const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';\n return resolve(dirname(fileURLToPath(import.meta.url)), `../worker/launcher.${extension}`)\n .replaceAll('\\\\', '/');\n}\n\nfunction commandMatches(\n command: string,\n expectedExecutable: string,\n launchProtocol: string | null,\n expectedLaunchIdentity: string | null,\n): boolean {\n const expectedName = executableName(expectedExecutable);\n if (!expectedName) return false;\n\n if (launchProtocol === TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {\n if (!isLaunchIdentity(expectedLaunchIdentity)) return false;\n // ps 以空格拼接 argv 且不加引号:安装路径或 OpenCode 路径含空格时逐 token 解析会失真。\n // 以“launcher 路径 + 身份参数 + 每 run UUID”这一唯一序列定位,再分别校验其前的运行时和其后的 OpenCode 调用。\n const normalized = command.trim().replaceAll('\\\\', '/');\n const marker = ` ${guardianLauncherPath()} ${LAUNCH_IDENTITY_ARGUMENT} ${expectedLaunchIdentity} `;\n const markerIndex = normalized.indexOf(marker);\n if (markerIndex <= 0) return false;\n\n const runtime = normalized.slice(0, markerIndex);\n const runtimeName = executableName(process.execPath);\n const hasRuntime = [runtime, ...runtime.split(/\\s+/)].some((token) => (\n executableName(token) === runtimeName || executableName(token) === 'bun'\n ));\n const invocation = normalized.slice(markerIndex + marker.length);\n const runIndex = invocation.indexOf(' run ');\n if (runIndex <= 0) return false;\n return hasRuntime\n && executableName(invocation.slice(0, runIndex)) === expectedName\n && openCodeArgsMatch(commandTokens(invocation.slice(runIndex + 1)));\n }\n if (launchProtocol != null) return false;\n\n const tokens = commandTokens(command);\n\n const executableIndex = tokens.findIndex((token, index) => (\n index <= 3 && executableName(token) === expectedName\n ));\n if (executableIndex < 0) return false;\n return openCodeArgsMatch(tokens.slice(executableIndex + 1, executableIndex + 12));\n}\n\nexport function identifyGatewayProcess(pid: number): GatewayProcessIdentity {\n if (!isProcessAlive(pid)) return 'not-running';\n const command = process.platform === 'win32'\n ? inspectWindowsCommand(pid)\n : inspectUnixProcess(pid)?.command ?? null;\n if (!command) return 'unknown';\n\n const tokens = command\n .trim()\n .split(/\\s+/)\n .map((token) => token.replace(/^['\"]|['\"]$/g, '').replaceAll('\\\\', '/'));\n const runtimeName = executableName(process.execPath);\n const hasRuntime = tokens.slice(0, 4).some((token) => (\n executableName(token) === runtimeName || executableName(token) === 'bun'\n ));\n const hasGatewayEntry = tokens.some((token) => /(?:^|\\/)gateway\\/index\\.(?:js|ts)$/.test(token));\n const cliEntryIndex = tokens.findIndex((token) => /(?:^|\\/)cli\\/index\\.(?:js|ts)$/.test(token));\n const hasCliGatewayCommand = cliEntryIndex >= 0\n && tokens.slice(cliEntryIndex + 1).includes('gateway');\n const supertaskIndex = tokens.findIndex((token, index) => (\n index <= 3 && executableName(token) === 'supertask'\n ));\n const hasBinGatewayCommand = supertaskIndex >= 0 && tokens[supertaskIndex + 1] === 'gateway';\n return hasRuntime && (hasGatewayEntry || hasCliGatewayCommand || hasBinGatewayCommand)\n ? 'match'\n : 'mismatch';\n}\n\nexport function signalSpawnedProcessTree(pid: number, signal: NodeJS.Signals): boolean {\n if (!isSafePid(pid)) return false;\n\n if (process.platform === 'win32') {\n const args = ['/PID', String(pid), '/T'];\n if (signal === 'SIGKILL') args.push('/F');\n const status = runBoundedOsCommand('taskkill', args, false).status;\n return status === 0 || !isSpawnedProcessTreeAlive(pid);\n }\n\n try {\n process.kill(-pid, signal);\n return true;\n } catch {\n }\n\n try {\n process.kill(pid, signal);\n return true;\n } catch {\n return false;\n }\n}\n\nexport function signalRecordedProcessTree(\n pid: number,\n signal: NodeJS.Signals,\n expectedExecutable: string,\n launchProtocol: string | null = null,\n expectedLaunchIdentity: string | null = null,\n): boolean {\n return signalRecordedProcessTreeWithResult(\n pid,\n signal,\n expectedExecutable,\n launchProtocol,\n expectedLaunchIdentity,\n ) === 'signalled';\n}\n\nexport function signalRecordedProcessTreeWithResult(\n pid: number,\n signal: NodeJS.Signals,\n expectedExecutable: string,\n launchProtocol: string | null = null,\n expectedLaunchIdentity: string | null = null,\n): RecordedProcessSignalResult {\n if (!isSafePid(pid)) return 'identity-mismatch';\n if (!isProcessAlive(pid)) return absentLeaderResult(pid);\n\n if (process.platform === 'win32') {\n const command = inspectWindowsCommand(pid);\n if (!command) return isProcessAlive(pid) ? 'inspect-failed' : absentLeaderResult(pid);\n if (!commandMatches(\n command,\n expectedExecutable,\n launchProtocol,\n expectedLaunchIdentity,\n )) {\n return 'identity-mismatch';\n }\n const args = ['/PID', String(pid), '/T'];\n if (signal === 'SIGKILL') args.push('/F');\n const status = runBoundedOsCommand('taskkill', args, false).status;\n if (status === 0) return 'signalled';\n return isProcessAlive(pid) ? 'signal-failed' : absentLeaderResult(pid);\n }\n\n const info = inspectUnixProcess(pid);\n if (!info) return isProcessAlive(pid) ? 'inspect-failed' : absentLeaderResult(pid);\n if (!commandMatches(\n info.command,\n expectedExecutable,\n launchProtocol,\n expectedLaunchIdentity,\n )) {\n return 'identity-mismatch';\n }\n\n try {\n if (info.processGroupId === pid) process.kill(-pid, signal);\n else process.kill(pid, signal);\n return 'signalled';\n } catch {\n return isProcessAlive(pid) ? 'signal-failed' : absentLeaderResult(pid);\n }\n}\n\nexport async function waitForSpawnedProcessTreeExit(\n pid: number,\n timeoutMs = 5_000,\n): Promise<boolean> {\n const deadline = Date.now() + timeoutMs;\n while (inspectSpawnedProcessTreePresence(pid) !== 'not-running' && Date.now() < deadline) {\n await Bun.sleep(Math.min(50, deadline - Date.now()));\n }\n return inspectSpaw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AAG,MAAM,iBAAiB,KAAK,IAAI,IAAI,UAAU;AACtF,UAAM,IAAI,MAAM,KAAK,IAAI,IAAI,WAAW,KAAK,IAAI,CAAC,CAAC;AAAA,EACvD;AACA,SAAO,kCAAkC,GAAG,MAAM;AACtD;","names":["result"]}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
CONFIG_BOUNDS,
|
|
5
|
+
DEFAULT_CONFIG,
|
|
6
|
+
DEFAULT_CONFIG_PATH,
|
|
7
|
+
getConfigPath,
|
|
8
|
+
loadConfig,
|
|
9
|
+
validateConfig
|
|
10
|
+
} from "./chunk-MVQ2XONT.js";
|
|
11
|
+
import "./chunk-3PIYMBV3.js";
|
|
12
|
+
export {
|
|
13
|
+
CONFIG_BOUNDS,
|
|
14
|
+
DEFAULT_CONFIG,
|
|
15
|
+
DEFAULT_CONFIG_PATH,
|
|
16
|
+
getConfigPath,
|
|
17
|
+
loadConfig,
|
|
18
|
+
validateConfig
|
|
19
|
+
};
|
|
20
|
+
//# sourceMappingURL=config-ED56ZLHY.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
DatabaseMaintenanceConflictError,
|
|
5
|
+
DatabaseMaintenanceService
|
|
6
|
+
} from "./chunk-DIJEKFBV.js";
|
|
7
|
+
import "./chunk-ZBH7YWXF.js";
|
|
8
|
+
import "./chunk-YB7MYTE5.js";
|
|
9
|
+
import "./chunk-EQWICVCJ.js";
|
|
10
|
+
import "./chunk-YGELD2E5.js";
|
|
11
|
+
import "./chunk-3PIYMBV3.js";
|
|
12
|
+
export {
|
|
13
|
+
DatabaseMaintenanceConflictError,
|
|
14
|
+
DatabaseMaintenanceService
|
|
15
|
+
};
|
|
16
|
+
//# sourceMappingURL=database-maintenance.service-F3IZU52F.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|
|
@@ -0,0 +1,165 @@
|
|
|
1
|
+
#!/usr/bin/env bun
|
|
2
|
+
|
|
3
|
+
import {
|
|
4
|
+
cliText
|
|
5
|
+
} from "./chunk-IYYBJHZF.js";
|
|
6
|
+
import "./chunk-3PIYMBV3.js";
|
|
7
|
+
|
|
8
|
+
// src/cli/database-output.ts
|
|
9
|
+
function useJson(options) {
|
|
10
|
+
const isTTY = options.isTTY ?? process.stdout.isTTY === true;
|
|
11
|
+
return options.forceJson === true || !isTTY;
|
|
12
|
+
}
|
|
13
|
+
function formatBytes(bytes) {
|
|
14
|
+
const units = ["B", "KiB", "MiB", "GiB"];
|
|
15
|
+
let value = bytes;
|
|
16
|
+
let unit = 0;
|
|
17
|
+
while (value >= 1024 && unit < units.length - 1) {
|
|
18
|
+
value /= 1024;
|
|
19
|
+
unit += 1;
|
|
20
|
+
}
|
|
21
|
+
const rendered = Number.isInteger(value) ? String(value) : value.toFixed(1);
|
|
22
|
+
return `${rendered} ${units[unit]}`;
|
|
23
|
+
}
|
|
24
|
+
function formatCounts(counts, locale) {
|
|
25
|
+
return cliText(
|
|
26
|
+
locale,
|
|
27
|
+
`\u4EFB\u52A1 ${counts.tasks} \xB7 \u6267\u884C\u8BB0\u5F55 ${counts.taskRuns} \xB7 \u5B9A\u65F6\u4EFB\u52A1\u6A21\u677F ${counts.taskTemplates}`,
|
|
28
|
+
`tasks ${counts.tasks} \xB7 runs ${counts.taskRuns} \xB7 scheduled templates ${counts.taskTemplates}`
|
|
29
|
+
);
|
|
30
|
+
}
|
|
31
|
+
function formatGateway(gateway, locale) {
|
|
32
|
+
if (gateway.restarted) return cliText(locale, "\u5DF2\u81EA\u52A8\u505C\u6B62\u3001\u91CD\u542F\u5E76\u6062\u590D\u5C31\u7EEA", "stopped, restarted, and ready");
|
|
33
|
+
if (gateway.keptStopped) return cliText(locale, "\u5DF2\u81EA\u52A8\u505C\u6B62\uFF0C\u6309\u8981\u6C42\u4FDD\u6301\u505C\u6B62", "stopped and left stopped as requested");
|
|
34
|
+
if (!gateway.wasRunning) {
|
|
35
|
+
return cliText(
|
|
36
|
+
locale,
|
|
37
|
+
"\u65E0\u9700\u81EA\u52A8\u505C\u542F\uFF08\u672A\u53D1\u73B0\u5339\u914D\u5F53\u524D\u6570\u636E\u5E93\u7684 PM2 Gateway\uFF09",
|
|
38
|
+
"no matching PM2 Gateway was running"
|
|
39
|
+
);
|
|
40
|
+
}
|
|
41
|
+
return cliText(locale, "\u539F Gateway \u672A\u6062\u590D\u8FD0\u884C", "the previous Gateway was not restored");
|
|
42
|
+
}
|
|
43
|
+
function formatCheck(result, locale) {
|
|
44
|
+
if (locale === "en") {
|
|
45
|
+
const lines2 = [
|
|
46
|
+
result.ok ? "\u2713 Database check passed" : "\u2717 Database check failed",
|
|
47
|
+
"",
|
|
48
|
+
`Database: ${result.path}`,
|
|
49
|
+
`Size: ${formatBytes(result.sizeBytes)}`,
|
|
50
|
+
`Journal mode: ${result.journalMode}`,
|
|
51
|
+
`Counts: ${formatCounts(result.counts, locale)}`,
|
|
52
|
+
`Running: tasks ${result.runningTasks} \xB7 runs ${result.runningRuns}`
|
|
53
|
+
];
|
|
54
|
+
if (!result.ok) {
|
|
55
|
+
lines2.push(
|
|
56
|
+
`Integrity: ${result.integrityMessages.join("; ") || "no result"}`,
|
|
57
|
+
`Foreign-key violations: ${result.foreignKeyViolations}`,
|
|
58
|
+
`Missing tables: ${result.missingTables.join(", ") || "none"}`
|
|
59
|
+
);
|
|
60
|
+
}
|
|
61
|
+
return lines2.join("\n");
|
|
62
|
+
}
|
|
63
|
+
const lines = [
|
|
64
|
+
result.ok ? "\u2713 \u6570\u636E\u5E93\u68C0\u67E5\u901A\u8FC7" : "\u2717 \u6570\u636E\u5E93\u68C0\u67E5\u672A\u901A\u8FC7",
|
|
65
|
+
"",
|
|
66
|
+
`\u6570\u636E\u5E93\uFF1A${result.path}`,
|
|
67
|
+
`\u5927\u5C0F\uFF1A${formatBytes(result.sizeBytes)}`,
|
|
68
|
+
`\u65E5\u5FD7\u6A21\u5F0F\uFF1A${result.journalMode}`,
|
|
69
|
+
`\u6570\u636E\u7EDF\u8BA1\uFF1A${formatCounts(result.counts, locale)}`,
|
|
70
|
+
`\u8FD0\u884C\u4E2D\uFF1A\u4EFB\u52A1 ${result.runningTasks} \xB7 \u6267\u884C\u8BB0\u5F55 ${result.runningRuns}`
|
|
71
|
+
];
|
|
72
|
+
if (!result.ok) {
|
|
73
|
+
lines.push(
|
|
74
|
+
`\u5B8C\u6574\u6027\uFF1A${result.integrityMessages.join("\uFF1B") || "\u65E0\u7ED3\u679C"}`,
|
|
75
|
+
`\u5916\u952E\u8FDD\u89C4\uFF1A${result.foreignKeyViolations}`,
|
|
76
|
+
`\u7F3A\u5931\u8868\uFF1A${result.missingTables.join("\u3001") || "\u65E0"}`
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
return lines.join("\n");
|
|
80
|
+
}
|
|
81
|
+
function formatHuman(operation, result, locale) {
|
|
82
|
+
switch (operation) {
|
|
83
|
+
case "check":
|
|
84
|
+
return formatCheck(result, locale);
|
|
85
|
+
case "backup": {
|
|
86
|
+
const backup = result;
|
|
87
|
+
if (locale === "en") {
|
|
88
|
+
return [
|
|
89
|
+
"\u2713 Database backup completed",
|
|
90
|
+
"",
|
|
91
|
+
`Backup: ${backup.path}`,
|
|
92
|
+
`Size: ${formatBytes(backup.sizeBytes)}`,
|
|
93
|
+
`Counts: ${formatCounts(backup.check.counts, locale)}`,
|
|
94
|
+
`Integrity: ${backup.check.ok ? "passed" : "failed"}`
|
|
95
|
+
].join("\n");
|
|
96
|
+
}
|
|
97
|
+
return [
|
|
98
|
+
"\u2713 \u6570\u636E\u5E93\u5907\u4EFD\u5B8C\u6210",
|
|
99
|
+
"",
|
|
100
|
+
`\u5907\u4EFD\u6587\u4EF6\uFF1A${backup.path}`,
|
|
101
|
+
`\u5927\u5C0F\uFF1A${formatBytes(backup.sizeBytes)}`,
|
|
102
|
+
`\u6570\u636E\u7EDF\u8BA1\uFF1A${formatCounts(backup.check.counts, locale)}`,
|
|
103
|
+
`\u6570\u636E\u5E93\u5B8C\u6574\u6027\uFF1A${backup.check.ok ? "\u901A\u8FC7" : "\u672A\u901A\u8FC7"}`
|
|
104
|
+
].join("\n");
|
|
105
|
+
}
|
|
106
|
+
case "clear": {
|
|
107
|
+
const cleared = result;
|
|
108
|
+
if (locale === "en") {
|
|
109
|
+
return [
|
|
110
|
+
"\u2713 Database safely cleared",
|
|
111
|
+
"",
|
|
112
|
+
`Deleted: ${formatCounts(cleared.deleted, locale)}`,
|
|
113
|
+
`Safety backup: ${cleared.backupPath}`,
|
|
114
|
+
`Gateway: ${formatGateway(cleared.gateway, locale)}`,
|
|
115
|
+
`Integrity: ${cleared.check.ok ? "passed" : "failed"}`
|
|
116
|
+
].join("\n");
|
|
117
|
+
}
|
|
118
|
+
return [
|
|
119
|
+
"\u2713 \u6570\u636E\u5E93\u5DF2\u5B89\u5168\u6E05\u7A7A",
|
|
120
|
+
"",
|
|
121
|
+
`\u5DF2\u5220\u9664\uFF1A${formatCounts(cleared.deleted, locale)}`,
|
|
122
|
+
`\u5B89\u5168\u5907\u4EFD\uFF1A${cleared.backupPath}`,
|
|
123
|
+
`Gateway\uFF1A${formatGateway(cleared.gateway, locale)}`,
|
|
124
|
+
`\u6570\u636E\u5E93\u5B8C\u6574\u6027\uFF1A${cleared.check.ok ? "\u901A\u8FC7" : "\u672A\u901A\u8FC7"}`
|
|
125
|
+
].join("\n");
|
|
126
|
+
}
|
|
127
|
+
case "restore": {
|
|
128
|
+
const restored = result;
|
|
129
|
+
if (locale === "en") {
|
|
130
|
+
return [
|
|
131
|
+
"\u2713 Database restore completed",
|
|
132
|
+
"",
|
|
133
|
+
`Source: ${restored.sourcePath}`,
|
|
134
|
+
`Pre-restore safety backup: ${restored.safetyBackupPath}`,
|
|
135
|
+
`Recovered runtime state: tasks ${restored.recoveredRunningTasks} \xB7 runs ${restored.closedRunningRuns}`,
|
|
136
|
+
`Counts: ${formatCounts(restored.check.counts, locale)}`,
|
|
137
|
+
`Gateway: ${formatGateway(restored.gateway, locale)}`,
|
|
138
|
+
`Integrity: ${restored.check.ok ? "passed" : "failed"}`
|
|
139
|
+
].join("\n");
|
|
140
|
+
}
|
|
141
|
+
return [
|
|
142
|
+
"\u2713 \u6570\u636E\u5E93\u6062\u590D\u5B8C\u6210",
|
|
143
|
+
"",
|
|
144
|
+
`\u6062\u590D\u6765\u6E90\uFF1A${restored.sourcePath}`,
|
|
145
|
+
`\u6062\u590D\u524D\u5B89\u5168\u5907\u4EFD\uFF1A${restored.safetyBackupPath}`,
|
|
146
|
+
`\u8FD0\u884C\u6001\u6536\u655B\uFF1A\u4EFB\u52A1 ${restored.recoveredRunningTasks} \xB7 \u6267\u884C\u8BB0\u5F55 ${restored.closedRunningRuns}`,
|
|
147
|
+
`\u6570\u636E\u7EDF\u8BA1\uFF1A${formatCounts(restored.check.counts, locale)}`,
|
|
148
|
+
`Gateway\uFF1A${formatGateway(restored.gateway, locale)}`,
|
|
149
|
+
`\u6570\u636E\u5E93\u5B8C\u6574\u6027\uFF1A${restored.check.ok ? "\u901A\u8FC7" : "\u672A\u901A\u8FC7"}`
|
|
150
|
+
].join("\n");
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
function renderDatabaseResult(operation, result, options = {}) {
|
|
155
|
+
return useJson(options) ? JSON.stringify(result, null, 2) : formatHuman(operation, result, options.locale ?? "zh-CN");
|
|
156
|
+
}
|
|
157
|
+
function renderDatabaseError(error, options = {}) {
|
|
158
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
159
|
+
return useJson(options) ? JSON.stringify({ error: message }) : `\u2717 ${message}`;
|
|
160
|
+
}
|
|
161
|
+
export {
|
|
162
|
+
renderDatabaseError,
|
|
163
|
+
renderDatabaseResult
|
|
164
|
+
};
|
|
165
|
+
//# sourceMappingURL=database-output-GH7F6X6D.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/cli/database-output.ts"],"sourcesContent":["import type {\n DatabaseBackupResult,\n DatabaseCheckResult,\n DatabaseClearResult,\n DatabaseCounts,\n DatabaseRestoreResult,\n} from '@core/services/database-maintenance.service';\nimport { cliText, type CliLocale } from './i18n';\n\nexport interface GatewayMaintenanceReport {\n wasRunning: boolean;\n restarted: boolean;\n keptStopped: boolean;\n}\n\ninterface DatabaseResultMap {\n check: DatabaseCheckResult;\n backup: DatabaseBackupResult;\n clear: DatabaseClearResult & { gateway: GatewayMaintenanceReport };\n restore: DatabaseRestoreResult & { gateway: GatewayMaintenanceReport };\n}\n\ninterface RenderOptions {\n forceJson?: boolean;\n isTTY?: boolean;\n locale?: CliLocale;\n}\n\nfunction useJson(options: RenderOptions): boolean {\n const isTTY = options.isTTY ?? process.stdout.isTTY === true;\n return options.forceJson === true || !isTTY;\n}\n\nfunction formatBytes(bytes: number): string {\n const units = ['B', 'KiB', 'MiB', 'GiB'];\n let value = bytes;\n let unit = 0;\n while (value >= 1024 && unit < units.length - 1) {\n value /= 1024;\n unit += 1;\n }\n const rendered = Number.isInteger(value) ? String(value) : value.toFixed(1);\n return `${rendered} ${units[unit]}`;\n}\n\nfunction formatCounts(counts: DatabaseCounts, locale: CliLocale): string {\n return cliText(\n locale,\n `任务 ${counts.tasks} · 执行记录 ${counts.taskRuns} · 定时任务模板 ${counts.taskTemplates}`,\n `tasks ${counts.tasks} · runs ${counts.taskRuns} · scheduled templates ${counts.taskTemplates}`,\n );\n}\n\nfunction formatGateway(gateway: GatewayMaintenanceReport, locale: CliLocale): string {\n if (gateway.restarted) return cliText(locale, '已自动停止、重启并恢复就绪', 'stopped, restarted, and ready');\n if (gateway.keptStopped) return cliText(locale, '已自动停止,按要求保持停止', 'stopped and left stopped as requested');\n if (!gateway.wasRunning) {\n return cliText(\n locale,\n '无需自动停启(未发现匹配当前数据库的 PM2 Gateway)',\n 'no matching PM2 Gateway was running',\n );\n }\n return cliText(locale, '原 Gateway 未恢复运行', 'the previous Gateway was not restored');\n}\n\nfunction formatCheck(result: DatabaseCheckResult, locale: CliLocale): string {\n if (locale === 'en') {\n const lines = [\n result.ok ? '✓ Database check passed' : '✗ Database check failed',\n '',\n `Database: ${result.path}`,\n `Size: ${formatBytes(result.sizeBytes)}`,\n `Journal mode: ${result.journalMode}`,\n `Counts: ${formatCounts(result.counts, locale)}`,\n `Running: tasks ${result.runningTasks} · runs ${result.runningRuns}`,\n ];\n if (!result.ok) {\n lines.push(\n `Integrity: ${result.integrityMessages.join('; ') || 'no result'}`,\n `Foreign-key violations: ${result.foreignKeyViolations}`,\n `Missing tables: ${result.missingTables.join(', ') || 'none'}`,\n );\n }\n return lines.join('\\n');\n }\n const lines = [\n result.ok ? '✓ 数据库检查通过' : '✗ 数据库检查未通过',\n '',\n `数据库:${result.path}`,\n `大小:${formatBytes(result.sizeBytes)}`,\n `日志模式:${result.journalMode}`,\n `数据统计:${formatCounts(result.counts, locale)}`,\n `运行中:任务 ${result.runningTasks} · 执行记录 ${result.runningRuns}`,\n ];\n if (!result.ok) {\n lines.push(\n `完整性:${result.integrityMessages.join(';') || '无结果'}`,\n `外键违规:${result.foreignKeyViolations}`,\n `缺失表:${result.missingTables.join('、') || '无'}`,\n );\n }\n return lines.join('\\n');\n}\n\nfunction formatHuman<K extends keyof DatabaseResultMap>(\n operation: K,\n result: DatabaseResultMap[K],\n locale: CliLocale,\n): string {\n switch (operation) {\n case 'check':\n return formatCheck(result as DatabaseCheckResult, locale);\n case 'backup': {\n const backup = result as DatabaseBackupResult;\n if (locale === 'en') {\n return [\n '✓ Database backup completed',\n '',\n `Backup: ${backup.path}`,\n `Size: ${formatBytes(backup.sizeBytes)}`,\n `Counts: ${formatCounts(backup.check.counts, locale)}`,\n `Integrity: ${backup.check.ok ? 'passed' : 'failed'}`,\n ].join('\\n');\n }\n return [\n '✓ 数据库备份完成',\n '',\n `备份文件:${backup.path}`,\n `大小:${formatBytes(backup.sizeBytes)}`,\n `数据统计:${formatCounts(backup.check.counts, locale)}`,\n `数据库完整性:${backup.check.ok ? '通过' : '未通过'}`,\n ].join('\\n');\n }\n case 'clear': {\n const cleared = result as DatabaseResultMap['clear'];\n if (locale === 'en') {\n return [\n '✓ Database safely cleared',\n '',\n `Deleted: ${formatCounts(cleared.deleted, locale)}`,\n `Safety backup: ${cleared.backupPath}`,\n `Gateway: ${formatGateway(cleared.gateway, locale)}`,\n `Integrity: ${cleared.check.ok ? 'passed' : 'failed'}`,\n ].join('\\n');\n }\n return [\n '✓ 数据库已安全清空',\n '',\n `已删除:${formatCounts(cleared.deleted, locale)}`,\n `安全备份:${cleared.backupPath}`,\n `Gateway:${formatGateway(cleared.gateway, locale)}`,\n `数据库完整性:${cleared.check.ok ? '通过' : '未通过'}`,\n ].join('\\n');\n }\n case 'restore': {\n const restored = result as DatabaseResultMap['restore'];\n if (locale === 'en') {\n return [\n '✓ Database restore completed',\n '',\n `Source: ${restored.sourcePath}`,\n `Pre-restore safety backup: ${restored.safetyBackupPath}`,\n `Recovered runtime state: tasks ${restored.recoveredRunningTasks} · runs ${restored.closedRunningRuns}`,\n `Counts: ${formatCounts(restored.check.counts, locale)}`,\n `Gateway: ${formatGateway(restored.gateway, locale)}`,\n `Integrity: ${restored.check.ok ? 'passed' : 'failed'}`,\n ].join('\\n');\n }\n return [\n '✓ 数据库恢复完成',\n '',\n `恢复来源:${restored.sourcePath}`,\n `恢复前安全备份:${restored.safetyBackupPath}`,\n `运行态收敛:任务 ${restored.recoveredRunningTasks} · 执行记录 ${restored.closedRunningRuns}`,\n `数据统计:${formatCounts(restored.check.counts, locale)}`,\n `Gateway:${formatGateway(restored.gateway, locale)}`,\n `数据库完整性:${restored.check.ok ? '通过' : '未通过'}`,\n ].join('\\n');\n }\n }\n}\n\nexport function renderDatabaseResult<K extends keyof DatabaseResultMap>(\n operation: K,\n result: DatabaseResultMap[K],\n options: RenderOptions = {},\n): string {\n return useJson(options)\n ? JSON.stringify(result, null, 2)\n : formatHuman(operation, result, options.locale ?? 'zh-CN');\n}\n\nexport function renderDatabaseError(error: unknown, options: RenderOptions = {}): string {\n const message = error instanceof Error ? error.message : String(error);\n return useJson(options)\n ? JSON.stringify({ error: message })\n : `✗ ${message}`;\n}\n"],"mappings":";;;;;;;;AA4BA,SAAS,QAAQ,SAAiC;AAC9C,QAAM,QAAQ,QAAQ,SAAS,QAAQ,OAAO,UAAU;AACxD,SAAO,QAAQ,cAAc,QAAQ,CAAC;AAC1C;AAEA,SAAS,YAAY,OAAuB;AACxC,QAAM,QAAQ,CAAC,KAAK,OAAO,OAAO,KAAK;AACvC,MAAI,QAAQ;AACZ,MAAI,OAAO;AACX,SAAO,SAAS,QAAQ,OAAO,MAAM,SAAS,GAAG;AAC7C,aAAS;AACT,YAAQ;AAAA,EACZ;AACA,QAAM,WAAW,OAAO,UAAU,KAAK,IAAI,OAAO,KAAK,IAAI,MAAM,QAAQ,CAAC;AAC1E,SAAO,GAAG,QAAQ,IAAI,MAAM,IAAI,CAAC;AACrC;AAEA,SAAS,aAAa,QAAwB,QAA2B;AACrE,SAAO;AAAA,IACH;AAAA,IACA,gBAAM,OAAO,KAAK,kCAAW,OAAO,QAAQ,8CAAa,OAAO,aAAa;AAAA,IAC7E,SAAS,OAAO,KAAK,cAAW,OAAO,QAAQ,6BAA0B,OAAO,aAAa;AAAA,EACjG;AACJ;AAEA,SAAS,cAAc,SAAmC,QAA2B;AACjF,MAAI,QAAQ,UAAW,QAAO,QAAQ,QAAQ,kFAAiB,+BAA+B;AAC9F,MAAI,QAAQ,YAAa,QAAO,QAAQ,QAAQ,kFAAiB,uCAAuC;AACxG,MAAI,CAAC,QAAQ,YAAY;AACrB,WAAO;AAAA,MACH;AAAA,MACA;AAAA,MACA;AAAA,IACJ;AAAA,EACJ;AACA,SAAO,QAAQ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EXPECTED_SCHEMA_USER_VERSION,
|
|
6
|
+
closeDb,
|
|
7
|
+
db,
|
|
8
|
+
getDb,
|
|
9
|
+
getSqlite,
|
|
10
|
+
migrateSqliteDatabase,
|
|
11
|
+
schema_exports,
|
|
12
|
+
sqlite
|
|
13
|
+
} from "./chunk-YGELD2E5.js";
|
|
14
|
+
import "./chunk-3PIYMBV3.js";
|
|
15
|
+
export {
|
|
16
|
+
DB_FILE_PATH,
|
|
17
|
+
EXPECTED_SCHEMA_USER_VERSION,
|
|
18
|
+
closeDb,
|
|
19
|
+
db,
|
|
20
|
+
getDb,
|
|
21
|
+
getSqlite,
|
|
22
|
+
migrateSqliteDatabase,
|
|
23
|
+
schema_exports as schema,
|
|
24
|
+
sqlite
|
|
25
|
+
};
|
|
26
|
+
//# sourceMappingURL=db-H7GIFWS2.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":[],"sourcesContent":[],"mappings":"","names":[]}
|