opencode-supertask 0.1.41 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (97) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +66 -39
  3. package/README.zh-CN.md +66 -39
  4. package/dist/cli/chunk-3PIYMBV3.js +45 -0
  5. package/dist/cli/chunk-3PIYMBV3.js.map +1 -0
  6. package/dist/cli/chunk-4FK5KE6G.js +111 -0
  7. package/dist/cli/chunk-4FK5KE6G.js.map +1 -0
  8. package/dist/cli/chunk-5VKFECHP.js +412 -0
  9. package/dist/cli/chunk-5VKFECHP.js.map +1 -0
  10. package/dist/cli/chunk-AZM76ISG.js +143 -0
  11. package/dist/cli/chunk-AZM76ISG.js.map +1 -0
  12. package/dist/cli/chunk-CMEP6IB4.js +9379 -0
  13. package/dist/cli/chunk-CMEP6IB4.js.map +1 -0
  14. package/dist/cli/chunk-DF56RPNL.js +65 -0
  15. package/dist/cli/chunk-DF56RPNL.js.map +1 -0
  16. package/dist/cli/chunk-DIJEKFBV.js +486 -0
  17. package/dist/cli/chunk-DIJEKFBV.js.map +1 -0
  18. package/dist/cli/chunk-DYXFSX5J.js +28 -0
  19. package/dist/cli/chunk-DYXFSX5J.js.map +1 -0
  20. package/dist/cli/chunk-EQWICVCJ.js +1701 -0
  21. package/dist/cli/chunk-EQWICVCJ.js.map +1 -0
  22. package/dist/cli/chunk-GHXFMJTS.js +42 -0
  23. package/dist/cli/chunk-GHXFMJTS.js.map +1 -0
  24. package/dist/cli/chunk-IYYBJHZF.js +28 -0
  25. package/dist/cli/chunk-IYYBJHZF.js.map +1 -0
  26. package/dist/cli/chunk-J34FWHQU.js +376 -0
  27. package/dist/cli/chunk-J34FWHQU.js.map +1 -0
  28. package/dist/cli/chunk-LX5CBJLP.js +121 -0
  29. package/dist/cli/chunk-LX5CBJLP.js.map +1 -0
  30. package/dist/cli/chunk-MVQ2XONT.js +139 -0
  31. package/dist/cli/chunk-MVQ2XONT.js.map +1 -0
  32. package/dist/cli/chunk-NCT3ETTK.js +1332 -0
  33. package/dist/cli/chunk-NCT3ETTK.js.map +1 -0
  34. package/dist/cli/chunk-YB7MYTE5.js +34 -0
  35. package/dist/cli/chunk-YB7MYTE5.js.map +1 -0
  36. package/dist/cli/chunk-YGELD2E5.js +5464 -0
  37. package/dist/cli/chunk-YGELD2E5.js.map +1 -0
  38. package/dist/cli/chunk-ZBH7YWXF.js +314 -0
  39. package/dist/cli/chunk-ZBH7YWXF.js.map +1 -0
  40. package/dist/cli/config-ED56ZLHY.js +20 -0
  41. package/dist/cli/config-ED56ZLHY.js.map +1 -0
  42. package/dist/cli/database-maintenance.service-F3IZU52F.js +16 -0
  43. package/dist/cli/database-maintenance.service-F3IZU52F.js.map +1 -0
  44. package/dist/cli/database-output-GH7F6X6D.js +165 -0
  45. package/dist/cli/database-output-GH7F6X6D.js.map +1 -0
  46. package/dist/cli/db-H7GIFWS2.js +26 -0
  47. package/dist/cli/db-H7GIFWS2.js.map +1 -0
  48. package/dist/cli/doctor-smoke-QXHF7UNN.js +150 -0
  49. package/dist/cli/doctor-smoke-QXHF7UNN.js.map +1 -0
  50. package/dist/cli/duration-Q3UMLO6F.js +10 -0
  51. package/dist/cli/duration-Q3UMLO6F.js.map +1 -0
  52. package/dist/cli/gateway-HNMX5ZTO.js +1738 -0
  53. package/dist/cli/gateway-HNMX5ZTO.js.map +1 -0
  54. package/dist/cli/gateway-wake-U4HTV56Q.js +14 -0
  55. package/dist/cli/gateway-wake-U4HTV56Q.js.map +1 -0
  56. package/dist/cli/index.js +626 -26583
  57. package/dist/cli/index.js.map +1 -1
  58. package/dist/cli/job-templates-RPQJ4XXW.js +21 -0
  59. package/dist/cli/job-templates-RPQJ4XXW.js.map +1 -0
  60. package/dist/cli/logs-QD2N62KK.js +316 -0
  61. package/dist/cli/logs-QD2N62KK.js.map +1 -0
  62. package/dist/cli/output-2INTEUFQ.js +19 -0
  63. package/dist/cli/output-2INTEUFQ.js.map +1 -0
  64. package/dist/cli/pm2-WY644BUO.js +49 -0
  65. package/dist/cli/pm2-WY644BUO.js.map +1 -0
  66. package/dist/cli/task-run.service-QMDINJKG.js +15 -0
  67. package/dist/cli/task-run.service-QMDINJKG.js.map +1 -0
  68. package/dist/cli/task-template.service-SZBKGLCB.js +12 -0
  69. package/dist/cli/task-template.service-SZBKGLCB.js.map +1 -0
  70. package/dist/cli/task.service-ZVDJ6VSQ.js +19 -0
  71. package/dist/cli/task.service-ZVDJ6VSQ.js.map +1 -0
  72. package/dist/cli/update-FYD546I2.js +2058 -0
  73. package/dist/cli/update-FYD546I2.js.map +1 -0
  74. package/dist/cli/web-2S7DW7XA.js +9403 -0
  75. package/dist/cli/web-2S7DW7XA.js.map +1 -0
  76. package/dist/daemon/gateway-diagnostic-runner.js +280 -238
  77. package/dist/daemon/gateway-diagnostic-runner.js.map +1 -1
  78. package/dist/gateway/index.d.ts +82 -1
  79. package/dist/gateway/index.js +9154 -2577
  80. package/dist/gateway/index.js.map +1 -1
  81. package/dist/plugin/supertask.d.ts +157 -1
  82. package/dist/plugin/supertask.js +5056 -1550
  83. package/dist/plugin/supertask.js.map +1 -1
  84. package/dist/pm2-cli-CEDhULjk.d.ts +40 -0
  85. package/dist/web/index.d.ts +36 -34
  86. package/dist/web/index.js +9951 -4006
  87. package/dist/web/index.js.map +1 -1
  88. package/dist/worker/index.d.ts +5 -0
  89. package/dist/worker/index.js +1989 -331
  90. package/dist/worker/index.js.map +1 -1
  91. package/dist/worker/launcher.d.ts +46 -1
  92. package/dist/worker/launcher.js +218 -68
  93. package/dist/worker/launcher.js.map +1 -1
  94. package/drizzle/0009_little_weapon_omega.sql +7 -0
  95. package/drizzle/meta/0009_snapshot.json +681 -0
  96. package/drizzle/meta/_journal.json +7 -0
  97. package/package.json +4 -4
