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
@@ -1,42 +1,34 @@
1
- // src/daemon/pm2.ts
1
+ // src/daemon/pm2-cli.ts
2
2
  import { execSync, spawnSync } from "child_process";
3
3
  import {
4
4
  accessSync,
5
- chmodSync,
6
5
  constants,
7
6
  existsSync,
8
7
  mkdirSync,
9
8
  readFileSync,
10
- rmSync,
11
9
  statSync,
12
10
  writeFileSync
13
11
  } from "fs";
14
- import { homedir as homedir2, userInfo } from "os";
15
- import { delimiter, dirname, isAbsolute, join as join2, resolve } from "path";
16
- import { fileURLToPath } from "url";
17
- import { Database as Database2 } from "bun:sqlite";
18
-
19
- // src/gateway/config.ts
20
12
  import { homedir } from "os";
21
- import { join } from "path";
22
- var DEFAULT_CONFIG_PATH = join(homedir(), ".config/opencode/supertask.json");
23
-
24
- // src/daemon/management-lock.ts
13
+ import { delimiter, dirname, isAbsolute, join, resolve } from "path";
14
+ import { fileURLToPath } from "url";
25
15
  import { Database } from "bun:sqlite";
26
-
27
- // src/daemon/pm2.ts
28
16
  var __dirname = dirname(fileURLToPath(import.meta.url));
29
17
  var PROCESS_NAME = "supertask-gateway";
30
18
  var MAC_LAUNCH_AGENT_LABEL = "com.supertask.pm2-resurrect";
19
+ var PM2_DEFAULT_KILL_TIMEOUT_MS = 1600;
31
20
  var GATEWAY_LOCK_STALE_MS = 3e4;
32
21
  function runtimeHome(env) {
33
- return resolve(env.HOME || homedir2());
22
+ return resolve(env.HOME || homedir());
34
23
  }
35
24
  function runtimePath(value, cwd) {
36
25
  return resolve(cwd, value);
37
26
  }
27
+ function databasePath(env = process.env, cwd = process.cwd()) {
28
+ return env.SUPERTASK_DB_PATH ? runtimePath(env.SUPERTASK_DB_PATH, cwd) : join(runtimeHome(env), ".local/share/opencode/tasks.db");
29
+ }
38
30
  function versionFile(env = process.env, cwd = process.cwd()) {
39
- return env.SUPERTASK_VERSION_FILE ? runtimePath(env.SUPERTASK_VERSION_FILE, cwd) : join2(runtimeHome(env), ".local/share/opencode/supertask-gateway-version");
31
+ return env.SUPERTASK_VERSION_FILE ? runtimePath(env.SUPERTASK_VERSION_FILE, cwd) : join(runtimeHome(env), ".local/share/opencode/supertask-gateway-version");
40
32
  }