@@ -0,0 +1,1332 @@
1
+ #!/usr/bin/env bun
2
+
3
+ import {
4
+ getPackageVersion
5
+ } from "./chunk-DYXFSX5J.js";
6
+ import {
7
+ loadConfig
8
+ } from "./chunk-MVQ2XONT.js";
9
+
10
+ // src/daemon/pm2-cli.ts
11
+ import { execSync, spawnSync } from "child_process";
12
+ import {
13
+ accessSync,
14
+ constants,
15
+ existsSync,
16
+ mkdirSync,
17
+ readFileSync,
18
+ statSync,
19
+ writeFileSync
20
+ } from "fs";
21
+ import { homedir } from "os";
22
+ import { delimiter, dirname, isAbsolute, join, resolve } from "path";
23
+ import { fileURLToPath } from "url";
24
+ import { Database } from "bun:sqlite";
25
+ var __dirname = dirname(fileURLToPath(import.meta.url));
26
+ var PROCESS_NAME = "supertask-gateway";
27
+ var MAC_LAUNCH_AGENT_LABEL = "com.supertask.pm2-resurrect";
28
+ var PM2_DEFAULT_KILL_TIMEOUT_MS = 1600;
29
+ var GATEWAY_LOCK_STALE_MS = 3e4;
30
+ function resolveGatewayEntry() {
31
+ const override = process.env.SUPERTASK_GATEWAY_ENTRY;
32
+ if (override) {
33
+ if (!existsSync(override)) throw new Error(`[supertask] Gateway entry not found: ${override}`);
34
+ return override;
35
+ }
36
+ const candidates = [
37
+ join(__dirname, "../gateway/index.js"),
38
+ join(__dirname, "../gateway/index.ts")
39
+ ];
40
+ const entry = candidates.find((candidate) => existsSync(candidate));
41
+ if (!entry) throw new Error(`[supertask] Gateway entry not found. Checked: ${candidates.join(", ")}`);
42
+ return entry;
43
+ }
44
+ function runtimeHome(env) {
45
+ return resolve(env.HOME || homedir());
46
+ }
47
+ function runtimePath(value, cwd) {
48
+ return resolve(cwd, value);
49
+ }
50
+ function databasePath(env = process.env, cwd = process.cwd()) {
51
+ return env.SUPERTASK_DB_PATH ? runtimePath(env.SUPERTASK_DB_PATH, cwd) : join(runtimeHome(env), ".local/share/opencode/tasks.db");
52
+ }
53
+ function versionFile(env = process.env, cwd = process.cwd()) {
54
+ return env.SUPERTASK_VERSION_FILE ? runtimePath(env.SUPERTASK_VERSION_FILE, cwd) : join(runtimeHome(env), ".local/share/opencode/supertask-gateway-version");
55
+ }
56
+ function getRunningVersion(env = process.env, cwd = process.cwd()) {
57
+ try {
58
+ const path = versionFile(env, cwd);
59
+ if (!existsSync(path)) return null;
60
+ return readFileSync(path, "utf-8").trim() || null;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+ function writeRunningVersion(version, env = process.env, cwd = process.cwd()) {
66
+ const path = versionFile(env, cwd);
67
+ mkdirSync(dirname(path), { recursive: true });
68
+ writeFileSync(path, version, "utf-8");
69
+ }
70
+ function packageVersionFromGatewayEntry(gatewayEntry) {
71
+ if (gatewayEntry === null) return null;
72
+ let directory = dirname(gatewayEntry);
73
+ for (let depth = 0; depth < 6; depth += 1) {
74
+ const packagePath = join(directory, "package.json");
75
+ if (existsSync(packagePath)) {
76
+ try {
77
+ const pkg = JSON.parse(readFileSync(packagePath, "utf8"));
78
+ if (pkg.name === "opencode-supertask" && typeof pkg.version === "string") {
79
+ return pkg.version;
80
+ }
81
+ } catch {
82
+ }
83
+ }
84
+ const parent = dirname(directory);
85
+ if (parent === directory) break;
86
+ directory = parent;
87
+ }
88
+ return null;
89
+ }
90
+ function resolveRuntimeExecutable(command, env, cwd) {
91
+ if (isAbsolute(command) || command.includes("/")) return runtimePath(command, cwd);
92
+ for (const entry of (env.PATH ?? "").split(delimiter)) {
93
+ if (!entry) continue;
94
+ const candidate = resolve(cwd, entry, command);
95
+ try {
96
+ accessSync(candidate, constants.X_OK);
97
+ return candidate;
98
+ } catch {
99
+ }
100
+ }
101
+ return command;
102
+ }
103
+ function findBunPath() {
104
+ const override = process.env.SUPERTASK_BUN_BIN;
105
+ if (override) return override;
106
+ try {
107
+ const command = process.platform === "win32" ? "where bun" : "which bun";
108
+ return execSync(command, { stdio: "pipe" }).toString().trim().split("\n")[0];
109
+ } catch {
110
+ return process.execPath;
111
+ }
112
+ }
113
+ function pm2Bin(env = process.env) {
114
+ return env.SUPERTASK_PM2_BIN ?? (process.platform === "win32" ? "pm2.cmd" : "pm2");
115
+ }
116
+ function pm2CommandTimeoutMs(env = process.env) {
117
+ const configured = Number(env.SUPERTASK_PM2_COMMAND_TIMEOUT_MS ?? 15e3);
118
+ return Number.isFinite(configured) && configured > 0 ? configured : 15e3;
119
+ }
120
+ function resolvePm2Bin(env = process.env) {
121
+ const configured = pm2Bin(env);
122
+ if (isAbsolute(configured)) return configured;
123
+ const result = spawnSync("which", [configured], { encoding: "utf8", env });
124
+ const resolved = result.status === 0 ? result.stdout.trim().split("\n")[0] : "";
125
+ if (!resolved) throw new Error(`[supertask] \u65E0\u6CD5\u89E3\u6790 pm2 \u53EF\u6267\u884C\u6587\u4EF6: ${configured}`);
126
+ return resolved;
127
+ }
128
+ function launchAgentPath() {
129
+ return process.env.SUPERTASK_LAUNCH_AGENT_PATH ?? join(runtimeHome(process.env), "Library/LaunchAgents", `${MAC_LAUNCH_AGENT_LABEL}.plist`);
130
+ }
131
+ function launchctlBin() {
132
+ return process.env.SUPERTASK_LAUNCHCTL_BIN ?? "launchctl";
133
+ }
134
+ function systemctlBin(env = process.env) {
135
+ return env.SUPERTASK_SYSTEMCTL_BIN ?? "systemctl";
136
+ }
137
+ function xmlEscape(value) {
138
+ return value.replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;").replaceAll("'", "&apos;");
139
+ }
140
+ function xmlUnescape(value) {
141
+ return value.replaceAll("&apos;", "'").replaceAll("&quot;", '"').replaceAll("&gt;", ">").replaceAll("&lt;", "<").replaceAll("&amp;", "&");
142
+ }
143
+ function plistValue(contents, key) {
144
+ const escapedKey = key.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
145
+ const match = contents.match(new RegExp(`<key>\\s*${escapedKey}\\s*</key>\\s*<string>([^<]*)</string>`));
146
+ return match?.[1] ? xmlUnescape(match[1]) : null;
147
+ }
148
+ function isPm2Installed(env = process.env) {
149
+ const result = spawnSync(pm2Bin(env), ["--version"], {
150
+ stdio: "ignore",
151
+ env,
152
+ shell: process.platform === "win32",
153
+ timeout: pm2CommandTimeoutMs(env),
154
+ killSignal: "SIGKILL"
155
+ });
156
+ return result.status === 0;
157
+ }
158
+ function installPm2() {
159
+ console.log("[supertask] Installing pm2...");
160
+ try {
161
+ execSync("npm install -g pm2", { stdio: "inherit" });
162
+ return true;
163
+ } catch {
164
+ try {
165
+ execSync("bun install -g pm2", { stdio: "inherit" });
166
+ return true;
167
+ } catch {
168
+ return false;
169
+ }
170
+ }
171
+ }
172
+ function resolveCommand(command, env = process.env) {
173
+ const lookup = process.platform === "win32" ? "where" : "which";
174
+ const result = spawnSync(lookup, [command], { encoding: "utf8", env });
175
+ return result.status === 0 ? result.stdout.trim().split("\n")[0] || null : null;
176
+ }
177
+ function npmPreferredEnvironment(baseEnv = process.env) {
178
+ if (process.platform === "win32") return null;
179
+ const npm = resolveCommand("npm", baseEnv) ?? resolveCommand("npm", process.env);
180
+ const node = resolveCommand("node", baseEnv) ?? resolveCommand("node", process.env);
181
+ if (!npm || !node) return null;
182
+ let command;
183
+ try {
184
+ command = resolvePm2Bin(baseEnv);
185
+ } catch {
186
+ return null;
187
+ }
188
+ const existingPathEntries = (baseEnv.PATH ?? "").split(delimiter).filter(Boolean);
189
+ const path = [.../* @__PURE__ */ new Set([
190
+ dirname(command),
191
+ dirname(npm),
192
+ dirname(node),
193
+ ...existingPathEntries,
194
+ "/usr/local/bin",
195
+ "/usr/bin",
196
+ "/bin"
197
+ ])].join(delimiter);
198
+ return { command, env: { ...baseEnv, PATH: path } };
199
+ }
200
+ function pm2Exec(args, options = {}) {
201
+ const baseEnv = options.env ?? process.env;
202
+ const npmEnvironment = options.preferNpm ? npmPreferredEnvironment(baseEnv) : null;
203
+ const effectiveEnv = npmEnvironment?.env ?? baseEnv;
204
+ const result = spawnSync(npmEnvironment?.command ?? pm2Bin(effectiveEnv), args, {
205
+ stdio: ["pipe", "pipe", "pipe"],
206
+ encoding: "utf-8",
207
+ env: effectiveEnv,
208
+ shell: process.platform === "win32",
209
+ timeout: options.timeoutMs ?? pm2CommandTimeoutMs(effectiveEnv),
210
+ killSignal: "SIGKILL"
211
+ });
212
+ const output = `${result.stdout ?? ""}${result.stderr ?? ""}`.trim();
213
+ if (result.error) return { ok: false, output: result.error.message };
214
+ return { ok: result.status === 0, output };
215
+ }
216
+ function requirePm2(args, action, options = {}) {
217
+ const result = pm2Exec(args, options);
218
+ if (!result.ok) throw new Error(`[supertask] ${action} failed: ${result.output || "unknown pm2 error"}`);
219
+ return result.output;
220
+ }
221
+ function ensurePm2LogRotation(env = process.env) {
222
+ if (!isPm2Installed(env)) return false;
223
+ const installed = pm2JsonList(env).some((item) => item.name === "pm2-logrotate");
224
+ if (!installed) {
225
+ const result = pm2Exec(["install", "pm2-logrotate"], { preferNpm: true, env });
226
+ if (!result.ok) return false;
227
+ }
228
+ for (const [key, value] of [
229
+ ["max_size", "10M"],
230
+ ["retain", "7"],
231
+ ["compress", "true"],
232
+ ["workerInterval", "3600"]
233
+ ]) {
234
+ const result = pm2Exec(["set", `pm2-logrotate:${key}`, value], { env });
235
+ if (!result.ok) return false;
236
+ }
237
+ return true;
238
+ }
239
+ function pm2JsonList(env = process.env) {
240
+ const output = requirePm2(["jlist"], "pm2 jlist", { env });
241
+ try {
242
+ const parsed = JSON.parse(output);
243
+ if (!Array.isArray(parsed)) throw new Error("result is not an array");
244
+ return parsed;
245
+ } catch (error) {
246
+ const message = error instanceof Error ? error.message : String(error);
247
+ throw new Error(`[supertask] Invalid pm2 jlist output: ${message}`);
248
+ }
249
+ }
250
+ function savePm2State(env = process.env) {
251
+ requirePm2(["save"], "pm2 save", { env });
252
+ }
253
+ function gatewayEntryFromProcess(processInfo) {
254
+ const args = processInfo?.pm2_env?.args ?? processInfo?.args;
255
+ const candidates = Array.isArray(args) ? [...args].reverse() : typeof args === "string" ? [args] : [];
256
+ const savedCwd = processInfo?.pm2_env?.pm_cwd ?? processInfo?.pm_cwd;
257
+ for (const candidate of candidates) {
258
+ const path = typeof savedCwd === "string" ? runtimePath(candidate, savedCwd) : candidate;
259
+ if (existsSync(path)) return resolve(path);
260
+ }
261
+ return null;
262
+ }
263
+ function gatewayEnvironmentFromProcess(processInfo) {
264
+ const saved = processInfo?.pm2_env?.env ?? processInfo?.env;
265
+ if (!saved) return { ...process.env };
266
+ const env = {};
267
+ for (const [key, value] of Object.entries(saved)) {
268
+ if (typeof value === "string") env[key] = value;
269
+ }
270
+ return env;
271
+ }
272
+ function gatewayRuntimeFromProcess(processInfo) {
273
+ const gatewayEntry = gatewayEntryFromProcess(processInfo);
274
+ if (!gatewayEntry) return null;
275
+ const savedBunPath = processInfo?.pm2_env?.pm_exec_path ?? processInfo?.pm_exec_path;
276
+ const savedCwd = processInfo?.pm2_env?.pm_cwd ?? processInfo?.pm_cwd;
277
+ const savedEnv = gatewayEnvironmentFromProcess(processInfo);
278
+ if (typeof savedBunPath !== "string" || typeof savedCwd !== "string") return null;
279
+ try {
280
+ accessSync(savedBunPath, constants.X_OK);
281
+ if (!statSync(savedCwd).isDirectory()) return null;
282
+ if (spawnSync(savedBunPath, ["--version"], {
283
+ stdio: "ignore",
284
+ env: savedEnv,
285
+ timeout: pm2CommandTimeoutMs(savedEnv),
286
+ killSignal: "SIGKILL"
287
+ }).status !== 0) return null;
288
+ } catch {
289
+ return null;
290
+ }
291
+ const killTimeout = processInfo?.pm2_env?.kill_timeout ?? processInfo?.kill_timeout;
292
+ return {
293
+ gatewayEntry,
294
+ bunPath: savedBunPath,
295
+ cwd: resolve(savedCwd),
296
+ env: savedEnv,
297
+ killTimeoutMs: Number.isInteger(killTimeout) && killTimeout >= 5e3 ? killTimeout : void 0,
298
+ pm2KillTimeoutMs: Number.isInteger(killTimeout) ? killTimeout : PM2_DEFAULT_KILL_TIMEOUT_MS
299
+ };
300
+ }
301
+ function hasRestorableSavedGatewayRuntime(processInfo) {
302
+ return gatewayRuntimeFromProcess(processInfo) !== null;
303
+ }
304
+ function currentGatewayRuntime(gatewayEntry = resolveGatewayEntry()) {
305
+ return {
306
+ gatewayEntry: resolve(gatewayEntry),
307
+ bunPath: resolve(findBunPath()),
308
+ cwd: process.cwd(),
309
+ env: { ...process.env }
310
+ };
311
+ }
312
+ function refreshGatewayExecutionEnvironment(runtime, gatewayEntry) {
313
+ const env = { ...process.env };
314
+ for (const key of /* @__PURE__ */ new Set([
315
+ ...Object.keys(runtime.env).filter((name) => name.startsWith("SUPERTASK_")),
316
+ ...Object.keys(env).filter((name) => name.startsWith("SUPERTASK_")),
317
+ "HOME",
318
+ "PATH",
319
+ "PM2_HOME"
320
+ ])) {
321
+ const value = runtime.env[key];
322
+ if (value === void 0) delete env[key];
323
+ else env[key] = value;
324
+ }
325
+ return {
326
+ ...runtime,
327
+ gatewayEntry: resolve(gatewayEntry),
328
+ env
329
+ };
330
+ }
331
+ function queryGatewayLock(path, query, fallback) {
332
+ if (!existsSync(path)) return fallback;
333
+ let database = null;
334
+ try {
335
+ database = new Database(path, { readonly: true });
336
+ return query(database);
337
+ } catch {
338
+ return fallback;
339
+ } finally {
340
+ database?.close();
341
+ }
342
+ }
343
+ function isGatewayReady(expectedPid, path = databasePath()) {
344
+ return queryGatewayLock(path, (database) => {
345
+ const row = database.query(
346
+ "SELECT pid, heartbeat_at, ready_at FROM gateway_lock WHERE id = 1"
347
+ ).get();
348
+ if (!row || row.ready_at == null) return false;
349
+ if (expectedPid !== void 0 && row.pid !== expectedPid) return false;
350
+ const ageMs = Date.now() - row.heartbeat_at;
351
+ return ageMs >= -5e3 && ageMs < GATEWAY_LOCK_STALE_MS;
352
+ }, false);
353
+ }
354
+ function gatewayVersionFromLock(expectedPid, path) {
355
+ return queryGatewayLock(path, (database) => {
356
+ const row = database.query(
357
+ "SELECT pid, version FROM gateway_lock WHERE id = 1"
358
+ ).get();
359
+ if (!row || row.pid !== expectedPid) return void 0;
360
+ return row.version;
361
+ }, void 0);
362
+ }
363
+ function readyTimeoutMs(env = process.env) {
364
+ const value = Number(env.SUPERTASK_GATEWAY_READY_TIMEOUT_MS ?? 3e4);
365
+ return Number.isFinite(value) && value > 0 ? value : 3e4;
366
+ }
367
+ function waitForGatewayReady(pid, path = databasePath(), env = process.env) {
368
+ const deadline = Date.now() + readyTimeoutMs(env);
369
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
370
+ while (Date.now() < deadline) {
371
+ if (isGatewayReady(pid, path)) return true;
372
+ Atomics.wait(sleeper, 0, 0, 100);
373
+ }
374
+ return isGatewayReady(pid, path);
375
+ }
376
+
377
+ // src/daemon/pm2-scope.ts
378
+ import { spawnSync as spawnSync2 } from "child_process";
379
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "fs";
380
+ import { join as join2, resolve as resolve2 } from "path";
381
+ import { Database as Database3 } from "bun:sqlite";
382
+
383
+ // src/daemon/management-lock.ts
384
+ import { Database as Database2 } from "bun:sqlite";
385
+ import { mkdirSync as mkdirSync2 } from "fs";
386
+ import { dirname as dirname2 } from "path";
387
+ var ManagementLockBusyError = class extends Error {
388
+ constructor() {
389
+ super("Gateway management lock is busy");
390
+ this.name = "ManagementLockBusyError";
391
+ }
392
+ };
393
+ function isBusyError(error) {
394
+ if (!(error instanceof Error)) return false;
395
+ const code = error.code;
396
+ return code === "SQLITE_BUSY" || /database is locked/i.test(error.message);
397
+ }
398
+ function withExclusiveManagementLock(path, timeoutMs, action) {
399
+ mkdirSync2(dirname2(path), { recursive: true });
400
+ const database = new Database2(path, { create: true });
401
+ const normalizedTimeout = Number.isFinite(timeoutMs) && timeoutMs >= 0 ? Math.floor(timeoutMs) : 0;
402
+ database.exec(`PRAGMA busy_timeout = ${normalizedTimeout}`);
403
+ try {
404
+ try {
405
+ database.exec("BEGIN IMMEDIATE");
406
+ } catch (error) {
407
+ if (isBusyError(error)) throw new ManagementLockBusyError();
408
+ throw error;
409
+ }
410
+ try {
411
+ const result = action();
412
+ database.exec("COMMIT");
413
+ return result;
414
+ } catch (error) {
415
+ try {
416
+ database.exec("ROLLBACK");
417
+ } catch {
418
+ }
419
+ throw error;
420
+ }
421
+ } finally {
422
+ database.close();
423
+ }
424
+ }
425
+
426
+ // src/daemon/pm2-scope.ts
427
+ function canonicalManagementLockPath(env = process.env, cwd = process.cwd()) {
428
+ const home = runtimeHome(env);
429
+ const pm2Home = env.PM2_HOME ? runtimePath(env.PM2_HOME, cwd) : join2(home, ".pm2");
430
+ return join2(pm2Home, "supertask-gateway.manage.sqlite");
431
+ }
432
+ function managementLockPath(env = process.env, cwd = process.cwd()) {
433
+ const override = env.SUPERTASK_PM2_MANAGEMENT_LOCK;
434
+ if (override) return runtimePath(override, cwd);
435
+ return join2(runtimeScope({ env, cwd }).pm2Home, "supertask-gateway.manage.sqlite");
436
+ }
437
+ function runtimeScope(runtime) {
438
+ const { cwd, env } = runtime;
439
+ const home = runtimeHome(env);
440
+ return {
441
+ cwd: resolve2(cwd),
442
+ databasePath: env.SUPERTASK_DB_PATH ? runtimePath(env.SUPERTASK_DB_PATH, cwd) : join2(home, ".local/share/opencode/tasks.db"),
443
+ configPath: env.SUPERTASK_CONFIG_PATH ? runtimePath(env.SUPERTASK_CONFIG_PATH, cwd) : join2(home, ".config/opencode/supertask.json"),
444
+ opencodePath: resolveRuntimeExecutable(env.SUPERTASK_OPENCODE_BIN ?? "opencode", env, cwd),
445
+ home,
446
+ pm2Home: env.PM2_HOME ? runtimePath(env.PM2_HOME, cwd) : join2(home, ".pm2"),
447
+ managementLockPath: canonicalManagementLockPath(env, cwd)
448
+ };
449
+ }
450
+ function scopesMatch(left, right) {
451
+ return left.databasePath === right.databasePath && left.configPath === right.configPath && left.opencodePath === right.opencodePath && left.home === right.home && left.pm2Home === right.pm2Home && left.managementLockPath === right.managementLockPath;
452
+ }
453
+ function currentScope() {
454
+ return runtimeScope({ cwd: process.cwd(), env: process.env });
455
+ }
456
+ function diagnoseOpenCodeRuntime(runtime = {
457
+ cwd: process.cwd(),
458
+ env: process.env
459
+ }) {
460
+ const executable = runtimeScope(runtime).opencodePath;
461
+ const result = spawnSync2(executable, ["--version"], {
462
+ cwd: runtime.cwd,
463
+ env: runtime.env,
464
+ encoding: "utf8",
465
+ timeout: 1e4,
466
+ killSignal: "SIGKILL"
467
+ });
468
+ const ok = result.status === 0 && result.error === void 0;
469
+ return {
470
+ ok,
471
+ executable,
472
+ version: ok ? result.stdout.trim() || result.stderr.trim() || null : null,
473
+ error: ok ? null : result.error?.message || result.stderr.trim() || result.stdout.trim() || `exit code ${result.status}`
474
+ };
475
+ }
476
+ function assertOpenCodeRuntime(runtime) {
477
+ const diagnostic = diagnoseOpenCodeRuntime(runtime);
478
+ if (!diagnostic.ok) {
479
+ throw new Error(
480
+ `[supertask] \u76EE\u6807 Gateway \u73AF\u5883\u65E0\u6CD5\u6267\u884C OpenCode (${diagnostic.executable}): ${diagnostic.error}`
481
+ );
482
+ }
483
+ }
484
+ function pm2MaxMemoryRestart(env = process.env) {
485
+ const value = env.SUPERTASK_PM2_MAX_MEMORY ?? "512M";
486
+ if (!/^\d+(?:K|M|G)$/i.test(value)) {
487
+ throw new Error("[supertask] SUPERTASK_PM2_MAX_MEMORY \u5FC5\u987B\u4F7F\u7528 512M / 1G \u8FD9\u7C7B\u683C\u5F0F");
488
+ }
489
+ return value;
490
+ }
491
+ function gatewayKillTimeoutMs(runtime) {
492
+ const shutdownGracePeriodMs = loadConfig(runtimeScope(runtime).configPath).worker.shutdownGracePeriodMs;
493
+ const minimumKillTimeoutMs = shutdownGracePeriodMs + 15e3;
494
+ const configuredValue = runtime.env.SUPERTASK_PM2_KILL_TIMEOUT_MS;
495
+ if (configuredValue !== void 0) {
496
+ const configuredKillTimeout = Number(configuredValue);
497
+ if (!Number.isInteger(configuredKillTimeout) || configuredKillTimeout < minimumKillTimeoutMs) {
498
+ throw new Error(
499
+ `[supertask] SUPERTASK_PM2_KILL_TIMEOUT_MS \u5FC5\u987B\u662F\u81F3\u5C11 ${minimumKillTimeoutMs} \u7684\u6574\u6570\uFF08worker shutdown grace ${shutdownGracePeriodMs}ms + 15000ms \u6536\u5C3E\u4F59\u91CF\uFF09`
500
+ );
501
+ }
502
+ return configuredKillTimeout;
503
+ }
504
+ return Math.max(runtime.killTimeoutMs ?? 0, minimumKillTimeoutMs);
505
+ }
506
+ function gatewayTerminationCommandTimeoutMs(runtime) {
507
+ const effectiveKillTimeoutMs = Math.max(
508
+ runtime.killTimeoutMs ?? 0,
509
+ gatewayKillTimeoutMs(runtime)
510
+ );
511
+ const minimumCommandTimeoutMs = effectiveKillTimeoutMs + 5e3;
512
+ const configuredValue = runtime.env.SUPERTASK_PM2_COMMAND_TIMEOUT_MS;
513
+ if (configuredValue !== void 0) {
514
+ const configuredTimeoutMs = Number(configuredValue);
515
+ if (!Number.isInteger(configuredTimeoutMs) || configuredTimeoutMs < minimumCommandTimeoutMs) {
516
+ throw new Error(
517
+ `[supertask] SUPERTASK_PM2_COMMAND_TIMEOUT_MS \u5FC5\u987B\u662F\u81F3\u5C11 ${minimumCommandTimeoutMs} \u7684\u6574\u6570\uFF08Gateway kill timeout ${effectiveKillTimeoutMs}ms + 5000ms PM2 \u6536\u5C3E\u4F59\u91CF\uFF09`
518
+ );
519
+ }
520
+ return configuredTimeoutMs;
521
+ }
522
+ return Math.max(pm2CommandTimeoutMs(runtime.env), minimumCommandTimeoutMs);
523
+ }
524
+ function runningWorkCount(path) {
525
+ if (!existsSync2(path)) return 0;
526
+ let database = null;
527
+ try {
528
+ database = new Database3(path, { readonly: true });
529
+ const tables = database.query(
530
+ "SELECT COUNT(*) AS count FROM sqlite_master WHERE type = 'table' AND name IN ('tasks', 'task_runs')"
531
+ ).get();
532
+ if (Number(tables?.count ?? 0) < 2) return 0;
533
+ const row = database.query(
534
+ "SELECT (SELECT COUNT(*) FROM tasks WHERE status = 'running') + (SELECT COUNT(*) FROM task_runs WHERE status = 'running') AS count"
535
+ ).get();
536
+ return Number(row?.count ?? 0);
537
+ } finally {
538
+ database?.close();
539
+ }
540
+ }
541
+ function assertPm2KillTimeoutCoversShutdown(runtime) {
542
+ if (runtime.pm2KillTimeoutMs === void 0) return;
543
+ const scope = runtimeScope(runtime);
544
+ const requiredMs = loadConfig(scope.configPath).worker.shutdownGracePeriodMs + 15e3;
545
+ if (runtime.pm2KillTimeoutMs >= requiredMs) return;
546
+ const running = runningWorkCount(scope.databasePath);
547
+ if (running === 0) return;
548
+ throw new Error(
549
+ `[supertask] PM2 Gateway \u7684 kill_timeout \u4E3A ${runtime.pm2KillTimeoutMs}ms\uFF0C\u4F4E\u4E8E shutdown grace + 15000ms\uFF08${requiredMs}ms\uFF09\uFF0C\u4E14\u4ECD\u6709 ${running} \u4E2A\u8FD0\u884C\u4E2D\u4EFB\u52A1/\u6267\u884C\u8BB0\u5F55\uFF1B\u73B0\u5728\u505C\u6B62\u4F1A\u5728\u4F18\u96C5\u505C\u673A\u4E2D\u9014\u88AB\u5F3A\u5236\u7EC8\u6B62\u3002\u8BF7\u7B49\u5F85\u4EFB\u52A1\u5B8C\u6210\u540E\u91CD\u8BD5`
550
+ );
551
+ }
552
+ function requirePm2Termination(command, action, runtime) {
553
+ assertPm2KillTimeoutCoversShutdown(runtime);
554
+ return requirePm2([command, PROCESS_NAME], action, {
555
+ env: runtime.env,
556
+ timeoutMs: gatewayTerminationCommandTimeoutMs(runtime)
557
+ });
558
+ }
559
+ function assertRuntimeCanControlPm2(runtime, existing) {
560
+ if (!existing) return;
561
+ if (!runtime) {
562
+ throw new Error(
563
+ "[supertask] \u65E0\u6CD5\u5B8C\u6574\u9A8C\u8BC1\u5DF2\u6709 Gateway \u7684\u5165\u53E3\u3001Bun \u548C cwd\uFF0C\u5DF2\u62D2\u7EDD\u5220\u9664\u73B0\u6709\u8FDB\u7A0B"
564
+ );
565
+ }
566
+ const probe = pm2Exec(["--version"], { env: runtime.env });
567
+ if (!probe.ok) {
568
+ throw new Error(
569
+ `[supertask] \u4FDD\u5B58\u7684 Gateway \u8FD0\u884C\u73AF\u5883\u65E0\u6CD5\u6267\u884C pm2\uFF0C\u5DF2\u62D2\u7EDD\u5220\u9664\u73B0\u6709\u8FDB\u7A0B\uFF1B\u8BF7\u5148\u4FEE\u590D PATH \u6216 SUPERTASK_PM2_BIN: ${probe.output || "pm2 unavailable"}`
570
+ );
571
+ }
572
+ const observed = pm2JsonList(runtime.env).find((item) => item.name === PROCESS_NAME);
573
+ const observedRuntime = gatewayRuntimeFromProcess(observed);
574
+ if (!observed || observed.pid !== existing.pid || !observedRuntime || observedRuntime.gatewayEntry !== runtime.gatewayEntry || observedRuntime.bunPath !== runtime.bunPath || observedRuntime.cwd !== runtime.cwd) {
575
+ throw new Error("[supertask] \u4FDD\u5B58\u7684 PM2 \u73AF\u5883\u65E0\u6CD5\u91CD\u73B0\u540C\u4E00 Gateway \u8BB0\u5F55\uFF0C\u5DF2\u62D2\u7EDD\u5220\u9664\u73B0\u6709\u8FDB\u7A0B");
576
+ }
577
+ }
578
+ function addLegacyManagementLock(paths, env, cwd) {
579
+ const value = env?.SUPERTASK_PM2_MANAGEMENT_LOCK;
580
+ if (typeof value === "string" && value.length > 0) paths.add(runtimePath(value, cwd));
581
+ }
582
+ function collectLegacyLockFromProcess(paths, gateway) {
583
+ const cwd = gateway?.pm2_env?.pm_cwd ?? gateway?.pm_cwd;
584
+ if (typeof cwd === "string") {
585
+ addLegacyManagementLock(paths, gateway?.pm2_env?.env ?? gateway?.env, cwd);
586
+ }
587
+ }
588
+ function savedManagementLockPaths() {
589
+ const canonical = canonicalManagementLockPath();
590
+ const legacy = /* @__PURE__ */ new Set();
591
+ addLegacyManagementLock(legacy, process.env, process.cwd());
592
+ const pm2Home = currentScope().pm2Home;
593
+ try {
594
+ const dump = JSON.parse(readFileSync2(join2(pm2Home, "dump.pm2"), "utf8"));
595
+ if (Array.isArray(dump)) {
596
+ collectLegacyLockFromProcess(
597
+ legacy,
598
+ dump.find((item) => item.name === PROCESS_NAME)
599
+ );
600
+ }
601
+ } catch {
602
+ }
603
+ if (process.platform === "darwin") {
604
+ try {
605
+ const configured = plistValue(
606
+ readFileSync2(launchAgentPath(), "utf8"),
607
+ "SUPERTASK_PM2_MANAGEMENT_LOCK"
608
+ );
609
+ if (configured) legacy.add(resolve2(configured));
610
+ } catch {
611
+ }
612
+ }
613
+ if (isPm2Installed()) {
614
+ collectLegacyLockFromProcess(
615
+ legacy,
616
+ pm2JsonList().find((item) => item.name === PROCESS_NAME)
617
+ );
618
+ }
619
+ return [
620
+ canonical,
621
+ ...[...legacy].filter((path) => path !== canonical).sort()
622
+ ];
623
+ }
624
+ function withManagementLocks(paths, timeoutMs, action, index = 0) {
625
+ const path = paths[index];
626
+ if (!path) return action();
627
+ return withExclusiveManagementLock(
628
+ path,
629
+ timeoutMs,
630
+ () => withManagementLocks(paths, timeoutMs, action, index + 1)
631
+ );
632
+ }
633
+ function assertMacLaunchAgentPm2HomeMatchesCurrent() {
634
+ if (process.platform !== "darwin") return;
635
+ try {
636
+ const configuredPm2Home = plistValue(
637
+ readFileSync2(launchAgentPath(), "utf8"),
638
+ "PM2_HOME"
639
+ );
640
+ if (!configuredPm2Home) return;
641
+ const installedPm2Home = resolve2(configuredPm2Home);
642
+ const activePm2Home = currentScope().pm2Home;
643
+ if (installedPm2Home !== activePm2Home) {
644
+ throw new Error(
645
+ `[supertask] \u5DF2\u5B89\u88C5\u7684 macOS LaunchAgent \u4F7F\u7528 PM2_HOME=${installedPm2Home}\uFF0C\u5F53\u524D CLI \u4F7F\u7528 ${activePm2Home}\uFF1B\u4E3A\u907F\u514D\u4E24\u4E2A PM2 daemon \u540C\u65F6\u7BA1\u7406 Gateway\uFF0C\u5DF2\u62D2\u7EDD\u4FEE\u6539\u3002\u8BF7\u4F7F\u7528 PM2_HOME=${installedPm2Home} \u91CD\u65B0\u6267\u884C\u547D\u4EE4`
646
+ );
647
+ }
648
+ } catch (error) {
649
+ if (error instanceof Error && error.message.startsWith("[supertask] \u5DF2\u5B89\u88C5\u7684 macOS LaunchAgent")) {
650
+ throw error;
651
+ }
652
+ if (error.code !== "ENOENT") throw error;
653
+ }
654
+ }
655
+ function withManagementLock(action) {
656
+ const paths = savedManagementLockPaths();
657
+ const configuredTimeout = Number(process.env.SUPERTASK_PM2_MANAGEMENT_LOCK_TIMEOUT_MS ?? 15e3);
658
+ const timeoutMs = Number.isFinite(configuredTimeout) && configuredTimeout > 0 ? configuredTimeout : 15e3;
659
+ try {
660
+ return withManagementLocks(paths, timeoutMs, () => {
661
+ assertMacLaunchAgentPm2HomeMatchesCurrent();
662
+ return action();
663
+ });
664
+ } catch (error) {
665
+ if (error instanceof ManagementLockBusyError) {
666
+ throw new Error("[supertask] \u53E6\u4E00\u4E2A Gateway \u7BA1\u7406\u64CD\u4F5C\u4ECD\u5728\u8FDB\u884C\uFF0C\u5DF2\u62D2\u7EDD\u5E76\u53D1\u4FEE\u6539 PM2 \u72B6\u6001");
667
+ }
668
+ throw error;
669
+ }
670
+ }
671
+
672
+ // src/daemon/pm2-startup.ts
673
+ import { spawnSync as spawnSync3 } from "child_process";
674
+ import {
675
+ accessSync as accessSync2,
676
+ chmodSync,
677
+ constants as constants2,
678
+ existsSync as existsSync3,
679
+ mkdirSync as mkdirSync3,
680
+ readFileSync as readFileSync3,
681
+ rmSync,
682
+ writeFileSync as writeFileSync2
683
+ } from "fs";
684
+ import { userInfo } from "os";
685
+ import { dirname as dirname3, join as join3, resolve as resolve3 } from "path";
686
+ import { fileURLToPath as fileURLToPath2 } from "url";
687
+ var __dirname2 = dirname3(fileURLToPath2(import.meta.url));
688
+ function resolvePm2SupervisorEntry(baseDir = __dirname2) {
689
+ const override = process.env.SUPERTASK_PM2_SUPERVISOR_ENTRY;
690
+ if (override) {
691
+ if (!existsSync3(override)) throw new Error(`[supertask] PM2 supervisor entry not found: ${override}`);
692
+ return resolve3(override);
693
+ }
694
+ const candidates = [
695
+ join3(baseDir, "pm2-supervisor.js"),
696
+ join3(baseDir, "pm2-supervisor.ts"),
697
+ join3(baseDir, "../daemon/pm2-supervisor.js"),
698
+ join3(baseDir, "../daemon/pm2-supervisor.ts")
699
+ ];
700
+ const entry = candidates.find((candidate) => existsSync3(candidate));
701
+ if (!entry) throw new Error(`[supertask] PM2 supervisor entry not found. Checked: ${candidates.join(", ")}`);
702
+ return resolve3(entry);
703
+ }
704
+ function readRestorableDumpGatewayRuntime(pm2Home) {
705
+ const dump = JSON.parse(readFileSync3(join3(pm2Home, "dump.pm2"), "utf8"));
706
+ if (!Array.isArray(dump)) return null;
707
+ const gateway = dump.find((item) => item.name === PROCESS_NAME);
708
+ const runtime = gatewayRuntimeFromProcess(gateway);
709
+ return runtime && hasRestorableSavedGatewayRuntime(gateway) ? runtime : null;
710
+ }
711
+ function isMacLaunchAgentConfigured(expectedPm2Home, expectedRuntime) {
712
+ if (typeof process.getuid !== "function") return false;
713
+ const plistPath = launchAgentPath();
714
+ if (!existsSync3(plistPath)) return false;
715
+ try {
716
+ const contents = readFileSync3(plistPath, "utf8");
717
+ const argumentsBlock = contents.match(
718
+ /<key>\s*ProgramArguments\s*<\/key>\s*<array>([\s\S]*?)<\/array>/
719
+ )?.[1];
720
+ const programArguments = argumentsBlock ? [...argumentsBlock.matchAll(/<string>([^<]*)<\/string>/g)].map((match) => xmlUnescape(match[1])) : [];
721
+ const bunPath = programArguments[0];
722
+ const supervisorEntry = programArguments[1];
723
+ const pm2Path = programArguments[2];
724
+ const pm2Home = plistValue(contents, "PM2_HOME");
725
+ const managementLock = plistValue(contents, "SUPERTASK_PM2_MANAGEMENT_LOCK");
726
+ if (!bunPath || !supervisorEntry || !pm2Path || !pm2Home || !managementLock) return false;
727
+ if (expectedPm2Home && resolve3(pm2Home) !== resolve3(expectedPm2Home)) return false;
728
+ const expectedManagementLock = expectedRuntime ? managementLockPath(expectedRuntime.env, expectedRuntime.cwd) : process.env.SUPERTASK_PM2_MANAGEMENT_LOCK ? managementLockPath() : join3(expectedPm2Home ?? currentScope().pm2Home, "supertask-gateway.manage.sqlite");
729
+ if (managementLock !== expectedManagementLock) return false;
730
+ accessSync2(bunPath, constants2.X_OK);
731
+ accessSync2(supervisorEntry, constants2.R_OK);
732
+ accessSync2(pm2Path, constants2.X_OK);
733
+ if (spawnSync3(bunPath, ["--version"], {
734
+ stdio: "ignore",
735
+ timeout: pm2CommandTimeoutMs(),
736
+ killSignal: "SIGKILL"
737
+ }).status !== 0) return false;
738
+ if (spawnSync3(pm2Path, ["--version"], {
739
+ stdio: "ignore",
740
+ env: { ...process.env, PM2_HOME: pm2Home },
741
+ timeout: pm2CommandTimeoutMs(),
742
+ killSignal: "SIGKILL"
743
+ }).status !== 0) return false;
744
+ const loaded = spawnSync3(
745
+ launchctlBin(),
746
+ ["print", `gui/${process.getuid()}/${MAC_LAUNCH_AGENT_LABEL}`],
747
+ {
748
+ encoding: "utf8",
749
+ stdio: ["ignore", "pipe", "ignore"],
750
+ timeout: pm2CommandTimeoutMs(),
751
+ killSignal: "SIGKILL"
752
+ }
753
+ );
754
+ if (loaded.status !== 0) return false;
755
+ if (!loaded.stdout.includes("state = running")) return false;
756
+ if (!loaded.stdout.includes(`path = ${plistPath}`)) return false;
757
+ if (!loaded.stdout.includes(`program = ${bunPath}`)) return false;
758
+ const dumpRuntime = readRestorableDumpGatewayRuntime(pm2Home);
759
+ if (!dumpRuntime) return false;
760
+ return expectedRuntime === void 0 || dumpRuntime.gatewayEntry === expectedRuntime.gatewayEntry && dumpRuntime.bunPath === expectedRuntime.bunPath && dumpRuntime.cwd === expectedRuntime.cwd && scopesMatch(runtimeScope(dumpRuntime), runtimeScope(expectedRuntime));
761
+ } catch {
762
+ return false;
763
+ }
764
+ }
765
+ function bootstrapMacLaunchAgent(domain, path) {
766
+ const retryDeadline = Date.now() + 2e3;
767
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
768
+ let result = spawnSync3(launchctlBin(), ["bootstrap", domain, path], {
769
+ encoding: "utf8",
770
+ timeout: pm2CommandTimeoutMs(),
771
+ killSignal: "SIGKILL"
772
+ });
773
+ while (result.status !== 0 && Date.now() < retryDeadline) {
774
+ const output = `${result.stdout ?? ""}${result.stderr ?? ""}`;
775
+ if (result.status !== 5 && !output.includes("Bootstrap failed: 5:")) break;
776
+ Atomics.wait(sleeper, 0, 0, 100);
777
+ result = spawnSync3(launchctlBin(), ["bootstrap", domain, path], {
778
+ encoding: "utf8",
779
+ timeout: pm2CommandTimeoutMs(),
780
+ killSignal: "SIGKILL"
781
+ });
782
+ }
783
+ return result;
784
+ }
785
+ function installMacLaunchAgent(expectedRuntime = currentGatewayRuntime()) {
786
+ if (typeof process.getuid !== "function") {
787
+ throw new Error("[supertask] \u5F53\u524D\u8FD0\u884C\u65F6\u65E0\u6CD5\u83B7\u53D6 macOS \u7528\u6237 ID");
788
+ }
789
+ const path = launchAgentPath();
790
+ const home = runtimeHome(expectedRuntime.env);
791
+ const pm2Home = runtimeScope(expectedRuntime).pm2Home;
792
+ const managementLock = managementLockPath(expectedRuntime.env, expectedRuntime.cwd);
793
+ const environmentPath = expectedRuntime.env.PATH ?? "/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin";
794
+ const bunPath = findBunPath();
795
+ const supervisorEntry = resolvePm2SupervisorEntry();
796
+ const pm2Path = resolvePm2Bin();
797
+ const plist = `<?xml version="1.0" encoding="UTF-8"?>
798
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
799
+ <plist version="1.0">
800
+ <dict>
801
+ <key>Label</key>
802
+ <string>${MAC_LAUNCH_AGENT_LABEL}</string>
803
+ <key>ProgramArguments</key>
804
+ <array>
805
+ <string>${xmlEscape(bunPath)}</string>
806
+ <string>${xmlEscape(supervisorEntry)}</string>
807
+ <string>${xmlEscape(pm2Path)}</string>
808
+ </array>
809
+ <key>RunAtLoad</key>
810
+ <true/>
811
+ <key>KeepAlive</key>
812
+ <true/>
813
+ <key>ThrottleInterval</key>
814
+ <integer>10</integer>
815
+ <key>EnvironmentVariables</key>
816
+ <dict>
817
+ <key>HOME</key>
818
+ <string>${xmlEscape(home)}</string>
819
+ <key>PATH</key>
820
+ <string>${xmlEscape(environmentPath)}</string>
821
+ <key>PM2_HOME</key>
822
+ <string>${xmlEscape(pm2Home)}</string>
823
+ <key>SUPERTASK_PM2_MANAGEMENT_LOCK</key>
824
+ <string>${xmlEscape(managementLock)}</string>
825
+ </dict>
826
+ <key>StandardErrorPath</key>
827
+ <string>${xmlEscape(join3(pm2Home, "supertask-launchd-error.log"))}</string>
828
+ <key>StandardOutPath</key>
829
+ <string>${xmlEscape(join3(pm2Home, "supertask-launchd-output.log"))}</string>
830
+ </dict>
831
+ </plist>
832
+ `;
833
+ const domain = `gui/${process.getuid()}`;
834
+ const previousPlist = existsSync3(path) ? readFileSync3(path) : null;
835
+ const wasLoaded = previousPlist != null && spawnSync3(
836
+ launchctlBin(),
837
+ ["print", `${domain}/${MAC_LAUNCH_AGENT_LABEL}`],
838
+ {
839
+ stdio: "ignore",
840
+ timeout: pm2CommandTimeoutMs(),
841
+ killSignal: "SIGKILL"
842
+ }
843
+ ).status === 0;
844
+ mkdirSync3(dirname3(path), { recursive: true });
845
+ writeFileSync2(path, plist, { mode: 384 });
846
+ chmodSync(path, 384);
847
+ spawnSync3(launchctlBin(), ["bootout", `${domain}/${MAC_LAUNCH_AGENT_LABEL}`], {
848
+ stdio: "ignore",
849
+ timeout: pm2CommandTimeoutMs(),
850
+ killSignal: "SIGKILL"
851
+ });
852
+ const loaded = bootstrapMacLaunchAgent(domain, path);
853
+ const configuredVerifyTimeout = Number(process.env.SUPERTASK_LAUNCH_AGENT_VERIFY_TIMEOUT_MS ?? 2e3);
854
+ const verifyTimeoutMs = Number.isFinite(configuredVerifyTimeout) && configuredVerifyTimeout > 0 ? configuredVerifyTimeout : 2e3;
855
+ const verifyDeadline = Date.now() + verifyTimeoutMs;
856
+ const sleeper = new Int32Array(new SharedArrayBuffer(4));
857
+ let verified = loaded.status === 0 && isMacLaunchAgentConfigured(pm2Home, expectedRuntime);
858
+ while (loaded.status === 0 && !verified && Date.now() < verifyDeadline) {
859
+ Atomics.wait(sleeper, 0, 0, 100);
860
+ verified = isMacLaunchAgentConfigured(pm2Home, expectedRuntime);
861
+ }
862
+ if (loaded.status !== 0 || !verified) {
863
+ const output = loaded.status === 0 ? "supervisor \u672A\u4FDD\u6301 running \u6216 PM2 dump \u4E0D\u53EF\u6062\u590D" : `${loaded.stdout ?? ""}${loaded.stderr ?? ""}`.trim();
864
+ if (loaded.status === 0) {
865
+ spawnSync3(launchctlBin(), ["bootout", `${domain}/${MAC_LAUNCH_AGENT_LABEL}`], {
866
+ stdio: "ignore",
867
+ timeout: pm2CommandTimeoutMs(),
868
+ killSignal: "SIGKILL"
869
+ });
870
+ }
871
+ if (previousPlist == null) rmSync(path, { force: true });
872
+ else {
873
+ writeFileSync2(path, previousPlist, { mode: 384 });
874
+ chmodSync(path, 384);
875
+ }
876
+ let rollbackFailure = "";
877
+ if (wasLoaded && previousPlist != null) {
878
+ const restored = bootstrapMacLaunchAgent(domain, path);
879
+ if (restored.status !== 0) {
880
+ rollbackFailure = `\uFF1B\u65E7 LaunchAgent \u6062\u590D\u5931\u8D25: ${`${restored.stdout ?? ""}${restored.stderr ?? ""}`.trim() || `\u9000\u51FA\u7801 ${restored.status}`}`;
881
+ }
882
+ }
883
+ throw new Error(`[supertask] macOS LaunchAgent \u52A0\u8F7D\u5931\u8D25: ${output || `\u9000\u51FA\u7801 ${loaded.status}`}${rollbackFailure}`);
884
+ }
885
+ return path;
886
+ }
887
+ function removeMacLaunchAgent() {
888
+ if (typeof process.getuid !== "function") return;
889
+ const path = launchAgentPath();
890
+ const domain = `gui/${process.getuid()}`;
891
+ const loaded = spawnSync3(
892
+ launchctlBin(),
893
+ ["print", `${domain}/${MAC_LAUNCH_AGENT_LABEL}`],
894
+ {
895
+ stdio: "ignore",
896
+ timeout: pm2CommandTimeoutMs(),
897
+ killSignal: "SIGKILL"
898
+ }
899
+ );
900
+ if (loaded.error) {
901
+ throw new Error(`[supertask] \u65E0\u6CD5\u786E\u8BA4 macOS LaunchAgent \u72B6\u6001: ${loaded.error.message}`);
902
+ }
903
+ if (loaded.status === 0) {
904
+ const removed = spawnSync3(
905
+ launchctlBin(),
906
+ ["bootout", `${domain}/${MAC_LAUNCH_AGENT_LABEL}`],
907
+ {
908
+ encoding: "utf8",
909
+ timeout: pm2CommandTimeoutMs(),
910
+ killSignal: "SIGKILL"
911
+ }
912
+ );
913
+ if (removed.status !== 0 || removed.error) {
914
+ const output = `${removed.stdout ?? ""}${removed.stderr ?? ""}`.trim();
915
+ throw new Error(
916
+ `[supertask] Gateway \u5DF2\u4ECE PM2 \u4E0E dump \u4E2D\u79FB\u9664\uFF0C\u4F46 macOS LaunchAgent \u505C\u6B62\u5931\u8D25: ` + (output || removed.error?.message || `\u9000\u51FA\u7801 ${removed.status}`)
917
+ );
918
+ }
919
+ }
920
+ rmSync(path, { force: true });
921
+ }
922
+ function systemdUnitMatchesPm2Home(unitContent, expectedPm2Home) {
923
+ const normalizedExpected = resolve3(expectedPm2Home);
924
+ const envAssignPattern = /(?<![A-Za-z0-9_])PM2_HOME=(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([^\s"']+))/g;
925
+ let match;
926
+ while ((match = envAssignPattern.exec(unitContent)) !== null) {
927
+ const rawValue = (match[1] ?? match[2] ?? match[3] ?? "").trim();
928
+ if (rawValue && resolve3(rawValue) === normalizedExpected) {
929
+ return true;
930
+ }
931
+ }
932
+ return false;
933
+ }
934
+ function isLinuxStartupConfigured(env = process.env, cwd = process.cwd(), expectedRuntime) {
935
+ const unit = env.SUPERTASK_PM2_SYSTEMD_UNIT ?? `pm2-${userInfo().username}.service`;
936
+ const enabled = spawnSync3(systemctlBin(env), ["is-enabled", unit], {
937
+ encoding: "utf8",
938
+ env,
939
+ stdio: ["ignore", "pipe", "ignore"],
940
+ timeout: pm2CommandTimeoutMs(env),
941
+ killSignal: "SIGKILL"
942
+ });
943
+ if (enabled.status !== 0 || enabled.stdout.trim() !== "enabled") return false;
944
+ const contents = spawnSync3(systemctlBin(env), ["cat", unit], {
945
+ encoding: "utf8",
946
+ env,
947
+ stdio: ["ignore", "pipe", "ignore"],
948
+ timeout: pm2CommandTimeoutMs(env),
949
+ killSignal: "SIGKILL"
950
+ });
951
+ if (contents.status !== 0) return false;
952
+ const expectedPm2Home = runtimeScope({ cwd, env }).pm2Home;
953
+ if (!contents.stdout.includes("resurrect") || !systemdUnitMatchesPm2Home(contents.stdout, expectedPm2Home)) {
954
+ return false;
955
+ }
956
+ try {
957
+ const runtime = readRestorableDumpGatewayRuntime(expectedPm2Home);
958
+ if (!runtime) return false;
959
+ return runtime.cwd === resolve3(cwd) && scopesMatch(runtimeScope(runtime), runtimeScope({ cwd, env })) && (expectedRuntime === void 0 || runtime.gatewayEntry === expectedRuntime.gatewayEntry && runtime.bunPath === expectedRuntime.bunPath);
960
+ } catch {
961
+ return false;
962
+ }
963
+ }
964
+
965
+ // src/daemon/pm2-lifecycle.ts
966
+ import { accessSync as accessSync3, constants as constants3, statSync as statSync2 } from "fs";
967
+ import { resolve as resolve4 } from "path";
968
+ function getGatewayDiagnostic(options = {}) {
969
+ const producerScope = currentScope();
970
+ if (!isPm2Installed()) {
971
+ return {
972
+ pm2Installed: false,
973
+ processFound: false,
974
+ status: null,
975
+ pid: null,
976
+ ready: false,
977
+ runningVersion: getRunningVersion(),
978
+ gatewayEntry: null,
979
+ gatewayPackageVersion: null,
980
+ logRotationInstalled: false,
981
+ startupConfigured: process.platform === "darwin" || process.platform === "linux" ? false : null,
982
+ currentScope: producerScope,
983
+ gatewayScope: null,
984
+ scopeMatches: false,
985
+ gatewayOpenCode: null
986
+ };
987
+ }
988
+ const processes = pm2JsonList();
989
+ const gateway = processes.find((item) => item.name === PROCESS_NAME);
990
+ const runtime = gatewayRuntimeFromProcess(gateway);
991
+ const gatewayEnv = runtime?.env ?? process.env;
992
+ const managedScope = runtime ? runtimeScope(runtime) : null;
993
+ const pid = typeof gateway?.pid === "number" ? gateway.pid : null;
994
+ const readyPath = managedScope?.databasePath ?? databasePath();
995
+ const lockedVersion = pid == null ? void 0 : gatewayVersionFromLock(pid, readyPath);
996
+ const gatewayEntry = runtime?.gatewayEntry ?? null;
997
+ return {
998
+ pm2Installed: true,
999
+ processFound: gateway != null,
1000
+ status: gateway?.pm2_env?.status ?? null,
1001
+ pid,
1002
+ ready: pid != null && isGatewayReady(pid, readyPath),
1003
+ runningVersion: lockedVersion === void 0 ? getRunningVersion(gatewayEnv, runtime?.cwd) : lockedVersion,
1004
+ gatewayEntry,
1005
+ gatewayPackageVersion: packageVersionFromGatewayEntry(gatewayEntry),
1006
+ logRotationInstalled: processes.some((item) => item.name === "pm2-logrotate" && item.pm2_env?.status === "online"),
1007
+ startupConfigured: process.platform === "darwin" ? isMacLaunchAgentConfigured(
1008
+ managedScope?.pm2Home ?? producerScope.pm2Home,
1009
+ runtime ?? void 0
1010
+ ) : process.platform === "linux" ? isLinuxStartupConfigured(gatewayEnv, runtime?.cwd, runtime ?? void 0) : null,
1011
+ currentScope: producerScope,
1012
+ gatewayScope: managedScope,
1013
+ scopeMatches: managedScope != null && scopesMatch(producerScope, managedScope),
1014
+ gatewayOpenCode: runtime === null || !options.probeOpenCode ? null : diagnoseOpenCodeRuntime(runtime)
1015
+ };
1016
+ }
1017
+ function isGatewayRunning() {
1018
+ if (!isPm2Installed()) return false;
1019
+ const proc = pm2JsonList().find((item) => item.name === PROCESS_NAME);
1020
+ const runtime = gatewayRuntimeFromProcess(proc);
1021
+ return proc?.pm2_env?.status === "online" && typeof proc.pid === "number" && runtime !== null && isGatewayReady(proc.pid, runtimeScope(runtime).databasePath);
1022
+ }
1023
+ function pm2StartGateway(runtime = currentGatewayRuntime(), expectedVersion) {
1024
+ try {
1025
+ accessSync3(runtime.bunPath, constants3.X_OK);
1026
+ accessSync3(runtime.gatewayEntry, constants3.R_OK);
1027
+ if (!statSync2(runtime.cwd).isDirectory()) throw new Error("cwd is not a directory");
1028
+ } catch (error) {
1029
+ throw new Error(`[supertask] Gateway \u76EE\u6807\u8FD0\u884C\u65F6\u4E0D\u53EF\u7528: ${error instanceof Error ? error.message : String(error)}`);
1030
+ }
1031
+ const killTimeoutMs = gatewayKillTimeoutMs(runtime);
1032
+ requirePm2([
1033
+ "start",
1034
+ runtime.bunPath,
1035
+ "--name",
1036
+ PROCESS_NAME,
1037
+ "--interpreter",
1038
+ "none",
1039
+ "--restart-delay",
1040
+ "5000",
1041
+ "--max-restarts",
1042
+ "30",
1043
+ "--max-memory-restart",
1044
+ pm2MaxMemoryRestart(runtime.env),
1045
+ "--kill-timeout",
1046
+ String(killTimeoutMs),
1047
+ "--cwd",
1048
+ runtime.cwd,
1049
+ "--",
1050
+ runtime.gatewayEntry
1051
+ ], "pm2 start", { env: runtime.env });
1052
+ const started = pm2JsonList(runtime.env).find((item) => item.name === PROCESS_NAME);
1053
+ if (started?.pm2_env?.status !== "online") {
1054
+ throw new Error(`[supertask] Gateway did not become online (status: ${started?.pm2_env?.status ?? "missing"})`);
1055
+ }
1056
+ const observedRuntime = gatewayRuntimeFromProcess(started);
1057
+ if (!observedRuntime || observedRuntime.gatewayEntry !== resolve4(runtime.gatewayEntry) || observedRuntime.bunPath !== runtime.bunPath || observedRuntime.cwd !== resolve4(runtime.cwd) || !scopesMatch(runtimeScope(observedRuntime), runtimeScope(runtime))) {
1058
+ throw new Error("[supertask] PM2 online \u8BB0\u5F55\u4E0E\u672C\u6B21\u542F\u52A8\u76EE\u6807\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u62D2\u7EDD\u63A5\u7BA1");
1059
+ }
1060
+ if (typeof started.pid !== "number" || !waitForGatewayReady(started.pid, runtimeScope(runtime).databasePath, runtime.env)) {
1061
+ throw new Error("[supertask] Gateway \u8FDB\u7A0B online\uFF0C\u4F46\u672A\u5728\u9650\u5B9A\u65F6\u95F4\u5185\u5C31\u7EEA\uFF1B\u8BF7\u67E5\u770B pm2 logs supertask-gateway");
1062
+ }
1063
+ const readyVersion = gatewayVersionFromLock(started.pid, runtimeScope(runtime).databasePath);
1064
+ if (expectedVersion !== void 0 && typeof readyVersion === "string" && readyVersion !== expectedVersion) {
1065
+ throw new Error(`[supertask] Gateway \u5DF2\u5C31\u7EEA\uFF0C\u4F46\u8FD0\u884C\u7248\u672C ${readyVersion} \u4E0D\u662F\u76EE\u6807\u7248\u672C ${expectedVersion}`);
1066
+ }
1067
+ }
1068
+ function rollbackFailedGatewayStart(error, targetRuntime, oldRuntime, before) {
1069
+ const message = (value) => value instanceof Error ? value.message : String(value);
1070
+ const problems = [];
1071
+ try {
1072
+ const failed = pm2JsonList(targetRuntime.env).find((item) => item.name === PROCESS_NAME);
1073
+ if (failed) {
1074
+ requirePm2Termination(
1075
+ "delete",
1076
+ "pm2 delete failed Gateway",
1077
+ gatewayRuntimeFromProcess(failed) ?? targetRuntime
1078
+ );
1079
+ }
1080
+ } catch (cleanupError) {
1081
+ problems.push(`\u6E05\u7406\u5931\u8D25\u7684\u65B0 Gateway \u5931\u8D25: ${message(cleanupError)}`);
1082
+ }
1083
+ if (!oldRuntime) {
1084
+ if (problems.length === 0) throw error;
1085
+ throw new Error(`${message(error)}; ${problems.join("; ")}`);
1086
+ }
1087
+ try {
1088
+ pm2StartGateway(oldRuntime);
1089
+ savePm2State(oldRuntime.env);
1090
+ if (before) writeRunningVersion(before, oldRuntime.env, oldRuntime.cwd);
1091
+ } catch (rollbackError) {
1092
+ problems.push(`\u65E7 Gateway \u56DE\u6EDA\u4E5F\u5931\u8D25: ${message(rollbackError)}`);
1093
+ throw new Error(`${message(error)}; ${problems.join("; ")}`);
1094
+ }
1095
+ throw new Error(`${message(error)}; ${[...problems, "\u5DF2\u56DE\u6EDA\u5230\u65E7 Gateway"].join("; ")}`);
1096
+ }
1097
+ function replaceGatewayProcess(params) {
1098
+ const { existing, oldRuntime, targetRuntime, version, before, deleteAction } = params;
1099
+ if (!params.controlAlreadyVerified) assertRuntimeCanControlPm2(oldRuntime, existing);
1100
+ gatewayKillTimeoutMs(targetRuntime);
1101
+ gatewayTerminationCommandTimeoutMs(targetRuntime);
1102
+ assertOpenCodeRuntime(targetRuntime);
1103
+ if (existing) requirePm2Termination("delete", deleteAction, oldRuntime);
1104
+ try {
1105
+ pm2StartGateway(targetRuntime, version);
1106
+ savePm2State(targetRuntime.env);
1107
+ writeRunningVersion(version, targetRuntime.env, targetRuntime.cwd);
1108
+ } catch (error) {
1109
+ rollbackFailedGatewayStart(error, targetRuntime, oldRuntime, before);
1110
+ }
1111
+ }
1112
+ function stopGatewayForMaintenance() {
1113
+ if (!isPm2Installed()) return { wasRunning: false };
1114
+ const proc = pm2JsonList().find((item) => item.name === PROCESS_NAME);
1115
+ const runtime = gatewayRuntimeFromProcess(proc);
1116
+ const managedCurrentDatabase = proc?.pm2_env?.status === "online" && typeof proc.pid === "number" && runtime !== null && scopesMatch(currentScope(), runtimeScope(runtime)) && isGatewayReady(proc.pid, runtimeScope(runtime).databasePath);
1117
+ if (!managedCurrentDatabase) return { wasRunning: false };
1118
+ assertRuntimeCanControlPm2(runtime, proc);
1119
+ assertPm2KillTimeoutCoversShutdown(runtime);
1120
+ const state = { wasRunning: true, env: runtime.env, cwd: runtime.cwd };
1121
+ try {
1122
+ requirePm2Termination("stop", "pm2 stop Gateway for database maintenance", runtime);
1123
+ } catch (error) {
1124
+ try {
1125
+ restartGatewayAfterMaintenance(state);
1126
+ } catch (restartError) {
1127
+ const original = error instanceof Error ? error.message : String(error);
1128
+ const restart = restartError instanceof Error ? restartError.message : String(restartError);
1129
+ throw new Error(`${original}\uFF1BGateway \u81EA\u52A8\u6062\u590D\u4E5F\u5931\u8D25\uFF1A${restart}`);
1130
+ }
1131
+ throw error;
1132
+ }
1133
+ return state;
1134
+ }
1135
+ function restartGatewayAfterMaintenance(state) {
1136
+ if (!state.wasRunning) return false;
1137
+ const env = state.env ?? process.env;
1138
+ const cwd = state.cwd ?? process.cwd();
1139
+ requirePm2(["start", PROCESS_NAME], "pm2 restart Gateway after database maintenance", { env });
1140
+ const started = pm2JsonList(env).find((item) => item.name === PROCESS_NAME);
1141
+ if (started?.pm2_env?.status !== "online") {
1142
+ throw new Error(
1143
+ `[supertask] Gateway \u6570\u636E\u5E93\u7EF4\u62A4\u540E\u672A\u6062\u590D online\uFF08\u72B6\u6001\uFF1A${started?.pm2_env?.status ?? "missing"}\uFF09`
1144
+ );
1145
+ }
1146
+ if (typeof started.pid !== "number" || !waitForGatewayReady(started.pid, databasePath(env, cwd), env)) {
1147
+ throw new Error("[supertask] Gateway \u6570\u636E\u5E93\u7EF4\u62A4\u540E\u5DF2 online\uFF0C\u4F46\u672A\u5728\u9650\u5B9A\u65F6\u95F4\u5185\u5C31\u7EEA\uFF1B\u8BF7\u67E5\u770B pm2 logs supertask-gateway");
1148
+ }
1149
+ return true;
1150
+ }
1151
+ function withGatewayMaintenance(keepStopped, operation, guard) {
1152
+ return withManagementLock(() => {
1153
+ const baseline = guard?.assertIdleBeforeStop();
1154
+ const state = stopGatewayForMaintenance();
1155
+ if (guard && baseline !== void 0) {
1156
+ try {
1157
+ guard.assertNoRunsStartedSince(baseline);
1158
+ } catch (error) {
1159
+ if (state.wasRunning) {
1160
+ try {
1161
+ restartGatewayAfterMaintenance(state);
1162
+ } catch (restartError) {
1163
+ const original = error instanceof Error ? error.message : String(error);
1164
+ const restart = restartError instanceof Error ? restartError.message : String(restartError);
1165
+ throw new Error(`${original}\uFF1BGateway \u81EA\u52A8\u6062\u590D\u4E5F\u5931\u8D25\uFF1A${restart}`);
1166
+ }
1167
+ }
1168
+ throw error;
1169
+ }
1170
+ }
1171
+ let result;
1172
+ try {
1173
+ result = operation();
1174
+ } catch (error) {
1175
+ if (state.wasRunning && !keepStopped) {
1176
+ try {
1177
+ restartGatewayAfterMaintenance(state);
1178
+ } catch (restartError) {
1179
+ const original = error instanceof Error ? error.message : String(error);
1180
+ const restart = restartError instanceof Error ? restartError.message : String(restartError);
1181
+ throw new Error(`${original}\uFF1BGateway \u81EA\u52A8\u6062\u590D\u4E5F\u5931\u8D25\uFF1A${restart}`);
1182
+ }
1183
+ }
1184
+ throw error;
1185
+ }
1186
+ let restarted = false;
1187
+ if (state.wasRunning && !keepStopped) {
1188
+ try {
1189
+ restarted = restartGatewayAfterMaintenance(state);
1190
+ } catch (error) {
1191
+ const message = error instanceof Error ? error.message : String(error);
1192
+ throw new Error(`\u6570\u636E\u5E93\u7EF4\u62A4\u5DF2\u5B8C\u6210\uFF0C\u4F46 Gateway \u81EA\u52A8\u91CD\u542F\u5931\u8D25\uFF1A${message}`);
1193
+ }
1194
+ }
1195
+ return {
1196
+ result,
1197
+ wasRunning: state.wasRunning,
1198
+ restarted,
1199
+ keptStopped: state.wasRunning && keepStopped
1200
+ };
1201
+ });
1202
+ }
1203
+ function install() {
1204
+ return withManagementLock(installUnlocked);
1205
+ }
1206
+ function installUnlocked() {
1207
+ if (!isPm2Installed() && !installPm2()) {
1208
+ throw new Error("[supertask] Failed to install pm2. Please install it manually: npm install -g pm2");
1209
+ }
1210
+ const existing = pm2JsonList().find((item) => item.name === PROCESS_NAME);
1211
+ const oldRuntime = gatewayRuntimeFromProcess(existing);
1212
+ const targetRuntime = oldRuntime ? refreshGatewayExecutionEnvironment(oldRuntime, resolveGatewayEntry()) : currentGatewayRuntime();
1213
+ const before = getRunningVersion(oldRuntime?.env ?? process.env, oldRuntime?.cwd);
1214
+ if (oldRuntime && !scopesMatch(currentScope(), runtimeScope(oldRuntime))) {
1215
+ throw new Error("[supertask] \u5F53\u524D CLI \u4E0E PM2 Gateway \u7684\u6570\u636E\u5E93/\u914D\u7F6E/OpenCode \u8FD0\u884C\u4F5C\u7528\u57DF\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u62D2\u7EDD\u8986\u76D6");
1216
+ }
1217
+ replaceGatewayProcess({
1218
+ existing,
1219
+ oldRuntime,
1220
+ targetRuntime,
1221
+ version: getPackageVersion(),
1222
+ before,
1223
+ deleteAction: "pm2 delete existing Gateway"
1224
+ });
1225
+ if (!ensurePm2LogRotation(targetRuntime.env)) {
1226
+ console.warn("[supertask] pm2-logrotate \u5B89\u88C5\u6216\u914D\u7F6E\u5931\u8D25\uFF1BGateway \u5DF2\u8FD0\u884C\uFF0C\u4F46\u8BF7\u6267\u884C `supertask doctor` \u68C0\u67E5\u65E5\u5FD7\u6CBB\u7406\u3002");
1227
+ }
1228
+ if (process.platform === "darwin") {
1229
+ const path = installMacLaunchAgent(targetRuntime);
1230
+ console.log(`[supertask] macOS LaunchAgent installed: ${path}`);
1231
+ } else {
1232
+ const startup = pm2Exec(["startup"], { env: targetRuntime.env });
1233
+ if (startup.output) console.log(startup.output);
1234
+ if (process.platform === "linux" && (!startup.ok || !isLinuxStartupConfigured(targetRuntime.env, targetRuntime.cwd, targetRuntime))) {
1235
+ throw new Error("[supertask] pm2 startup \u672A\u5B8C\u6210\u6216 systemd \u81EA\u542F\u672A\u751F\u6548\uFF1BGateway \u5F53\u524D\u5DF2\u8FD0\u884C\uFF0C\u4F46\u5B89\u88C5\u672A\u8FBE\u5230\u53EF\u91CD\u542F\u6062\u590D\u6807\u51C6");
1236
+ }
1237
+ }
1238
+ console.log("[supertask] Gateway installed and running.");
1239
+ console.log("[supertask] Manage with: pm2 status / pm2 logs supertask-gateway");
1240
+ }
1241
+ function uninstall() {
1242
+ return withManagementLock(uninstallUnlocked);
1243
+ }
1244
+ function uninstallUnlocked() {
1245
+ if (!isPm2Installed()) throw new Error("[supertask] pm2 is not installed");
1246
+ const existing = pm2JsonList().find((item) => item.name === PROCESS_NAME);
1247
+ const runtime = gatewayRuntimeFromProcess(existing);
1248
+ assertRuntimeCanControlPm2(runtime, existing);
1249
+ if (existing) requirePm2Termination("delete", "pm2 delete Gateway", runtime);
1250
+ savePm2State(runtime?.env);
1251
+ if (process.platform === "darwin") removeMacLaunchAgent();
1252
+ console.log("[supertask] Gateway removed from pm2. Other pm2 startup entries were preserved.");
1253
+ }
1254
+ function upgrade(target) {
1255
+ return withManagementLock(() => upgradeUnlocked(target));
1256
+ }
1257
+ function upgradeUnlocked(target) {
1258
+ if (!isPm2Installed()) {
1259
+ throw new Error("[supertask] pm2 is not installed. Run `supertask install` first.");
1260
+ }
1261
+ const existing = pm2JsonList().find((item) => item.name === PROCESS_NAME);
1262
+ const oldRuntime = existing ? gatewayRuntimeFromProcess(existing) ?? (process.env.SUPERTASK_GATEWAY_ENTRY ? currentGatewayRuntime(resolveGatewayEntry()) : null) : null;
1263
+ const before = getRunningVersion(oldRuntime?.env ?? process.env, oldRuntime?.cwd);
1264
+ const currentVersion = target?.version ?? getPackageVersion();
1265
+ const targetRuntime = oldRuntime ? refreshGatewayExecutionEnvironment(
1266
+ oldRuntime,
1267
+ target?.gatewayEntry ?? oldRuntime.gatewayEntry
1268
+ ) : currentGatewayRuntime(target?.gatewayEntry ?? resolveGatewayEntry());
1269
+ replaceGatewayProcess({
1270
+ existing,
1271
+ oldRuntime,
1272
+ targetRuntime,
1273
+ version: currentVersion,
1274
+ before,
1275
+ deleteAction: "pm2 delete old Gateway"
1276
+ });
1277
+ return { before, after: currentVersion, restarted: true };
1278
+ }
1279
+ function ensureGateway() {
1280
+ return withManagementLock(ensureGatewayUnlocked);
1281
+ }
1282
+ function ensureGatewayUnlocked() {
1283
+ if (!isPm2Installed()) {
1284
+ return { ok: false, reason: "pm2-not-installed" };
1285
+ }
1286
+ const currentVersion = getPackageVersion();
1287
+ const processList = pm2JsonList();
1288
+ const existing = processList.find((item) => item.name === PROCESS_NAME);
1289
+ const oldRuntime = gatewayRuntimeFromProcess(existing);
1290
+ if (oldRuntime && !scopesMatch(currentScope(), runtimeScope(oldRuntime))) {
1291
+ throw new Error("[supertask] \u5F53\u524D OpenCode/CLI \u4E0E PM2 Gateway \u7684\u6570\u636E\u5E93\u3001\u914D\u7F6E\u6216 OpenCode \u53EF\u6267\u884C\u6587\u4EF6\u4F5C\u7528\u57DF\u4E0D\u4E00\u81F4\uFF0C\u5DF2\u62D2\u7EDD\u7EE7\u7EED\u5199\u5165");
1292
+ }
1293
+ assertRuntimeCanControlPm2(oldRuntime, existing);
1294
+ const lockedVersion = existing && typeof existing.pid === "number" && oldRuntime ? gatewayVersionFromLock(existing.pid, runtimeScope(oldRuntime).databasePath) : void 0;
1295
+ if (existing?.pm2_env?.status === "online" && typeof existing.pid === "number" && oldRuntime !== null && isGatewayReady(existing.pid, runtimeScope(oldRuntime).databasePath) && (lockedVersion === currentVersion || lockedVersion === void 0 && getRunningVersion(oldRuntime.env, oldRuntime.cwd) === currentVersion)) {
1296
+ return { ok: true, action: "already-running" };
1297
+ }
1298
+ const targetRuntime = oldRuntime ? { ...oldRuntime, gatewayEntry: resolve4(resolveGatewayEntry()) } : currentGatewayRuntime();
1299
+ const before = getRunningVersion(oldRuntime?.env ?? process.env, oldRuntime?.cwd);
1300
+ replaceGatewayProcess({
1301
+ existing,
1302
+ oldRuntime,
1303
+ targetRuntime,
1304
+ version: currentVersion,
1305
+ before,
1306
+ deleteAction: "pm2 delete stale Gateway",
1307
+ controlAlreadyVerified: true
1308
+ });
1309
+ return { ok: true, action: existing ? "restarted" : "started" };
1310
+ }
1311
+
1312
+ export {
1313
+ resolveGatewayEntry,
1314
+ isPm2Installed,
1315
+ ensurePm2LogRotation,
1316
+ isGatewayReady,
1317
+ diagnoseOpenCodeRuntime,
1318
+ resolvePm2SupervisorEntry,
1319
+ isMacLaunchAgentConfigured,
1320
+ installMacLaunchAgent,
1321
+ isLinuxStartupConfigured,
1322
+ getGatewayDiagnostic,
1323
+ isGatewayRunning,
1324
+ stopGatewayForMaintenance,
1325
+ restartGatewayAfterMaintenance,
1326
+ withGatewayMaintenance,
1327
+ install,
1328
+ uninstall,
1329
+ upgrade,
1330
+ ensureGateway
1331
+ };
1332
+ //# sourceMappingURL=chunk-NCT3ETTK.js.map