41
33
  function getRunningVersion(env = process.env, cwd = process.cwd()) {
42
34
  try {
@@ -51,7 +43,7 @@ function packageVersionFromGatewayEntry(gatewayEntry) {
51
43
  if (gatewayEntry === null) return null;
52
44
  let directory = dirname(gatewayEntry);
53
45
  for (let depth = 0; depth < 6; depth += 1) {
54
- const packagePath = join2(directory, "package.json");
46
+ const packagePath = join(directory, "package.json");
55
47
  if (existsSync(packagePath)) {
56
48
  try {
57
49
  const pkg = JSON.parse(readFileSync(packagePath, "utf8"));
@@ -80,94 +72,6 @@ function resolveRuntimeExecutable(command, env, cwd) {
80
72
  }
81
73
  return command;
82
74
  }
83
- function runtimeScope(runtime) {
84
- const { cwd, env } = runtime;
85
- const home = runtimeHome(env);
86
- return {
87
- cwd: resolve(cwd),
88
- databasePath: env.SUPERTASK_DB_PATH ? runtimePath(env.SUPERTASK_DB_PATH, cwd) : join2(home, ".local/share/opencode/tasks.db"),
89
- configPath: env.SUPERTASK_CONFIG_PATH ? runtimePath(env.SUPERTASK_CONFIG_PATH, cwd) : join2(home, ".config/opencode/supertask.json"),
90
- opencodePath: resolveRuntimeExecutable(env.SUPERTASK_OPENCODE_BIN ?? "opencode", env, cwd),
91
- home,
92
- pm2Home: env.PM2_HOME ? runtimePath(env.PM2_HOME, cwd) : join2(home, ".pm2"),
93
- managementLockPath: canonicalManagementLockPath(env, cwd)
94
- };
95
- }
96
- function scopesMatch(left, right) {
97
- 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;
98
- }
99
- function currentScope() {
100
- return runtimeScope({ cwd: process.cwd(), env: process.env });
101
- }
102
- function diagnoseOpenCodeRuntime(runtime = {
103
- cwd: process.cwd(),
104
- env: process.env
105
- }) {
106
- const executable = runtimeScope(runtime).opencodePath;
107
- const result = spawnSync(executable, ["--version"], {
108
- cwd: runtime.cwd,
109
- env: runtime.env,
110
- encoding: "utf8",
111
- timeout: 1e4,
112
- killSignal: "SIGKILL"
113
- });
114
- const ok = result.status === 0 && result.error === void 0;
115
- return {
116
- ok,
117
- executable,
118
- version: ok ? result.stdout.trim() || result.stderr.trim() || null : null,
119
- error: ok ? null : result.error?.message || result.stderr.trim() || result.stdout.trim() || `exit code ${result.status}`
120
- };
121
- }
122
- function getGatewayDiagnostic(options = {}) {
123
- const producerScope = currentScope();
124
- if (!isPm2Installed()) {
125
- return {
126
- pm2Installed: false,
127
- processFound: false,
128
- status: null,
129
- pid: null,
130
- ready: false,
131
- runningVersion: getRunningVersion(),
132
- gatewayEntry: null,
133
- gatewayPackageVersion: null,
134
- logRotationInstalled: false,
135
- startupConfigured: process.platform === "darwin" || process.platform === "linux" ? false : null,
136
- currentScope: producerScope,
137
- gatewayScope: null,
138
- scopeMatches: false,
139
- gatewayOpenCode: null
140
- };
141
- }
142
- const processes = pm2JsonList();
143
- const gateway = processes.find((item) => item.name === PROCESS_NAME);
144
- const runtime = gatewayRuntimeFromProcess(gateway);
145
- const gatewayEnv = runtime?.env ?? process.env;
146
- const managedScope = runtime ? runtimeScope(runtime) : null;
147
- const pid = typeof gateway?.pid === "number" ? gateway.pid : null;
148
- const readyPath = managedScope?.databasePath ?? databasePath();
149
- const lockedVersion = pid == null ? void 0 : gatewayVersionFromLock(pid, readyPath);
150
- const gatewayEntry = runtime?.gatewayEntry ?? null;
151
- return {
152
- pm2Installed: true,
153
- processFound: gateway != null,
154
- status: gateway?.pm2_env?.status ?? null,
155
- pid,
156
- ready: pid != null && isGatewayReady(pid, readyPath),
157
- runningVersion: lockedVersion === void 0 ? getRunningVersion(gatewayEnv, runtime?.cwd) : lockedVersion,
158
- gatewayEntry,
159
- gatewayPackageVersion: packageVersionFromGatewayEntry(gatewayEntry),
160
- logRotationInstalled: processes.some((item) => item.name === "pm2-logrotate" && item.pm2_env?.status === "online"),
161
- startupConfigured: process.platform === "darwin" ? isMacLaunchAgentConfigured(
162
- gatewayEnv.PM2_HOME ?? join2(runtimeHome(gatewayEnv), ".pm2"),
163
- runtime ?? void 0
164
- ) : process.platform === "linux" ? isLinuxStartupConfigured(gatewayEnv, runtime?.cwd, runtime ?? void 0) : null,
165
- currentScope: producerScope,
166
- gatewayScope: managedScope,
167
- scopeMatches: managedScope != null && scopesMatch(producerScope, managedScope),
168
- gatewayOpenCode: runtime === null || !options.probeOpenCode ? null : diagnoseOpenCodeRuntime(runtime)
169
- };
170
- }
171
75
  function pm2Bin(env = process.env) {
172
76
  return env.SUPERTASK_PM2_BIN ?? (process.platform === "win32" ? "pm2.cmd" : "pm2");
173
77
  }
@@ -175,20 +79,23 @@ function pm2CommandTimeoutMs(env = process.env) {
175
79
  const configured = Number(env.SUPERTASK_PM2_COMMAND_TIMEOUT_MS ?? 15e3);
176
80
  return Number.isFinite(configured) && configured > 0 ? configured : 15e3;
177
81
  }
178
- function resolvePm2Bin() {
179
- const configured = pm2Bin();
82
+ function resolvePm2Bin(env = process.env) {
83
+ const configured = pm2Bin(env);
180
84
  if (isAbsolute(configured)) return configured;
181
- const result = spawnSync("which", [configured], { encoding: "utf8" });
85
+ const result = spawnSync("which", [configured], { encoding: "utf8", env });
182
86
  const resolved = result.status === 0 ? result.stdout.trim().split("\n")[0] : "";
183
87
  if (!resolved) throw new Error(`[supertask] \u65E0\u6CD5\u89E3\u6790 pm2 \u53EF\u6267\u884C\u6587\u4EF6: ${configured}`);
184
88
  return resolved;
185
89
  }
186
90
  function launchAgentPath() {
187
- return process.env.SUPERTASK_LAUNCH_AGENT_PATH ?? join2(runtimeHome(process.env), "Library/LaunchAgents", `${MAC_LAUNCH_AGENT_LABEL}.plist`);
91
+ return process.env.SUPERTASK_LAUNCH_AGENT_PATH ?? join(runtimeHome(process.env), "Library/LaunchAgents", `${MAC_LAUNCH_AGENT_LABEL}.plist`);
188
92
  }
189
93
  function launchctlBin() {
190
94
  return process.env.SUPERTASK_LAUNCHCTL_BIN ?? "launchctl";
191
95
  }
96
+ function systemctlBin(env = process.env) {
97
+ return env.SUPERTASK_SYSTEMCTL_BIN ?? "systemctl";
98
+ }
192
99
  function xmlUnescape(value) {
193
100
  return value.replaceAll("&apos;", "'").replaceAll("&quot;", '"').replaceAll("&gt;", ">").replaceAll("&lt;", "<").replaceAll("&amp;", "&");
194
101
  }
@@ -197,100 +104,6 @@ function plistValue(contents, key) {
197
104
  const match = contents.match(new RegExp(`<key>\\s*${escapedKey}\\s*</key>\\s*<string>([^<]*)</string>`));
198
105
  return match?.[1] ? xmlUnescape(match[1]) : null;
199
106
  }
200
- function isMacLaunchAgentConfigured(expectedPm2Home, expectedRuntime) {
201
- if (typeof process.getuid !== "function") return false;
202
- const plistPath = launchAgentPath();
203
- if (!existsSync(plistPath)) return false;
204
- try {
205
- const contents = readFileSync(plistPath, "utf8");
206
- const argumentsBlock = contents.match(
207
- /<key>\s*ProgramArguments\s*<\/key>\s*<array>([\s\S]*?)<\/array>/
208
- )?.[1];
209
- const programArguments = argumentsBlock ? [...argumentsBlock.matchAll(/<string>([^<]*)<\/string>/g)].map((match) => xmlUnescape(match[1])) : [];
210
- const bunPath = programArguments[0];
211
- const supervisorEntry = programArguments[1];
212
- const pm2Path = programArguments[2];
213
- const pm2Home = plistValue(contents, "PM2_HOME");
214
- const managementLock = plistValue(contents, "SUPERTASK_PM2_MANAGEMENT_LOCK");
215
- if (!bunPath || !supervisorEntry || !pm2Path || !pm2Home || !managementLock) return false;
216
- if (expectedPm2Home && pm2Home !== expectedPm2Home) return false;
217
- const expectedManagementLock = expectedRuntime ? managementLockPath(expectedRuntime.env, expectedRuntime.cwd) : process.env.SUPERTASK_PM2_MANAGEMENT_LOCK ? managementLockPath() : join2(expectedPm2Home ?? currentScope().pm2Home, "supertask-gateway.manage.sqlite");
218
- if (managementLock !== expectedManagementLock) return false;
219
- accessSync(bunPath, constants.X_OK);
220
- accessSync(supervisorEntry, constants.R_OK);
221
- accessSync(pm2Path, constants.X_OK);
222
- if (spawnSync(bunPath, ["--version"], {
223
- stdio: "ignore",
224
- timeout: pm2CommandTimeoutMs(),
225
- killSignal: "SIGKILL"
226
- }).status !== 0) return false;
227
- if (spawnSync(pm2Path, ["--version"], {
228
- stdio: "ignore",
229
- env: { ...process.env, PM2_HOME: pm2Home },
230
- timeout: pm2CommandTimeoutMs(),
231
- killSignal: "SIGKILL"
232
- }).status !== 0) return false;
233
- const loaded = spawnSync(
234
- launchctlBin(),
235
- ["print", `gui/${process.getuid()}/${MAC_LAUNCH_AGENT_LABEL}`],
236
- {
237
- encoding: "utf8",
238
- stdio: ["ignore", "pipe", "ignore"],
239
- timeout: pm2CommandTimeoutMs(),
240
- killSignal: "SIGKILL"
241
- }
242
- );
243
- if (loaded.status !== 0) return false;
244
- if (!loaded.stdout.includes("state = running")) return false;
245
- if (!loaded.stdout.includes(`path = ${plistPath}`)) return false;
246
- if (!loaded.stdout.includes(`program = ${bunPath}`)) return false;
247
- const dumpPath = join2(pm2Home, "dump.pm2");
248
- const dump = JSON.parse(readFileSync(dumpPath, "utf8"));
249
- if (!Array.isArray(dump)) return false;
250
- const gateway = dump.find((item) => item.name === PROCESS_NAME);
251
- const dumpRuntime = gatewayRuntimeFromProcess(gateway);
252
- if (!dumpRuntime || !hasRestorableSavedGatewayRuntime(gateway)) return false;
253
- return expectedRuntime === void 0 || dumpRuntime.gatewayEntry === expectedRuntime.gatewayEntry && dumpRuntime.bunPath === expectedRuntime.bunPath && dumpRuntime.cwd === expectedRuntime.cwd && scopesMatch(runtimeScope(dumpRuntime), runtimeScope(expectedRuntime));
254
- } catch {
255
- return false;
256
- }
257
- }
258
- function systemctlBin(env = process.env) {
259
- return env.SUPERTASK_SYSTEMCTL_BIN ?? "systemctl";
260
- }
261
- function isLinuxStartupConfigured(env = process.env, cwd = process.cwd(), expectedRuntime) {
262
- const unit = env.SUPERTASK_PM2_SYSTEMD_UNIT ?? `pm2-${userInfo().username}.service`;
263
- const enabled = spawnSync(systemctlBin(env), ["is-enabled", unit], {
264
- encoding: "utf8",
265
- env,
266
- stdio: ["ignore", "pipe", "ignore"],
267
- timeout: pm2CommandTimeoutMs(env),
268
- killSignal: "SIGKILL"
269
- });
270
- if (enabled.status !== 0 || enabled.stdout.trim() !== "enabled") return false;
271
- const contents = spawnSync(systemctlBin(env), ["cat", unit], {
272
- encoding: "utf8",
273
- env,
274
- stdio: ["ignore", "pipe", "ignore"],
275
- timeout: pm2CommandTimeoutMs(env),
276
- killSignal: "SIGKILL"
277
- });
278
- if (contents.status !== 0) return false;
279
- const expectedPm2Home = env.PM2_HOME ?? join2(runtimeHome(env), ".pm2");
280
- if (!contents.stdout.includes("resurrect") || !contents.stdout.includes(expectedPm2Home)) {
281
- return false;
282
- }
283
- try {
284
- const dump = JSON.parse(readFileSync(join2(expectedPm2Home, "dump.pm2"), "utf8"));
285
- if (!Array.isArray(dump)) return false;
286
- const gateway = dump.find((item) => item.name === PROCESS_NAME);
287
- const runtime = gatewayRuntimeFromProcess(gateway);
288
- if (!runtime || !hasRestorableSavedGatewayRuntime(gateway)) return false;
289
- return runtime.cwd === resolve(cwd) && scopesMatch(runtimeScope(runtime), runtimeScope({ cwd, env })) && (expectedRuntime === void 0 || runtime.gatewayEntry === expectedRuntime.gatewayEntry && runtime.bunPath === expectedRuntime.bunPath);
290
- } catch {
291
- return false;
292
- }
293
- }
294
107
  function isPm2Installed(env = process.env) {
295
108
  const result = spawnSync(pm2Bin(env), ["--version"], {
296
109
  stdio: "ignore",
@@ -301,30 +114,38 @@ function isPm2Installed(env = process.env) {
301
114
  });
302
115
  return result.status === 0;
303
116
  }
304
- function resolveCommand(command) {
117
+ function resolveCommand(command, env = process.env) {
305
118
  const lookup = process.platform === "win32" ? "where" : "which";
306
- const result = spawnSync(lookup, [command], { encoding: "utf8" });
119
+ const result = spawnSync(lookup, [command], { encoding: "utf8", env });
307
120
  return result.status === 0 ? result.stdout.trim().split("\n")[0] || null : null;
308
121
  }
309
- function npmPreferredEnvironment() {
122
+ function npmPreferredEnvironment(baseEnv = process.env) {
310
123
  if (process.platform === "win32") return null;
311
- const npm = resolveCommand("npm");
312
- const node = resolveCommand("node");
124
+ const npm = resolveCommand("npm", baseEnv) ?? resolveCommand("npm", process.env);
125
+ const node = resolveCommand("node", baseEnv) ?? resolveCommand("node", process.env);
313
126
  if (!npm || !node) return null;
314
- const command = resolvePm2Bin();
127
+ let command;
128
+ try {
129
+ command = resolvePm2Bin(baseEnv);
130
+ } catch {
131
+ return null;
132
+ }
133
+ const existingPathEntries = (baseEnv.PATH ?? "").split(delimiter).filter(Boolean);
315
134
  const path = [.../* @__PURE__ */ new Set([
316
135
  dirname(command),
317
136
  dirname(npm),
318
137
  dirname(node),
138
+ ...existingPathEntries,
319
139
  "/usr/local/bin",
320
140
  "/usr/bin",
321
141
  "/bin"
322
142
  ])].join(delimiter);
323
- return { command, env: { ...process.env, PATH: path } };
143
+ return { command, env: { ...baseEnv, PATH: path } };
324
144
  }
325
145
  function pm2Exec(args, options = {}) {
326
- const npmEnvironment = options.preferNpm ? npmPreferredEnvironment() : null;
327
- const effectiveEnv = options.env ?? npmEnvironment?.env ?? process.env;
146
+ const baseEnv = options.env ?? process.env;
147
+ const npmEnvironment = options.preferNpm ? npmPreferredEnvironment(baseEnv) : null;
148
+ const effectiveEnv = npmEnvironment?.env ?? baseEnv;
328
149
  const result = spawnSync(npmEnvironment?.command ?? pm2Bin(effectiveEnv), args, {
329
150
  stdio: ["pipe", "pipe", "pipe"],
330
151
  encoding: "utf-8",
@@ -397,20 +218,27 @@ function gatewayRuntimeFromProcess(processInfo) {
397
218
  bunPath: savedBunPath,
398
219
  cwd: resolve(savedCwd),
399
220
  env: savedEnv,
400
- killTimeoutMs: Number.isInteger(killTimeout) && killTimeout >= 5e3 ? killTimeout : void 0
221
+ killTimeoutMs: Number.isInteger(killTimeout) && killTimeout >= 5e3 ? killTimeout : void 0,
222
+ pm2KillTimeoutMs: Number.isInteger(killTimeout) ? killTimeout : PM2_DEFAULT_KILL_TIMEOUT_MS
401
223
  };
402
224
  }
403
225
  function hasRestorableSavedGatewayRuntime(processInfo) {
404
226
  return gatewayRuntimeFromProcess(processInfo) !== null;
405
227
  }
406
- function databasePath(env = process.env, cwd = process.cwd()) {
407
- return env.SUPERTASK_DB_PATH ? runtimePath(env.SUPERTASK_DB_PATH, cwd) : join2(runtimeHome(env), ".local/share/opencode/tasks.db");
408
- }
409
- function isGatewayReady(expectedPid, path = databasePath()) {
410
- if (!existsSync(path)) return false;
228
+ function queryGatewayLock(path, query, fallback) {
229
+ if (!existsSync(path)) return fallback;
411
230
  let database = null;
412
231
  try {
413
- database = new Database2(path, { readonly: true });
232
+ database = new Database(path, { readonly: true });
233
+ return query(database);
234
+ } catch {
235
+ return fallback;
236
+ } finally {
237
+ database?.close();
238
+ }
239
+ }
240
+ function isGatewayReady(expectedPid, path = databasePath()) {
241
+ return queryGatewayLock(path, (database) => {
414
242
  const row = database.query(
415
243
  "SELECT pid, heartbeat_at, ready_at FROM gateway_lock WHERE id = 1"
416
244
  ).get();
@@ -418,37 +246,251 @@ function isGatewayReady(expectedPid, path = databasePath()) {
418
246
  if (expectedPid !== void 0 && row.pid !== expectedPid) return false;
419
247
  const ageMs = Date.now() - row.heartbeat_at;
420
248
  return ageMs >= -5e3 && ageMs < GATEWAY_LOCK_STALE_MS;
421
- } catch {
422
- return false;
423
- } finally {
424
- database?.close();
425
- }
249
+ }, false);
426
250
  }
427
251
  function gatewayVersionFromLock(expectedPid, path) {
428
- if (!existsSync(path)) return void 0;
429
- let database = null;
430
- try {
431
- database = new Database2(path, { readonly: true });
252
+ return queryGatewayLock(path, (database) => {
432
253
  const row = database.query(
433
254
  "SELECT pid, version FROM gateway_lock WHERE id = 1"
434
255
  ).get();
435
256
  if (!row || row.pid !== expectedPid) return void 0;
436
257
  return row.version;
437
- } catch {
438
- return void 0;
439
- } finally {
440
- database?.close();
441
- }
258
+ }, void 0);
259
+ }
260
+
261
+ // src/daemon/pm2-scope.ts
262
+ import { spawnSync as spawnSync2 } from "child_process";
263
+ import { join as join3, resolve as resolve2 } from "path";
264
+ import { Database as Database3 } from "bun:sqlite";
265
+
266
+ // src/gateway/config.ts
267
+ import { homedir as homedir2 } from "os";
268
+ import { join as join2 } from "path";
269
+ var DEFAULT_CONFIG_PATH = join2(homedir2(), ".config/opencode/supertask.json");
270
+
271
+ // src/daemon/management-lock.ts
272
+ import { Database as Database2 } from "bun:sqlite";
273
+
274
+ // src/daemon/pm2-scope.ts
275
+ function canonicalManagementLockPath(env = process.env, cwd = process.cwd()) {
276
+ const home = runtimeHome(env);
277
+ const pm2Home = env.PM2_HOME ? runtimePath(env.PM2_HOME, cwd) : join3(home, ".pm2");
278
+ return join3(pm2Home, "supertask-gateway.manage.sqlite");
442
279
  }
443
280
  function managementLockPath(env = process.env, cwd = process.cwd()) {
444
281
  const override = env.SUPERTASK_PM2_MANAGEMENT_LOCK;
445
282
  if (override) return runtimePath(override, cwd);
446
- return join2(runtimeScope({ env, cwd }).pm2Home, "supertask-gateway.manage.sqlite");
283
+ return join3(runtimeScope({ env, cwd }).pm2Home, "supertask-gateway.manage.sqlite");
447
284
  }
448
- function canonicalManagementLockPath(env = process.env, cwd = process.cwd()) {
285
+ function runtimeScope(runtime) {
286
+ const { cwd, env } = runtime;
449
287
  const home = runtimeHome(env);
450
- const pm2Home = env.PM2_HOME ? runtimePath(env.PM2_HOME, cwd) : join2(home, ".pm2");
451
- return join2(pm2Home, "supertask-gateway.manage.sqlite");
288
+ return {
289
+ cwd: resolve2(cwd),
290
+ databasePath: env.SUPERTASK_DB_PATH ? runtimePath(env.SUPERTASK_DB_PATH, cwd) : join3(home, ".local/share/opencode/tasks.db"),
291
+ configPath: env.SUPERTASK_CONFIG_PATH ? runtimePath(env.SUPERTASK_CONFIG_PATH, cwd) : join3(home, ".config/opencode/supertask.json"),
292
+ opencodePath: resolveRuntimeExecutable(env.SUPERTASK_OPENCODE_BIN ?? "opencode", env, cwd),
293
+ home,
294
+ pm2Home: env.PM2_HOME ? runtimePath(env.PM2_HOME, cwd) : join3(home, ".pm2"),
295
+ managementLockPath: canonicalManagementLockPath(env, cwd)
296
+ };
297
+ }
298
+ function scopesMatch(left, right) {
299
+ 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;
300
+ }
301
+ function currentScope() {
302
+ return runtimeScope({ cwd: process.cwd(), env: process.env });
303
+ }
304
+ function diagnoseOpenCodeRuntime(runtime = {
305
+ cwd: process.cwd(),
306
+ env: process.env
307
+ }) {
308
+ const executable = runtimeScope(runtime).opencodePath;
309
+ const result = spawnSync2(executable, ["--version"], {
310
+ cwd: runtime.cwd,
311
+ env: runtime.env,
312
+ encoding: "utf8",
313
+ timeout: 1e4,
314
+ killSignal: "SIGKILL"
315
+ });
316
+ const ok = result.status === 0 && result.error === void 0;
317
+ return {
318
+ ok,
319
+ executable,
320
+ version: ok ? result.stdout.trim() || result.stderr.trim() || null : null,
321
+ error: ok ? null : result.error?.message || result.stderr.trim() || result.stdout.trim() || `exit code ${result.status}`
322
+ };
323
+ }
324
+
325
+ // src/daemon/pm2-startup.ts
326
+ import { spawnSync as spawnSync3 } from "child_process";
327
+ import {
328
+ accessSync as accessSync2,
329
+ chmodSync,
330
+ constants as constants2,
331
+ existsSync as existsSync2,
332
+ mkdirSync as mkdirSync2,
333
+ readFileSync as readFileSync2,
334
+ rmSync,
335
+ writeFileSync as writeFileSync2
336
+ } from "fs";
337
+ import { userInfo } from "os";
338
+ import { dirname as dirname2, join as join4, resolve as resolve3 } from "path";
339
+ import { fileURLToPath as fileURLToPath2 } from "url";
340
+ var __dirname2 = dirname2(fileURLToPath2(import.meta.url));
341
+ function readRestorableDumpGatewayRuntime(pm2Home) {
342
+ const dump = JSON.parse(readFileSync2(join4(pm2Home, "dump.pm2"), "utf8"));
343
+ if (!Array.isArray(dump)) return null;
344
+ const gateway = dump.find((item) => item.name === PROCESS_NAME);
345
+ const runtime = gatewayRuntimeFromProcess(gateway);
346
+ return runtime && hasRestorableSavedGatewayRuntime(gateway) ? runtime : null;
347
+ }
348
+ function isMacLaunchAgentConfigured(expectedPm2Home, expectedRuntime) {
349
+ if (typeof process.getuid !== "function") return false;
350
+ const plistPath = launchAgentPath();
351
+ if (!existsSync2(plistPath)) return false;
352
+ try {
353
+ const contents = readFileSync2(plistPath, "utf8");
354
+ const argumentsBlock = contents.match(
355
+ /<key>\s*ProgramArguments\s*<\/key>\s*<array>([\s\S]*?)<\/array>/
356
+ )?.[1];
357
+ const programArguments = argumentsBlock ? [...argumentsBlock.matchAll(/<string>([^<]*)<\/string>/g)].map((match) => xmlUnescape(match[1])) : [];
358
+ const bunPath = programArguments[0];
359
+ const supervisorEntry = programArguments[1];
360
+ const pm2Path = programArguments[2];
361
+ const pm2Home = plistValue(contents, "PM2_HOME");
362
+ const managementLock = plistValue(contents, "SUPERTASK_PM2_MANAGEMENT_LOCK");
363
+ if (!bunPath || !supervisorEntry || !pm2Path || !pm2Home || !managementLock) return false;
364
+ if (expectedPm2Home && resolve3(pm2Home) !== resolve3(expectedPm2Home)) return false;
365
+ const expectedManagementLock = expectedRuntime ? managementLockPath(expectedRuntime.env, expectedRuntime.cwd) : process.env.SUPERTASK_PM2_MANAGEMENT_LOCK ? managementLockPath() : join4(expectedPm2Home ?? currentScope().pm2Home, "supertask-gateway.manage.sqlite");
366
+ if (managementLock !== expectedManagementLock) return false;
367
+ accessSync2(bunPath, constants2.X_OK);
368
+ accessSync2(supervisorEntry, constants2.R_OK);
369
+ accessSync2(pm2Path, constants2.X_OK);
370
+ if (spawnSync3(bunPath, ["--version"], {
371
+ stdio: "ignore",
372
+ timeout: pm2CommandTimeoutMs(),
373
+ killSignal: "SIGKILL"
374
+ }).status !== 0) return false;
375
+ if (spawnSync3(pm2Path, ["--version"], {
376
+ stdio: "ignore",
377
+ env: { ...process.env, PM2_HOME: pm2Home },
378
+ timeout: pm2CommandTimeoutMs(),
379
+ killSignal: "SIGKILL"
380
+ }).status !== 0) return false;
381
+ const loaded = spawnSync3(
382
+ launchctlBin(),
383
+ ["print", `gui/${process.getuid()}/${MAC_LAUNCH_AGENT_LABEL}`],
384
+ {
385
+ encoding: "utf8",
386
+ stdio: ["ignore", "pipe", "ignore"],
387
+ timeout: pm2CommandTimeoutMs(),
388
+ killSignal: "SIGKILL"
389
+ }
390
+ );
391
+ if (loaded.status !== 0) return false;
392
+ if (!loaded.stdout.includes("state = running")) return false;
393
+ if (!loaded.stdout.includes(`path = ${plistPath}`)) return false;
394
+ if (!loaded.stdout.includes(`program = ${bunPath}`)) return false;
395
+ const dumpRuntime = readRestorableDumpGatewayRuntime(pm2Home);
396
+ if (!dumpRuntime) return false;
397
+ return expectedRuntime === void 0 || dumpRuntime.gatewayEntry === expectedRuntime.gatewayEntry && dumpRuntime.bunPath === expectedRuntime.bunPath && dumpRuntime.cwd === expectedRuntime.cwd && scopesMatch(runtimeScope(dumpRuntime), runtimeScope(expectedRuntime));
398
+ } catch {
399
+ return false;
400
+ }
401
+ }
402
+ function systemdUnitMatchesPm2Home(unitContent, expectedPm2Home) {
403
+ const normalizedExpected = resolve3(expectedPm2Home);
404
+ const envAssignPattern = /(?<![A-Za-z0-9_])PM2_HOME=(?:"([^"\r\n]+)"|'([^'\r\n]+)'|([^\s"']+))/g;
405
+ let match;
406
+ while ((match = envAssignPattern.exec(unitContent)) !== null) {
407
+ const rawValue = (match[1] ?? match[2] ?? match[3] ?? "").trim();
408
+ if (rawValue && resolve3(rawValue) === normalizedExpected) {
409
+ return true;
410
+ }
411
+ }
412
+ return false;
413
+ }
414
+ function isLinuxStartupConfigured(env = process.env, cwd = process.cwd(), expectedRuntime) {
415
+ const unit = env.SUPERTASK_PM2_SYSTEMD_UNIT ?? `pm2-${userInfo().username}.service`;
416
+ const enabled = spawnSync3(systemctlBin(env), ["is-enabled", unit], {
417
+ encoding: "utf8",
418
+ env,
419
+ stdio: ["ignore", "pipe", "ignore"],
420
+ timeout: pm2CommandTimeoutMs(env),
421
+ killSignal: "SIGKILL"
422
+ });
423
+ if (enabled.status !== 0 || enabled.stdout.trim() !== "enabled") return false;
424
+ const contents = spawnSync3(systemctlBin(env), ["cat", unit], {
425
+ encoding: "utf8",
426
+ env,
427
+ stdio: ["ignore", "pipe", "ignore"],
428
+ timeout: pm2CommandTimeoutMs(env),
429
+ killSignal: "SIGKILL"
430
+ });
431
+ if (contents.status !== 0) return false;
432
+ const expectedPm2Home = runtimeScope({ cwd, env }).pm2Home;
433
+ if (!contents.stdout.includes("resurrect") || !systemdUnitMatchesPm2Home(contents.stdout, expectedPm2Home)) {
434
+ return false;
435
+ }
436
+ try {
437
+ const runtime = readRestorableDumpGatewayRuntime(expectedPm2Home);
438
+ if (!runtime) return false;
439
+ return runtime.cwd === resolve3(cwd) && scopesMatch(runtimeScope(runtime), runtimeScope({ cwd, env })) && (expectedRuntime === void 0 || runtime.gatewayEntry === expectedRuntime.gatewayEntry && runtime.bunPath === expectedRuntime.bunPath);
440
+ } catch {
441
+ return false;
442
+ }
443
+ }
444
+
445
+ // src/daemon/pm2-lifecycle.ts
446
+ function getGatewayDiagnostic(options = {}) {
447
+ const producerScope = currentScope();
448
+ if (!isPm2Installed()) {
449
+ return {
450
+ pm2Installed: false,
451
+ processFound: false,
452
+ status: null,
453
+ pid: null,
454
+ ready: false,
455
+ runningVersion: getRunningVersion(),
456
+ gatewayEntry: null,
457
+ gatewayPackageVersion: null,
458
+ logRotationInstalled: false,
459
+ startupConfigured: process.platform === "darwin" || process.platform === "linux" ? false : null,
460
+ currentScope: producerScope,
461
+ gatewayScope: null,
462
+ scopeMatches: false,
463
+ gatewayOpenCode: null
464
+ };
465
+ }
466
+ const processes = pm2JsonList();
467
+ const gateway = processes.find((item) => item.name === PROCESS_NAME);
468
+ const runtime = gatewayRuntimeFromProcess(gateway);
469
+ const gatewayEnv = runtime?.env ?? process.env;
470
+ const managedScope = runtime ? runtimeScope(runtime) : null;
471
+ const pid = typeof gateway?.pid === "number" ? gateway.pid : null;
472
+ const readyPath = managedScope?.databasePath ?? databasePath();
473
+ const lockedVersion = pid == null ? void 0 : gatewayVersionFromLock(pid, readyPath);
474
+ const gatewayEntry = runtime?.gatewayEntry ?? null;
475
+ return {
476
+ pm2Installed: true,
477
+ processFound: gateway != null,
478
+ status: gateway?.pm2_env?.status ?? null,
479
+ pid,
480
+ ready: pid != null && isGatewayReady(pid, readyPath),
481
+ runningVersion: lockedVersion === void 0 ? getRunningVersion(gatewayEnv, runtime?.cwd) : lockedVersion,
482
+ gatewayEntry,
483
+ gatewayPackageVersion: packageVersionFromGatewayEntry(gatewayEntry),
484
+ logRotationInstalled: processes.some((item) => item.name === "pm2-logrotate" && item.pm2_env?.status === "online"),
485
+ startupConfigured: process.platform === "darwin" ? isMacLaunchAgentConfigured(
486
+ managedScope?.pm2Home ?? producerScope.pm2Home,
487
+ runtime ?? void 0
488
+ ) : process.platform === "linux" ? isLinuxStartupConfigured(gatewayEnv, runtime?.cwd, runtime ?? void 0) : null,
489
+ currentScope: producerScope,
490
+ gatewayScope: managedScope,
491
+ scopeMatches: managedScope != null && scopesMatch(producerScope, managedScope),
492
+ gatewayOpenCode: runtime === null || !options.probeOpenCode ? null : diagnoseOpenCodeRuntime(runtime)
493
+ };
452
494
  }
453
495
 
454
496
  // src/daemon/gateway-diagnostic-runner.ts