opencode-supertask 0.2.1 → 0.3.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (80) hide show
  1. package/CHANGELOG.md +34 -0
  2. package/README.md +10 -0
  3. package/README.zh-CN.md +10 -0
  4. package/dist/cli/{chunk-NCT3ETTK.js → chunk-7BATA4DM.js} +20 -1
  5. package/dist/cli/chunk-7BATA4DM.js.map +1 -0
  6. package/dist/cli/{chunk-J34FWHQU.js → chunk-ETLJ4YXW.js} +3 -2
  7. package/dist/cli/chunk-ETLJ4YXW.js.map +1 -0
  8. package/dist/cli/{chunk-AZM76ISG.js → chunk-INW2NH3O.js} +6 -5
  9. package/dist/cli/chunk-INW2NH3O.js.map +1 -0
  10. package/dist/cli/{chunk-CMEP6IB4.js → chunk-K6UTYKN5.js} +19 -5
  11. package/dist/cli/{chunk-CMEP6IB4.js.map → chunk-K6UTYKN5.js.map} +1 -1
  12. package/dist/cli/{chunk-ZBH7YWXF.js → chunk-KC34M3F3.js} +2 -2
  13. package/dist/cli/{chunk-DF56RPNL.js → chunk-MZLIVCEU.js} +10 -2
  14. package/dist/cli/{chunk-DF56RPNL.js.map → chunk-MZLIVCEU.js.map} +1 -1
  15. package/dist/cli/{chunk-5VKFECHP.js → chunk-OJLDJVHB.js} +3 -3
  16. package/dist/cli/{chunk-LX5CBJLP.js → chunk-WHGCKWMR.js} +26 -3
  17. package/dist/cli/chunk-WHGCKWMR.js.map +1 -0
  18. package/dist/cli/{chunk-EQWICVCJ.js → chunk-XUCZLWCB.js} +48 -6
  19. package/dist/cli/chunk-XUCZLWCB.js.map +1 -0
  20. package/dist/cli/{chunk-YB7MYTE5.js → chunk-XWTKMNNI.js} +3 -1
  21. package/dist/cli/chunk-XWTKMNNI.js.map +1 -0
  22. package/dist/cli/{chunk-DIJEKFBV.js → chunk-YADLWDYK.js} +4 -4
  23. package/dist/cli/{chunk-YGELD2E5.js → chunk-ZIR7RA5B.js} +7 -4
  24. package/dist/cli/{chunk-YGELD2E5.js.map → chunk-ZIR7RA5B.js.map} +1 -1
  25. package/dist/cli/database-maintenance.service-NQBZ5VJT.js +16 -0
  26. package/dist/cli/{db-H7GIFWS2.js → db-KWSXP22E.js} +2 -2
  27. package/dist/cli/{doctor-smoke-QXHF7UNN.js → doctor-smoke-6VU2KCRK.js} +7 -7
  28. package/dist/cli/{gateway-BYLLK72W.js → gateway-I2SQOXWB.js} +686 -24
  29. package/dist/cli/gateway-I2SQOXWB.js.map +1 -0
  30. package/dist/cli/{gateway-wake-U4HTV56Q.js → gateway-wake-M5EXAIGD.js} +2 -2
  31. package/dist/cli/index.js +38 -38
  32. package/dist/cli/{job-templates-RPQJ4XXW.js → job-templates-FH7SGS34.js} +5 -5
  33. package/dist/cli/{logs-QD2N62KK.js → logs-HB5RV7HD.js} +7 -7
  34. package/dist/cli/{pm2-WY644BUO.js → pm2-YSCAIIBU.js} +2 -2
  35. package/dist/cli/task-run.service-R45W2VID.js +15 -0
  36. package/dist/cli/task-template.service-VA4WBJA4.js +12 -0
  37. package/dist/cli/{task.service-ZVDJ6VSQ.js → task.service-RB6RKV7T.js} +3 -3
  38. package/dist/cli/{update-FYD546I2.js → update-FMCBRTHT.js} +4 -4
  39. package/dist/cli/{web-J3FJ23FE.js → web-4QWJ4Z5K.js} +157 -17
  40. package/dist/cli/{web-J3FJ23FE.js.map → web-4QWJ4Z5K.js.map} +1 -1
  41. package/dist/daemon/gateway-diagnostic-runner.js.map +1 -1
  42. package/dist/gateway/index.d.ts +1 -0
  43. package/dist/gateway/index.js +929 -31
  44. package/dist/gateway/index.js.map +1 -1
  45. package/dist/plugin/supertask.js +106 -11
  46. package/dist/plugin/supertask.js.map +1 -1
  47. package/dist/web/index.js +235 -16
  48. package/dist/web/index.js.map +1 -1
  49. package/dist/worker/index.d.ts +492 -1
  50. package/dist/worker/index.js +728 -20
  51. package/dist/worker/index.js.map +1 -1
  52. package/dist/worker/launcher.js.map +1 -1
  53. package/drizzle/0010_task_metadata.sql +2 -0
  54. package/drizzle/meta/0010_snapshot.json +695 -0
  55. package/drizzle/meta/_journal.json +7 -0
  56. package/package.json +1 -1
  57. package/dist/cli/chunk-AZM76ISG.js.map +0 -1
  58. package/dist/cli/chunk-EQWICVCJ.js.map +0 -1
  59. package/dist/cli/chunk-J34FWHQU.js.map +0 -1
  60. package/dist/cli/chunk-LX5CBJLP.js.map +0 -1
  61. package/dist/cli/chunk-NCT3ETTK.js.map +0 -1
  62. package/dist/cli/chunk-YB7MYTE5.js.map +0 -1
  63. package/dist/cli/database-maintenance.service-F3IZU52F.js +0 -16
  64. package/dist/cli/gateway-BYLLK72W.js.map +0 -1
  65. package/dist/cli/task-run.service-QMDINJKG.js +0 -15
  66. package/dist/cli/task-template.service-SZBKGLCB.js +0 -12
  67. /package/dist/cli/{chunk-ZBH7YWXF.js.map → chunk-KC34M3F3.js.map} +0 -0
  68. /package/dist/cli/{chunk-5VKFECHP.js.map → chunk-OJLDJVHB.js.map} +0 -0
  69. /package/dist/cli/{chunk-DIJEKFBV.js.map → chunk-YADLWDYK.js.map} +0 -0
  70. /package/dist/cli/{database-maintenance.service-F3IZU52F.js.map → database-maintenance.service-NQBZ5VJT.js.map} +0 -0
  71. /package/dist/cli/{db-H7GIFWS2.js.map → db-KWSXP22E.js.map} +0 -0
  72. /package/dist/cli/{doctor-smoke-QXHF7UNN.js.map → doctor-smoke-6VU2KCRK.js.map} +0 -0
  73. /package/dist/cli/{gateway-wake-U4HTV56Q.js.map → gateway-wake-M5EXAIGD.js.map} +0 -0
  74. /package/dist/cli/{job-templates-RPQJ4XXW.js.map → job-templates-FH7SGS34.js.map} +0 -0
  75. /package/dist/cli/{logs-QD2N62KK.js.map → logs-HB5RV7HD.js.map} +0 -0
  76. /package/dist/cli/{pm2-WY644BUO.js.map → pm2-YSCAIIBU.js.map} +0 -0
  77. /package/dist/cli/{task-run.service-QMDINJKG.js.map → task-run.service-R45W2VID.js.map} +0 -0
  78. /package/dist/cli/{task-template.service-SZBKGLCB.js.map → task-template.service-VA4WBJA4.js.map} +0 -0
  79. /package/dist/cli/{task.service-ZVDJ6VSQ.js.map → task.service-RB6RKV7T.js.map} +0 -0
  80. /package/dist/cli/{update-FYD546I2.js.map → update-FMCBRTHT.js.map} +0 -0
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/daemon/pm2-cli.ts","../../src/daemon/pm2-scope.ts","../../src/daemon/management-lock.ts","../../src/daemon/pm2-startup.ts","../../src/daemon/pm2-lifecycle.ts"],"sourcesContent":["import { execSync, spawnSync } from \"child_process\";\nimport {\n accessSync,\n constants,\n existsSync,\n mkdirSync,\n readFileSync,\n statSync,\n writeFileSync,\n} from \"fs\";\nimport { homedir } from \"os\";\nimport { delimiter, dirname, isAbsolute, join, resolve } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport { Database } from \"bun:sqlite\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nexport const PROCESS_NAME = \"supertask-gateway\";\nexport const MAC_LAUNCH_AGENT_LABEL = \"com.supertask.pm2-resurrect\";\n// PM2 未显式配置 kill_timeout 时的默认值。\nexport const PM2_DEFAULT_KILL_TIMEOUT_MS = 1_600;\nexport const GATEWAY_LOCK_STALE_MS = 30_000;\n\nexport interface Pm2Process {\n name: string;\n pid?: number;\n args?: string[] | string;\n pm_exec_path?: string;\n pm_cwd?: string;\n env?: Record<string, unknown>;\n kill_timeout?: number;\n pm2_env?: {\n status?: string;\n args?: string[] | string;\n pm_exec_path?: string;\n pm_cwd?: string;\n env?: Record<string, unknown>;\n kill_timeout?: number;\n };\n}\n\nexport interface GatewayRuntime {\n gatewayEntry: string;\n bunPath: string;\n cwd: string;\n env: NodeJS.ProcessEnv;\n killTimeoutMs?: number;\n /** 已存在 PM2 进程实际生效的 kill_timeout(未保存时为 PM2 默认值);仅来自 jlist 的运行态才有。 */\n pm2KillTimeoutMs?: number;\n}\n\nexport interface RuntimeScope {\n cwd: string;\n databasePath: string;\n configPath: string;\n opencodePath: string;\n home: string;\n pm2Home: string;\n managementLockPath: string;\n}\n\nexport interface OpenCodeRuntimeDiagnostic {\n ok: boolean;\n executable: string;\n version: string | null;\n error: string | null;\n}\n\nexport interface GatewayDiagnostic {\n pm2Installed: boolean;\n processFound: boolean;\n status: string | null;\n pid: number | null;\n ready: boolean;\n runningVersion: string | null;\n gatewayEntry: string | null;\n gatewayPackageVersion: string | null;\n logRotationInstalled: boolean;\n startupConfigured: boolean | null;\n currentScope: RuntimeScope;\n gatewayScope: RuntimeScope | null;\n scopeMatches: boolean;\n gatewayOpenCode: OpenCodeRuntimeDiagnostic | null;\n}\n\nexport type EnsureGatewayResult =\n | { ok: true; action: \"already-running\" | \"started\" | \"restarted\" }\n | { ok: false; reason: \"pm2-not-installed\" };\n\nexport interface GatewayMaintenanceState {\n wasRunning: boolean;\n env?: NodeJS.ProcessEnv;\n cwd?: string;\n}\n\nexport interface GatewayMaintenanceResult<T> {\n result: T;\n wasRunning: boolean;\n restarted: boolean;\n keptStopped: boolean;\n}\n\n/** 停机前后的运行中工作检查;停机会中断并重置运行中任务,所以不能只在停机后检查。 */\nexport interface GatewayMaintenanceWorkGuard {\n assertIdleBeforeStop(): number;\n assertNoRunsStartedSince(baseline: number): void;\n}\n\nexport function resolveGatewayEntry(): string {\n const override = process.env.SUPERTASK_GATEWAY_ENTRY;\n if (override) {\n if (!existsSync(override)) throw new Error(`[supertask] Gateway entry not found: ${override}`);\n return override;\n }\n\n const candidates = [\n join(__dirname, \"../gateway/index.js\"),\n join(__dirname, \"../gateway/index.ts\"),\n ];\n const entry = candidates.find((candidate) => existsSync(candidate));\n if (!entry) throw new Error(`[supertask] Gateway entry not found. Checked: ${candidates.join(\", \")}`);\n return entry;\n}\n\nexport function runtimeHome(env: NodeJS.ProcessEnv): string {\n return resolve(env.HOME || homedir());\n}\n\nexport function runtimePath(value: string, cwd: string): string {\n return resolve(cwd, value);\n}\n\nexport function databasePath(env: NodeJS.ProcessEnv = process.env, cwd = process.cwd()): string {\n return env.SUPERTASK_DB_PATH\n ? runtimePath(env.SUPERTASK_DB_PATH, cwd)\n : join(runtimeHome(env), \".local/share/opencode/tasks.db\");\n}\n\nfunction versionFile(env: NodeJS.ProcessEnv = process.env, cwd = process.cwd()): string {\n return env.SUPERTASK_VERSION_FILE\n ? runtimePath(env.SUPERTASK_VERSION_FILE, cwd)\n : join(runtimeHome(env), \".local/share/opencode/supertask-gateway-version\");\n}\n\nexport function getRunningVersion(env: NodeJS.ProcessEnv = process.env, cwd = process.cwd()): string | null {\n try {\n const path = versionFile(env, cwd);\n if (!existsSync(path)) return null;\n return readFileSync(path, \"utf-8\").trim() || null;\n } catch {\n return null;\n }\n}\n\nexport function writeRunningVersion(\n version: string,\n env: NodeJS.ProcessEnv = process.env,\n cwd = process.cwd(),\n): void {\n const path = versionFile(env, cwd);\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, version, \"utf-8\");\n}\n\nexport function packageVersionFromGatewayEntry(gatewayEntry: string | null): string | null {\n if (gatewayEntry === null) return null;\n let directory = dirname(gatewayEntry);\n for (let depth = 0; depth < 6; depth += 1) {\n const packagePath = join(directory, \"package.json\");\n if (existsSync(packagePath)) {\n try {\n const pkg = JSON.parse(readFileSync(packagePath, \"utf8\")) as {\n name?: unknown;\n version?: unknown;\n };\n if (pkg.name === \"opencode-supertask\" && typeof pkg.version === \"string\") {\n return pkg.version;\n }\n } catch {}\n }\n const parent = dirname(directory);\n if (parent === directory) break;\n directory = parent;\n }\n return null;\n}\n\nexport function resolveRuntimeExecutable(command: string, env: NodeJS.ProcessEnv, cwd: string): string {\n if (isAbsolute(command) || command.includes(\"/\")) return runtimePath(command, cwd);\n for (const entry of (env.PATH ?? \"\").split(delimiter)) {\n if (!entry) continue;\n const candidate = resolve(cwd, entry, command);\n try {\n accessSync(candidate, constants.X_OK);\n return candidate;\n } catch {}\n }\n return command;\n}\n\nexport function findBunPath(): string {\n const override = process.env.SUPERTASK_BUN_BIN;\n if (override) return override;\n try {\n const command = process.platform === \"win32\" ? \"where bun\" : \"which bun\";\n return execSync(command, { stdio: \"pipe\" }).toString().trim().split(\"\\n\")[0];\n } catch {\n return process.execPath;\n }\n}\n\nexport function pm2Bin(env: NodeJS.ProcessEnv = process.env): string {\n return env.SUPERTASK_PM2_BIN\n ?? (process.platform === \"win32\" ? \"pm2.cmd\" : \"pm2\");\n}\n\nexport function pm2CommandTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {\n const configured = Number(env.SUPERTASK_PM2_COMMAND_TIMEOUT_MS ?? 15_000);\n return Number.isFinite(configured) && configured > 0 ? configured : 15_000;\n}\n\nexport function resolvePm2Bin(env: NodeJS.ProcessEnv = process.env): string {\n const configured = pm2Bin(env);\n if (isAbsolute(configured)) return configured;\n const result = spawnSync(\"which\", [configured], { encoding: \"utf8\", env });\n const resolved = result.status === 0 ? result.stdout.trim().split(\"\\n\")[0] : \"\";\n if (!resolved) throw new Error(`[supertask] 无法解析 pm2 可执行文件: ${configured}`);\n return resolved;\n}\n\nexport function launchAgentPath(): string {\n return process.env.SUPERTASK_LAUNCH_AGENT_PATH\n ?? join(runtimeHome(process.env), \"Library/LaunchAgents\", `${MAC_LAUNCH_AGENT_LABEL}.plist`);\n}\n\nexport function launchctlBin(): string {\n return process.env.SUPERTASK_LAUNCHCTL_BIN ?? \"launchctl\";\n}\n\nexport function systemctlBin(env: NodeJS.ProcessEnv = process.env): string {\n return env.SUPERTASK_SYSTEMCTL_BIN ?? \"systemctl\";\n}\n\nexport function xmlEscape(value: string): string {\n return value\n .replaceAll(\"&\", \"&amp;\")\n .replaceAll(\"<\", \"&lt;\")\n .replaceAll(\">\", \"&gt;\")\n .replaceAll('\"', \"&quot;\")\n .replaceAll(\"'\", \"&apos;\");\n}\n\nexport function xmlUnescape(value: string): string {\n return value\n .replaceAll(\"&apos;\", \"'\")\n .replaceAll(\"&quot;\", '\"')\n .replaceAll(\"&gt;\", \">\")\n .replaceAll(\"&lt;\", \"<\")\n .replaceAll(\"&amp;\", \"&\");\n}\n\nexport function plistValue(contents: string, key: string): string | null {\n const escapedKey = key.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n const match = contents.match(new RegExp(`<key>\\\\s*${escapedKey}\\\\s*</key>\\\\s*<string>([^<]*)</string>`));\n return match?.[1] ? xmlUnescape(match[1]) : null;\n}\n\nexport function isPm2Installed(env: NodeJS.ProcessEnv = process.env): boolean {\n const result = spawnSync(pm2Bin(env), [\"--version\"], {\n stdio: \"ignore\",\n env,\n shell: process.platform === \"win32\",\n timeout: pm2CommandTimeoutMs(env),\n killSignal: \"SIGKILL\",\n });\n return result.status === 0;\n}\n\nexport function installPm2(): boolean {\n console.log(\"[supertask] Installing pm2...\");\n try {\n execSync(\"npm install -g pm2\", { stdio: \"inherit\" });\n return true;\n } catch {\n try {\n execSync(\"bun install -g pm2\", { stdio: \"inherit\" });\n return true;\n } catch {\n return false;\n }\n }\n}\n\nfunction resolveCommand(command: string, env: NodeJS.ProcessEnv = process.env): string | null {\n const lookup = process.platform === \"win32\" ? \"where\" : \"which\";\n const result = spawnSync(lookup, [command], { encoding: \"utf8\", env });\n return result.status === 0 ? result.stdout.trim().split(\"\\n\")[0] || null : null;\n}\n\nfunction npmPreferredEnvironment(\n baseEnv: NodeJS.ProcessEnv = process.env,\n): { command: string; env: NodeJS.ProcessEnv } | null {\n if (process.platform === \"win32\") return null;\n const npm = resolveCommand(\"npm\", baseEnv) ?? resolveCommand(\"npm\", process.env);\n const node = resolveCommand(\"node\", baseEnv) ?? resolveCommand(\"node\", process.env);\n if (!npm || !node) return null;\n let command: string;\n try {\n command = resolvePm2Bin(baseEnv);\n } catch {\n return null;\n }\n const existingPathEntries = (baseEnv.PATH ?? \"\").split(delimiter).filter(Boolean);\n const path = [...new Set([\n dirname(command),\n dirname(npm),\n dirname(node),\n ...existingPathEntries,\n \"/usr/local/bin\",\n \"/usr/bin\",\n \"/bin\",\n ])].join(delimiter);\n return { command, env: { ...baseEnv, PATH: path } };\n}\n\nexport function pm2Exec(\n args: string[],\n options: { preferNpm?: boolean; env?: NodeJS.ProcessEnv; timeoutMs?: number } = {},\n): { ok: boolean; output: string } {\n const baseEnv = options.env ?? process.env;\n const npmEnvironment = options.preferNpm ? npmPreferredEnvironment(baseEnv) : null;\n const effectiveEnv = npmEnvironment?.env ?? baseEnv;\n const result = spawnSync(npmEnvironment?.command ?? pm2Bin(effectiveEnv), args, {\n stdio: [\"pipe\", \"pipe\", \"pipe\"],\n encoding: \"utf-8\",\n env: effectiveEnv,\n shell: process.platform === \"win32\",\n timeout: options.timeoutMs ?? pm2CommandTimeoutMs(effectiveEnv),\n killSignal: \"SIGKILL\",\n });\n const output = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`.trim();\n if (result.error) return { ok: false, output: result.error.message };\n return { ok: result.status === 0, output };\n}\n\nexport function requirePm2(\n args: string[],\n action: string,\n options: { env?: NodeJS.ProcessEnv; timeoutMs?: number } = {},\n): string {\n const result = pm2Exec(args, options);\n if (!result.ok) throw new Error(`[supertask] ${action} failed: ${result.output || \"unknown pm2 error\"}`);\n return result.output;\n}\n\nexport function ensurePm2LogRotation(env: NodeJS.ProcessEnv = process.env): boolean {\n if (!isPm2Installed(env)) return false;\n const installed = pm2JsonList(env).some((item) => item.name === \"pm2-logrotate\");\n if (!installed) {\n const result = pm2Exec([\"install\", \"pm2-logrotate\"], { preferNpm: true, env });\n if (!result.ok) return false;\n }\n\n for (const [key, value] of [\n [\"max_size\", \"10M\"],\n [\"retain\", \"7\"],\n [\"compress\", \"true\"],\n [\"workerInterval\", \"3600\"],\n ] as const) {\n const result = pm2Exec([\"set\", `pm2-logrotate:${key}`, value], { env });\n if (!result.ok) return false;\n }\n return true;\n}\n\nexport function pm2JsonList(env: NodeJS.ProcessEnv = process.env): Pm2Process[] {\n const output = requirePm2([\"jlist\"], \"pm2 jlist\", { env });\n try {\n const parsed = JSON.parse(output) as unknown;\n if (!Array.isArray(parsed)) throw new Error(\"result is not an array\");\n return parsed as Pm2Process[];\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`[supertask] Invalid pm2 jlist output: ${message}`);\n }\n}\n\nexport function savePm2State(env: NodeJS.ProcessEnv = process.env): void {\n requirePm2([\"save\"], \"pm2 save\", { env });\n}\n\nfunction gatewayEntryFromProcess(processInfo: Pm2Process | undefined): string | null {\n const args = processInfo?.pm2_env?.args ?? processInfo?.args;\n const candidates = Array.isArray(args) ? [...args].reverse() : typeof args === \"string\" ? [args] : [];\n const savedCwd = processInfo?.pm2_env?.pm_cwd ?? processInfo?.pm_cwd;\n for (const candidate of candidates) {\n const path = typeof savedCwd === \"string\" ? runtimePath(candidate, savedCwd) : candidate;\n if (existsSync(path)) return resolve(path);\n }\n return null;\n}\n\nfunction gatewayEnvironmentFromProcess(processInfo: Pm2Process | undefined): NodeJS.ProcessEnv {\n const saved = processInfo?.pm2_env?.env ?? processInfo?.env;\n if (!saved) return { ...process.env };\n\n const env: NodeJS.ProcessEnv = {};\n for (const [key, value] of Object.entries(saved)) {\n if (typeof value === \"string\") env[key] = value;\n }\n return env;\n}\n\nexport function gatewayRuntimeFromProcess(processInfo: Pm2Process | undefined): GatewayRuntime | null {\n const gatewayEntry = gatewayEntryFromProcess(processInfo);\n if (!gatewayEntry) return null;\n const savedBunPath = processInfo?.pm2_env?.pm_exec_path ?? processInfo?.pm_exec_path;\n const savedCwd = processInfo?.pm2_env?.pm_cwd ?? processInfo?.pm_cwd;\n const savedEnv = gatewayEnvironmentFromProcess(processInfo);\n if (typeof savedBunPath !== \"string\" || typeof savedCwd !== \"string\") return null;\n try {\n accessSync(savedBunPath, constants.X_OK);\n if (!statSync(savedCwd).isDirectory()) return null;\n if (spawnSync(savedBunPath, [\"--version\"], {\n stdio: \"ignore\",\n env: savedEnv,\n timeout: pm2CommandTimeoutMs(savedEnv),\n killSignal: \"SIGKILL\",\n }).status !== 0) return null;\n } catch {\n return null;\n }\n const killTimeout = processInfo?.pm2_env?.kill_timeout ?? processInfo?.kill_timeout;\n return {\n gatewayEntry,\n bunPath: savedBunPath,\n cwd: resolve(savedCwd),\n env: savedEnv,\n killTimeoutMs: Number.isInteger(killTimeout) && killTimeout! >= 5000\n ? killTimeout\n : undefined,\n pm2KillTimeoutMs: Number.isInteger(killTimeout) ? killTimeout : PM2_DEFAULT_KILL_TIMEOUT_MS,\n };\n}\n\nexport function hasRestorableSavedGatewayRuntime(processInfo: Pm2Process | undefined): boolean {\n return gatewayRuntimeFromProcess(processInfo) !== null;\n}\n\nexport function currentGatewayRuntime(gatewayEntry = resolveGatewayEntry()): GatewayRuntime {\n return {\n gatewayEntry: resolve(gatewayEntry),\n bunPath: resolve(findBunPath()),\n cwd: process.cwd(),\n env: { ...process.env },\n };\n}\n\nexport function refreshGatewayExecutionEnvironment(\n runtime: GatewayRuntime,\n gatewayEntry: string,\n): GatewayRuntime {\n const env = { ...process.env };\n\n // The explicit install/upgrade command is the point where users expect a\n // Gateway to pick up the same OpenCode/provider environment as their shell.\n // Keep daemon identity and SuperTask scope pinned to the proven old runtime;\n // everything else (including OPENCODE_*, XDG_* and provider credentials)\n // comes from the invoking environment.\n for (const key of new Set([\n ...Object.keys(runtime.env).filter((name) => name.startsWith(\"SUPERTASK_\")),\n ...Object.keys(env).filter((name) => name.startsWith(\"SUPERTASK_\")),\n \"HOME\",\n \"PATH\",\n \"PM2_HOME\",\n ])) {\n const value = runtime.env[key];\n if (value === undefined) delete env[key];\n else env[key] = value;\n }\n\n return {\n ...runtime,\n gatewayEntry: resolve(gatewayEntry),\n env,\n };\n}\n\nfunction queryGatewayLock<T>(\n path: string,\n query: (database: Database) => T,\n fallback: T,\n): T {\n if (!existsSync(path)) return fallback;\n let database: Database | null = null;\n try {\n database = new Database(path, { readonly: true });\n return query(database);\n } catch {\n return fallback;\n } finally {\n database?.close();\n }\n}\n\nexport function isGatewayReady(expectedPid?: number, path = databasePath()): boolean {\n return queryGatewayLock(path, (database) => {\n const row = database.query(\n \"SELECT pid, heartbeat_at, ready_at FROM gateway_lock WHERE id = 1\",\n ).get() as { pid: number; heartbeat_at: number; ready_at: number | null } | null;\n if (!row || row.ready_at == null) return false;\n if (expectedPid !== undefined && row.pid !== expectedPid) return false;\n const ageMs = Date.now() - row.heartbeat_at;\n return ageMs >= -5000 && ageMs < GATEWAY_LOCK_STALE_MS;\n }, false);\n}\n\nexport function gatewayVersionFromLock(expectedPid: number, path: string): string | null | undefined {\n return queryGatewayLock(path, (database) => {\n const row = database.query(\n \"SELECT pid, version FROM gateway_lock WHERE id = 1\",\n ).get() as { pid: number; version: string | null } | null;\n if (!row || row.pid !== expectedPid) return undefined;\n return row.version;\n }, undefined);\n}\n\nfunction readyTimeoutMs(env: NodeJS.ProcessEnv = process.env): number {\n const value = Number(env.SUPERTASK_GATEWAY_READY_TIMEOUT_MS ?? 30_000);\n return Number.isFinite(value) && value > 0 ? value : 30_000;\n}\n\nexport function waitForGatewayReady(\n pid: number,\n path = databasePath(),\n env: NodeJS.ProcessEnv = process.env,\n): boolean {\n const deadline = Date.now() + readyTimeoutMs(env);\n const sleeper = new Int32Array(new SharedArrayBuffer(4));\n while (Date.now() < deadline) {\n if (isGatewayReady(pid, path)) return true;\n Atomics.wait(sleeper, 0, 0, 100);\n }\n return isGatewayReady(pid, path);\n}\n","import { spawnSync } from \"child_process\";\nimport { existsSync, readFileSync } from \"fs\";\nimport { join, resolve } from \"path\";\nimport { Database } from \"bun:sqlite\";\nimport { loadConfig } from \"../gateway/config\";\nimport { ManagementLockBusyError, withExclusiveManagementLock } from \"./management-lock\";\nimport {\n PROCESS_NAME,\n gatewayRuntimeFromProcess,\n isPm2Installed,\n launchAgentPath,\n plistValue,\n pm2CommandTimeoutMs,\n pm2Exec,\n pm2JsonList,\n requirePm2,\n resolveRuntimeExecutable,\n runtimeHome,\n runtimePath,\n type GatewayRuntime,\n type OpenCodeRuntimeDiagnostic,\n type Pm2Process,\n type RuntimeScope,\n} from \"./pm2-cli\";\n\nexport function canonicalManagementLockPath(\n env: NodeJS.ProcessEnv = process.env,\n cwd = process.cwd(),\n): string {\n const home = runtimeHome(env);\n const pm2Home = env.PM2_HOME\n ? runtimePath(env.PM2_HOME, cwd)\n : join(home, \".pm2\");\n return join(pm2Home, \"supertask-gateway.manage.sqlite\");\n}\n\nexport function managementLockPath(\n env: NodeJS.ProcessEnv = process.env,\n cwd = process.cwd(),\n): string {\n const override = env.SUPERTASK_PM2_MANAGEMENT_LOCK;\n if (override) return runtimePath(override, cwd);\n return join(runtimeScope({ env, cwd }).pm2Home, \"supertask-gateway.manage.sqlite\");\n}\n\nexport function runtimeScope(runtime: Pick<GatewayRuntime, \"cwd\" | \"env\">): RuntimeScope {\n const { cwd, env } = runtime;\n const home = runtimeHome(env);\n return {\n cwd: resolve(cwd),\n databasePath: env.SUPERTASK_DB_PATH\n ? runtimePath(env.SUPERTASK_DB_PATH, cwd)\n : join(home, \".local/share/opencode/tasks.db\"),\n configPath: env.SUPERTASK_CONFIG_PATH\n ? runtimePath(env.SUPERTASK_CONFIG_PATH, cwd)\n : join(home, \".config/opencode/supertask.json\"),\n opencodePath: resolveRuntimeExecutable(env.SUPERTASK_OPENCODE_BIN ?? \"opencode\", env, cwd),\n home,\n pm2Home: env.PM2_HOME\n ? runtimePath(env.PM2_HOME, cwd)\n : join(home, \".pm2\"),\n managementLockPath: canonicalManagementLockPath(env, cwd),\n };\n}\n\nexport function scopesMatch(left: RuntimeScope, right: RuntimeScope): boolean {\n return left.databasePath === right.databasePath\n && left.configPath === right.configPath\n && left.opencodePath === right.opencodePath\n && left.home === right.home\n && left.pm2Home === right.pm2Home\n && left.managementLockPath === right.managementLockPath;\n}\n\nexport function currentScope(): RuntimeScope {\n return runtimeScope({ cwd: process.cwd(), env: process.env });\n}\n\nexport function diagnoseOpenCodeRuntime(\n runtime: Pick<GatewayRuntime, \"cwd\" | \"env\"> = {\n cwd: process.cwd(),\n env: process.env,\n },\n): OpenCodeRuntimeDiagnostic {\n const executable = runtimeScope(runtime).opencodePath;\n const result = spawnSync(executable, [\"--version\"], {\n cwd: runtime.cwd,\n env: runtime.env,\n encoding: \"utf8\",\n timeout: 10_000,\n killSignal: \"SIGKILL\",\n });\n const ok = result.status === 0 && result.error === undefined;\n return {\n ok,\n executable,\n version: ok ? result.stdout.trim() || result.stderr.trim() || null : null,\n error: ok\n ? null\n : result.error?.message\n || result.stderr.trim()\n || result.stdout.trim()\n || `exit code ${result.status}`,\n };\n}\n\nexport function assertOpenCodeRuntime(runtime: GatewayRuntime): void {\n const diagnostic = diagnoseOpenCodeRuntime(runtime);\n if (!diagnostic.ok) {\n throw new Error(\n `[supertask] 目标 Gateway 环境无法执行 OpenCode (${diagnostic.executable}): ${diagnostic.error}`,\n );\n }\n}\n\nexport function pm2MaxMemoryRestart(env: NodeJS.ProcessEnv = process.env): string {\n const value = env.SUPERTASK_PM2_MAX_MEMORY ?? \"512M\";\n if (!/^\\d+(?:K|M|G)$/i.test(value)) {\n throw new Error(\"[supertask] SUPERTASK_PM2_MAX_MEMORY 必须使用 512M / 1G 这类格式\");\n }\n return value;\n}\n\nexport function gatewayKillTimeoutMs(runtime: GatewayRuntime): number {\n const shutdownGracePeriodMs = loadConfig(runtimeScope(runtime).configPath).worker.shutdownGracePeriodMs;\n const minimumKillTimeoutMs = shutdownGracePeriodMs + 15_000;\n const configuredValue = runtime.env.SUPERTASK_PM2_KILL_TIMEOUT_MS;\n if (configuredValue !== undefined) {\n const configuredKillTimeout = Number(configuredValue);\n if (!Number.isInteger(configuredKillTimeout) || configuredKillTimeout < minimumKillTimeoutMs) {\n throw new Error(\n `[supertask] SUPERTASK_PM2_KILL_TIMEOUT_MS 必须是至少 ${minimumKillTimeoutMs} 的整数`\n + `(worker shutdown grace ${shutdownGracePeriodMs}ms + 15000ms 收尾余量)`,\n );\n }\n return configuredKillTimeout;\n }\n return Math.max(runtime.killTimeoutMs ?? 0, minimumKillTimeoutMs);\n}\n\nexport function gatewayTerminationCommandTimeoutMs(runtime: GatewayRuntime): number {\n const effectiveKillTimeoutMs = Math.max(\n runtime.killTimeoutMs ?? 0,\n gatewayKillTimeoutMs(runtime),\n );\n const minimumCommandTimeoutMs = effectiveKillTimeoutMs + 5_000;\n const configuredValue = runtime.env.SUPERTASK_PM2_COMMAND_TIMEOUT_MS;\n if (configuredValue !== undefined) {\n const configuredTimeoutMs = Number(configuredValue);\n if (!Number.isInteger(configuredTimeoutMs) || configuredTimeoutMs < minimumCommandTimeoutMs) {\n throw new Error(\n `[supertask] SUPERTASK_PM2_COMMAND_TIMEOUT_MS 必须是至少 ${minimumCommandTimeoutMs} 的整数`\n + `(Gateway kill timeout ${effectiveKillTimeoutMs}ms + 5000ms PM2 收尾余量)`,\n );\n }\n return configuredTimeoutMs;\n }\n return Math.max(pm2CommandTimeoutMs(runtime.env), minimumCommandTimeoutMs);\n}\n\nfunction runningWorkCount(path: string): number {\n if (!existsSync(path)) return 0;\n let database: Database | null = null;\n try {\n database = new Database(path, { readonly: true });\n const tables = database.query(\n \"SELECT COUNT(*) AS count FROM sqlite_master WHERE type = 'table' AND name IN ('tasks', 'task_runs')\",\n ).get() as { count: number } | null;\n if (Number(tables?.count ?? 0) < 2) return 0;\n const row = database.query(\n \"SELECT (SELECT COUNT(*) FROM tasks WHERE status = 'running') + (SELECT COUNT(*) FROM task_runs WHERE status = 'running') AS count\",\n ).get() as { count: number } | null;\n return Number(row?.count ?? 0);\n } finally {\n database?.close();\n }\n}\n\n/**\n * PM2 用进程自身保存的 kill_timeout 执行 stop/delete,命令侧超时无法延长它。若该值短于\n * shutdown grace + 15s 且仍有运行中任务,PM2 会在优雅停机中途 SIGKILL,run 只能进入隔离;\n * 此时在终止前失败关闭。没有运行中任务时停机很快,允许继续以免旧安装永远无法升级。\n */\nexport function assertPm2KillTimeoutCoversShutdown(runtime: GatewayRuntime): void {\n if (runtime.pm2KillTimeoutMs === undefined) return;\n const scope = runtimeScope(runtime);\n const requiredMs = loadConfig(scope.configPath).worker.shutdownGracePeriodMs + 15_000;\n if (runtime.pm2KillTimeoutMs >= requiredMs) return;\n const running = runningWorkCount(scope.databasePath);\n if (running === 0) return;\n throw new Error(\n `[supertask] PM2 Gateway 的 kill_timeout 为 ${runtime.pm2KillTimeoutMs}ms,低于 shutdown grace + 15000ms(${requiredMs}ms),`\n + `且仍有 ${running} 个运行中任务/执行记录;现在停止会在优雅停机中途被强制终止。请等待任务完成后重试`,\n );\n}\n\nexport function requirePm2Termination(\n command: \"stop\" | \"delete\",\n action: string,\n runtime: GatewayRuntime,\n): string {\n assertPm2KillTimeoutCoversShutdown(runtime);\n return requirePm2([command, PROCESS_NAME], action, {\n env: runtime.env,\n timeoutMs: gatewayTerminationCommandTimeoutMs(runtime),\n });\n}\n\nexport function assertRuntimeCanControlPm2(runtime: GatewayRuntime | null, existing?: Pm2Process): void {\n if (!existing) return;\n if (!runtime) {\n throw new Error(\n \"[supertask] 无法完整验证已有 Gateway 的入口、Bun 和 cwd,已拒绝删除现有进程\",\n );\n }\n const probe = pm2Exec([\"--version\"], { env: runtime.env });\n if (!probe.ok) {\n throw new Error(\n `[supertask] 保存的 Gateway 运行环境无法执行 pm2,已拒绝删除现有进程;请先修复 PATH 或 SUPERTASK_PM2_BIN: ${probe.output || \"pm2 unavailable\"}`,\n );\n }\n const observed = pm2JsonList(runtime.env).find((item) => item.name === PROCESS_NAME);\n const observedRuntime = gatewayRuntimeFromProcess(observed);\n if (\n !observed\n || observed.pid !== existing.pid\n || !observedRuntime\n || observedRuntime.gatewayEntry !== runtime.gatewayEntry\n || observedRuntime.bunPath !== runtime.bunPath\n || observedRuntime.cwd !== runtime.cwd\n ) {\n throw new Error(\"[supertask] 保存的 PM2 环境无法重现同一 Gateway 记录,已拒绝删除现有进程\");\n }\n}\n\nfunction addLegacyManagementLock(\n paths: Set<string>,\n env: Record<string, unknown> | undefined,\n cwd: string,\n): void {\n const value = env?.SUPERTASK_PM2_MANAGEMENT_LOCK;\n if (typeof value === \"string\" && value.length > 0) paths.add(runtimePath(value, cwd));\n}\n\nfunction collectLegacyLockFromProcess(paths: Set<string>, gateway: Pm2Process | undefined): void {\n const cwd = gateway?.pm2_env?.pm_cwd ?? gateway?.pm_cwd;\n if (typeof cwd === \"string\") {\n addLegacyManagementLock(paths, gateway?.pm2_env?.env ?? gateway?.env, cwd);\n }\n}\n\nfunction savedManagementLockPaths(): string[] {\n const canonical = canonicalManagementLockPath();\n const legacy = new Set<string>();\n addLegacyManagementLock(legacy, process.env, process.cwd());\n\n const pm2Home = currentScope().pm2Home;\n try {\n const dump = JSON.parse(readFileSync(join(pm2Home, \"dump.pm2\"), \"utf8\")) as unknown;\n if (Array.isArray(dump)) {\n collectLegacyLockFromProcess(\n legacy,\n (dump as Pm2Process[]).find((item) => item.name === PROCESS_NAME),\n );\n }\n } catch {}\n\n if (process.platform === \"darwin\") {\n try {\n const configured = plistValue(\n readFileSync(launchAgentPath(), \"utf8\"),\n \"SUPERTASK_PM2_MANAGEMENT_LOCK\",\n );\n if (configured) legacy.add(resolve(configured));\n } catch {}\n }\n\n if (isPm2Installed()) {\n collectLegacyLockFromProcess(\n legacy,\n pm2JsonList().find((item) => item.name === PROCESS_NAME),\n );\n }\n\n return [\n canonical,\n ...[...legacy].filter((path) => path !== canonical).sort(),\n ];\n}\n\nfunction withManagementLocks<T>(\n paths: string[],\n timeoutMs: number,\n action: () => T,\n index = 0,\n): T {\n const path = paths[index];\n if (!path) return action();\n return withExclusiveManagementLock(\n path,\n timeoutMs,\n () => withManagementLocks(paths, timeoutMs, action, index + 1),\n );\n}\n\nfunction assertMacLaunchAgentPm2HomeMatchesCurrent(): void {\n if (process.platform !== \"darwin\") return;\n try {\n const configuredPm2Home = plistValue(\n readFileSync(launchAgentPath(), \"utf8\"),\n \"PM2_HOME\",\n );\n if (!configuredPm2Home) return;\n const installedPm2Home = resolve(configuredPm2Home);\n const activePm2Home = currentScope().pm2Home;\n if (installedPm2Home !== activePm2Home) {\n throw new Error(\n `[supertask] 已安装的 macOS LaunchAgent 使用 PM2_HOME=${installedPm2Home},`\n + `当前 CLI 使用 ${activePm2Home};为避免两个 PM2 daemon 同时管理 Gateway,已拒绝修改。`\n + `请使用 PM2_HOME=${installedPm2Home} 重新执行命令`,\n );\n }\n } catch (error) {\n if (error instanceof Error && error.message.startsWith(\"[supertask] 已安装的 macOS LaunchAgent\")) {\n throw error;\n }\n if ((error as NodeJS.ErrnoException).code !== \"ENOENT\") throw error;\n }\n}\n\nexport function withManagementLock<T>(action: () => T): T {\n const paths = savedManagementLockPaths();\n const configuredTimeout = Number(process.env.SUPERTASK_PM2_MANAGEMENT_LOCK_TIMEOUT_MS ?? 15_000);\n const timeoutMs = Number.isFinite(configuredTimeout) && configuredTimeout > 0\n ? configuredTimeout\n : 15_000;\n try {\n return withManagementLocks(paths, timeoutMs, () => {\n assertMacLaunchAgentPm2HomeMatchesCurrent();\n return action();\n });\n } catch (error) {\n if (error instanceof ManagementLockBusyError) {\n throw new Error(\"[supertask] 另一个 Gateway 管理操作仍在进行,已拒绝并发修改 PM2 状态\");\n }\n throw error;\n }\n}\n","import { Database } from 'bun:sqlite';\nimport { mkdirSync } from 'fs';\nimport { dirname } from 'path';\n\nexport class ManagementLockBusyError extends Error {\n constructor() {\n super('Gateway management lock is busy');\n this.name = 'ManagementLockBusyError';\n }\n}\n\nfunction isBusyError(error: unknown): boolean {\n if (!(error instanceof Error)) return false;\n const code = (error as Error & { code?: string }).code;\n return code === 'SQLITE_BUSY' || /database is locked/i.test(error.message);\n}\n\n/**\n * Serializes PM2 lifecycle changes with an OS-backed SQLite write lock.\n * The transaction is held for the complete action and is released by SQLite\n * automatically if the owning process exits or is killed.\n */\nexport function withExclusiveManagementLock<T>(\n path: string,\n timeoutMs: number,\n action: () => T,\n): T {\n mkdirSync(dirname(path), { recursive: true });\n const database = new Database(path, { create: true });\n const normalizedTimeout = Number.isFinite(timeoutMs) && timeoutMs >= 0\n ? Math.floor(timeoutMs)\n : 0;\n database.exec(`PRAGMA busy_timeout = ${normalizedTimeout}`);\n\n try {\n try {\n database.exec('BEGIN IMMEDIATE');\n } catch (error) {\n if (isBusyError(error)) throw new ManagementLockBusyError();\n throw error;\n }\n\n try {\n const result = action();\n database.exec('COMMIT');\n return result;\n } catch (error) {\n try {\n database.exec('ROLLBACK');\n } catch {}\n throw error;\n }\n } finally {\n database.close();\n }\n}\n","import { spawnSync } from \"child_process\";\nimport {\n accessSync,\n chmodSync,\n constants,\n existsSync,\n mkdirSync,\n readFileSync,\n rmSync,\n writeFileSync,\n} from \"fs\";\nimport { userInfo } from \"os\";\nimport { dirname, join, resolve } from \"path\";\nimport { fileURLToPath } from \"url\";\nimport {\n MAC_LAUNCH_AGENT_LABEL,\n PROCESS_NAME,\n currentGatewayRuntime,\n findBunPath,\n gatewayRuntimeFromProcess,\n hasRestorableSavedGatewayRuntime,\n launchAgentPath,\n launchctlBin,\n plistValue,\n pm2CommandTimeoutMs,\n resolvePm2Bin,\n runtimeHome,\n systemctlBin,\n xmlEscape,\n xmlUnescape,\n type GatewayRuntime,\n type Pm2Process,\n} from \"./pm2-cli\";\nimport {\n currentScope,\n managementLockPath,\n runtimeScope,\n scopesMatch,\n} from \"./pm2-scope\";\n\nconst __dirname = dirname(fileURLToPath(import.meta.url));\n\nexport function resolvePm2SupervisorEntry(baseDir = __dirname): string {\n const override = process.env.SUPERTASK_PM2_SUPERVISOR_ENTRY;\n if (override) {\n if (!existsSync(override)) throw new Error(`[supertask] PM2 supervisor entry not found: ${override}`);\n return resolve(override);\n }\n const candidates = [\n join(baseDir, \"pm2-supervisor.js\"),\n join(baseDir, \"pm2-supervisor.ts\"),\n join(baseDir, \"../daemon/pm2-supervisor.js\"),\n join(baseDir, \"../daemon/pm2-supervisor.ts\"),\n ];\n const entry = candidates.find((candidate) => existsSync(candidate));\n if (!entry) throw new Error(`[supertask] PM2 supervisor entry not found. Checked: ${candidates.join(\", \")}`);\n return resolve(entry);\n}\n\nfunction readRestorableDumpGatewayRuntime(pm2Home: string): GatewayRuntime | null {\n const dump = JSON.parse(readFileSync(join(pm2Home, \"dump.pm2\"), \"utf8\")) as unknown;\n if (!Array.isArray(dump)) return null;\n const gateway = (dump as Pm2Process[]).find((item) => item.name === PROCESS_NAME);\n const runtime = gatewayRuntimeFromProcess(gateway);\n return runtime && hasRestorableSavedGatewayRuntime(gateway) ? runtime : null;\n}\n\nexport function isMacLaunchAgentConfigured(\n expectedPm2Home?: string,\n expectedRuntime?: GatewayRuntime,\n): boolean {\n if (typeof process.getuid !== \"function\") return false;\n const plistPath = launchAgentPath();\n if (!existsSync(plistPath)) return false;\n\n try {\n const contents = readFileSync(plistPath, \"utf8\");\n const argumentsBlock = contents.match(\n /<key>\\s*ProgramArguments\\s*<\\/key>\\s*<array>([\\s\\S]*?)<\\/array>/,\n )?.[1];\n const programArguments = argumentsBlock\n ? [...argumentsBlock.matchAll(/<string>([^<]*)<\\/string>/g)].map((match) => xmlUnescape(match[1]))\n : [];\n const bunPath = programArguments[0];\n const supervisorEntry = programArguments[1];\n const pm2Path = programArguments[2];\n const pm2Home = plistValue(contents, \"PM2_HOME\");\n const managementLock = plistValue(contents, \"SUPERTASK_PM2_MANAGEMENT_LOCK\");\n if (!bunPath || !supervisorEntry || !pm2Path || !pm2Home || !managementLock) return false;\n if (expectedPm2Home && resolve(pm2Home) !== resolve(expectedPm2Home)) return false;\n const expectedManagementLock = expectedRuntime\n ? managementLockPath(expectedRuntime.env, expectedRuntime.cwd)\n : process.env.SUPERTASK_PM2_MANAGEMENT_LOCK\n ? managementLockPath()\n : join(expectedPm2Home ?? currentScope().pm2Home, \"supertask-gateway.manage.sqlite\");\n if (managementLock !== expectedManagementLock) return false;\n\n accessSync(bunPath, constants.X_OK);\n accessSync(supervisorEntry, constants.R_OK);\n accessSync(pm2Path, constants.X_OK);\n if (spawnSync(bunPath, [\"--version\"], {\n stdio: \"ignore\",\n timeout: pm2CommandTimeoutMs(),\n killSignal: \"SIGKILL\",\n }).status !== 0) return false;\n if (spawnSync(pm2Path, [\"--version\"], {\n stdio: \"ignore\",\n env: { ...process.env, PM2_HOME: pm2Home },\n timeout: pm2CommandTimeoutMs(),\n killSignal: \"SIGKILL\",\n }).status !== 0) return false;\n\n const loaded = spawnSync(\n launchctlBin(),\n [\"print\", `gui/${process.getuid()}/${MAC_LAUNCH_AGENT_LABEL}`],\n {\n encoding: \"utf8\",\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: pm2CommandTimeoutMs(),\n killSignal: \"SIGKILL\",\n },\n );\n if (loaded.status !== 0) return false;\n if (!loaded.stdout.includes(\"state = running\")) return false;\n if (!loaded.stdout.includes(`path = ${plistPath}`)) return false;\n if (!loaded.stdout.includes(`program = ${bunPath}`)) return false;\n\n const dumpRuntime = readRestorableDumpGatewayRuntime(pm2Home);\n if (!dumpRuntime) return false;\n return expectedRuntime === undefined || (\n dumpRuntime.gatewayEntry === expectedRuntime.gatewayEntry\n && dumpRuntime.bunPath === expectedRuntime.bunPath\n && dumpRuntime.cwd === expectedRuntime.cwd\n && scopesMatch(runtimeScope(dumpRuntime), runtimeScope(expectedRuntime))\n );\n } catch {\n return false;\n }\n}\n\nfunction bootstrapMacLaunchAgent(domain: string, path: string) {\n const retryDeadline = Date.now() + 2_000;\n const sleeper = new Int32Array(new SharedArrayBuffer(4));\n let result = spawnSync(launchctlBin(), [\"bootstrap\", domain, path], {\n encoding: \"utf8\",\n timeout: pm2CommandTimeoutMs(),\n killSignal: \"SIGKILL\",\n });\n\n while (result.status !== 0 && Date.now() < retryDeadline) {\n const output = `${result.stdout ?? \"\"}${result.stderr ?? \"\"}`;\n if (result.status !== 5 && !output.includes(\"Bootstrap failed: 5:\")) break;\n Atomics.wait(sleeper, 0, 0, 100);\n result = spawnSync(launchctlBin(), [\"bootstrap\", domain, path], {\n encoding: \"utf8\",\n timeout: pm2CommandTimeoutMs(),\n killSignal: \"SIGKILL\",\n });\n }\n\n return result;\n}\n\nexport function installMacLaunchAgent(expectedRuntime = currentGatewayRuntime()): string {\n if (typeof process.getuid !== \"function\") {\n throw new Error(\"[supertask] 当前运行时无法获取 macOS 用户 ID\");\n }\n\n const path = launchAgentPath();\n const home = runtimeHome(expectedRuntime.env);\n const pm2Home = runtimeScope(expectedRuntime).pm2Home;\n const managementLock = managementLockPath(expectedRuntime.env, expectedRuntime.cwd);\n const environmentPath = expectedRuntime.env.PATH\n ?? \"/opt/homebrew/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin\";\n const bunPath = findBunPath();\n const supervisorEntry = resolvePm2SupervisorEntry();\n const pm2Path = resolvePm2Bin();\n const plist = `<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<!DOCTYPE plist PUBLIC \"-//Apple//DTD PLIST 1.0//EN\" \"http://www.apple.com/DTDs/PropertyList-1.0.dtd\">\n<plist version=\"1.0\">\n <dict>\n <key>Label</key>\n <string>${MAC_LAUNCH_AGENT_LABEL}</string>\n <key>ProgramArguments</key>\n <array>\n <string>${xmlEscape(bunPath)}</string>\n <string>${xmlEscape(supervisorEntry)}</string>\n <string>${xmlEscape(pm2Path)}</string>\n </array>\n <key>RunAtLoad</key>\n <true/>\n <key>KeepAlive</key>\n <true/>\n <key>ThrottleInterval</key>\n <integer>10</integer>\n <key>EnvironmentVariables</key>\n <dict>\n <key>HOME</key>\n <string>${xmlEscape(home)}</string>\n <key>PATH</key>\n <string>${xmlEscape(environmentPath)}</string>\n <key>PM2_HOME</key>\n <string>${xmlEscape(pm2Home)}</string>\n <key>SUPERTASK_PM2_MANAGEMENT_LOCK</key>\n <string>${xmlEscape(managementLock)}</string>\n </dict>\n <key>StandardErrorPath</key>\n <string>${xmlEscape(join(pm2Home, \"supertask-launchd-error.log\"))}</string>\n <key>StandardOutPath</key>\n <string>${xmlEscape(join(pm2Home, \"supertask-launchd-output.log\"))}</string>\n </dict>\n</plist>\n`;\n const domain = `gui/${process.getuid()}`;\n const previousPlist = existsSync(path) ? readFileSync(path) : null;\n const wasLoaded = previousPlist != null && spawnSync(\n launchctlBin(),\n [\"print\", `${domain}/${MAC_LAUNCH_AGENT_LABEL}`],\n {\n stdio: \"ignore\",\n timeout: pm2CommandTimeoutMs(),\n killSignal: \"SIGKILL\",\n },\n ).status === 0;\n\n mkdirSync(dirname(path), { recursive: true });\n writeFileSync(path, plist, { mode: 0o600 });\n chmodSync(path, 0o600);\n\n spawnSync(launchctlBin(), [\"bootout\", `${domain}/${MAC_LAUNCH_AGENT_LABEL}`], {\n stdio: \"ignore\",\n timeout: pm2CommandTimeoutMs(),\n killSignal: \"SIGKILL\",\n });\n const loaded = bootstrapMacLaunchAgent(domain, path);\n const configuredVerifyTimeout = Number(process.env.SUPERTASK_LAUNCH_AGENT_VERIFY_TIMEOUT_MS ?? 2_000);\n const verifyTimeoutMs = Number.isFinite(configuredVerifyTimeout) && configuredVerifyTimeout > 0\n ? configuredVerifyTimeout\n : 2_000;\n const verifyDeadline = Date.now() + verifyTimeoutMs;\n const sleeper = new Int32Array(new SharedArrayBuffer(4));\n let verified = loaded.status === 0 && isMacLaunchAgentConfigured(pm2Home, expectedRuntime);\n while (loaded.status === 0 && !verified && Date.now() < verifyDeadline) {\n Atomics.wait(sleeper, 0, 0, 100);\n verified = isMacLaunchAgentConfigured(pm2Home, expectedRuntime);\n }\n if (loaded.status !== 0 || !verified) {\n const output = loaded.status === 0\n ? \"supervisor 未保持 running 或 PM2 dump 不可恢复\"\n : `${loaded.stdout ?? \"\"}${loaded.stderr ?? \"\"}`.trim();\n if (loaded.status === 0) {\n spawnSync(launchctlBin(), [\"bootout\", `${domain}/${MAC_LAUNCH_AGENT_LABEL}`], {\n stdio: \"ignore\",\n timeout: pm2CommandTimeoutMs(),\n killSignal: \"SIGKILL\",\n });\n }\n if (previousPlist == null) rmSync(path, { force: true });\n else {\n writeFileSync(path, previousPlist, { mode: 0o600 });\n chmodSync(path, 0o600);\n }\n\n let rollbackFailure = \"\";\n if (wasLoaded && previousPlist != null) {\n const restored = bootstrapMacLaunchAgent(domain, path);\n if (restored.status !== 0) {\n rollbackFailure = `;旧 LaunchAgent 恢复失败: ${`${restored.stdout ?? \"\"}${restored.stderr ?? \"\"}`.trim() || `退出码 ${restored.status}`}`;\n }\n }\n throw new Error(`[supertask] macOS LaunchAgent 加载失败: ${output || `退出码 ${loaded.status}`}${rollbackFailure}`);\n }\n return path;\n}\n\nexport function removeMacLaunchAgent(): void {\n if (typeof process.getuid !== \"function\") return;\n const path = launchAgentPath();\n const domain = `gui/${process.getuid()}`;\n const loaded = spawnSync(\n launchctlBin(),\n [\"print\", `${domain}/${MAC_LAUNCH_AGENT_LABEL}`],\n {\n stdio: \"ignore\",\n timeout: pm2CommandTimeoutMs(),\n killSignal: \"SIGKILL\",\n },\n );\n if (loaded.error) {\n throw new Error(`[supertask] 无法确认 macOS LaunchAgent 状态: ${loaded.error.message}`);\n }\n if (loaded.status === 0) {\n const removed = spawnSync(\n launchctlBin(),\n [\"bootout\", `${domain}/${MAC_LAUNCH_AGENT_LABEL}`],\n {\n encoding: \"utf8\",\n timeout: pm2CommandTimeoutMs(),\n killSignal: \"SIGKILL\",\n },\n );\n if (removed.status !== 0 || removed.error) {\n const output = `${removed.stdout ?? \"\"}${removed.stderr ?? \"\"}`.trim();\n throw new Error(\n `[supertask] Gateway 已从 PM2 与 dump 中移除,但 macOS LaunchAgent 停止失败: `\n + (output || removed.error?.message || `退出码 ${removed.status}`),\n );\n }\n }\n rmSync(path, { force: true });\n}\n\nexport function systemdUnitMatchesPm2Home(unitContent: string, expectedPm2Home: string): boolean {\n const normalizedExpected = resolve(expectedPm2Home);\n const envAssignPattern = /(?<![A-Za-z0-9_])PM2_HOME=(?:\"([^\"\\r\\n]+)\"|'([^'\\r\\n]+)'|([^\\s\"']+))/g;\n let match: RegExpExecArray | null;\n while ((match = envAssignPattern.exec(unitContent)) !== null) {\n const rawValue = (match[1] ?? match[2] ?? match[3] ?? \"\").trim();\n if (rawValue && resolve(rawValue) === normalizedExpected) {\n return true;\n }\n }\n return false;\n}\n\nexport function isLinuxStartupConfigured(\n env: NodeJS.ProcessEnv = process.env,\n cwd = process.cwd(),\n expectedRuntime?: GatewayRuntime,\n): boolean {\n const unit = env.SUPERTASK_PM2_SYSTEMD_UNIT ?? `pm2-${userInfo().username}.service`;\n const enabled = spawnSync(systemctlBin(env), [\"is-enabled\", unit], {\n encoding: \"utf8\",\n env,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: pm2CommandTimeoutMs(env),\n killSignal: \"SIGKILL\",\n });\n if (enabled.status !== 0 || enabled.stdout.trim() !== \"enabled\") return false;\n\n const contents = spawnSync(systemctlBin(env), [\"cat\", unit], {\n encoding: \"utf8\",\n env,\n stdio: [\"ignore\", \"pipe\", \"ignore\"],\n timeout: pm2CommandTimeoutMs(env),\n killSignal: \"SIGKILL\",\n });\n if (contents.status !== 0) return false;\n const expectedPm2Home = runtimeScope({ cwd, env }).pm2Home;\n if (!contents.stdout.includes(\"resurrect\") || !systemdUnitMatchesPm2Home(contents.stdout, expectedPm2Home)) {\n return false;\n }\n try {\n const runtime = readRestorableDumpGatewayRuntime(expectedPm2Home);\n if (!runtime) return false;\n return runtime.cwd === resolve(cwd)\n && scopesMatch(runtimeScope(runtime), runtimeScope({ cwd, env }))\n && (expectedRuntime === undefined || (\n runtime.gatewayEntry === expectedRuntime.gatewayEntry\n && runtime.bunPath === expectedRuntime.bunPath\n ));\n } catch {\n return false;\n }\n}\n","import { accessSync, constants, statSync } from \"fs\";\nimport { resolve } from \"path\";\nimport { getPackageVersion } from \"../core/package-version\";\nimport {\n PROCESS_NAME,\n currentGatewayRuntime,\n databasePath,\n ensurePm2LogRotation,\n gatewayRuntimeFromProcess,\n gatewayVersionFromLock,\n getRunningVersion,\n installPm2,\n isGatewayReady,\n isPm2Installed,\n packageVersionFromGatewayEntry,\n pm2Exec,\n pm2JsonList,\n refreshGatewayExecutionEnvironment,\n requirePm2,\n resolveGatewayEntry,\n savePm2State,\n waitForGatewayReady,\n writeRunningVersion,\n type EnsureGatewayResult,\n type GatewayDiagnostic,\n type GatewayMaintenanceResult,\n type GatewayMaintenanceState,\n type GatewayMaintenanceWorkGuard,\n type GatewayRuntime,\n type Pm2Process,\n} from \"./pm2-cli\";\nimport {\n assertOpenCodeRuntime,\n assertPm2KillTimeoutCoversShutdown,\n assertRuntimeCanControlPm2,\n currentScope,\n diagnoseOpenCodeRuntime,\n gatewayKillTimeoutMs,\n gatewayTerminationCommandTimeoutMs,\n pm2MaxMemoryRestart,\n requirePm2Termination,\n runtimeScope,\n scopesMatch,\n withManagementLock,\n} from \"./pm2-scope\";\nimport {\n installMacLaunchAgent,\n isLinuxStartupConfigured,\n isMacLaunchAgentConfigured,\n removeMacLaunchAgent,\n} from \"./pm2-startup\";\n\nexport function getGatewayDiagnostic(options: { probeOpenCode?: boolean } = {}): GatewayDiagnostic {\n const producerScope = currentScope();\n if (!isPm2Installed()) {\n return {\n pm2Installed: false,\n processFound: false,\n status: null,\n pid: null,\n ready: false,\n runningVersion: getRunningVersion(),\n gatewayEntry: null,\n gatewayPackageVersion: null,\n logRotationInstalled: false,\n startupConfigured: process.platform === \"darwin\" || process.platform === \"linux\" ? false : null,\n currentScope: producerScope,\n gatewayScope: null,\n scopeMatches: false,\n gatewayOpenCode: null,\n };\n }\n\n const processes = pm2JsonList();\n const gateway = processes.find((item) => item.name === PROCESS_NAME);\n const runtime = gatewayRuntimeFromProcess(gateway);\n const gatewayEnv = runtime?.env ?? process.env;\n const managedScope = runtime ? runtimeScope(runtime) : null;\n const pid = typeof gateway?.pid === \"number\" ? gateway.pid : null;\n const readyPath = managedScope?.databasePath ?? databasePath();\n const lockedVersion = pid == null ? undefined : gatewayVersionFromLock(pid, readyPath);\n const gatewayEntry = runtime?.gatewayEntry ?? null;\n return {\n pm2Installed: true,\n processFound: gateway != null,\n status: gateway?.pm2_env?.status ?? null,\n pid,\n ready: pid != null && isGatewayReady(pid, readyPath),\n runningVersion: lockedVersion === undefined\n ? getRunningVersion(gatewayEnv, runtime?.cwd)\n : lockedVersion,\n gatewayEntry,\n gatewayPackageVersion: packageVersionFromGatewayEntry(gatewayEntry),\n logRotationInstalled: processes.some((item) => (\n item.name === \"pm2-logrotate\" && item.pm2_env?.status === \"online\"\n )),\n startupConfigured: process.platform === \"darwin\"\n ? isMacLaunchAgentConfigured(\n managedScope?.pm2Home ?? producerScope.pm2Home,\n runtime ?? undefined,\n )\n : process.platform === \"linux\"\n ? isLinuxStartupConfigured(gatewayEnv, runtime?.cwd, runtime ?? undefined)\n : null,\n currentScope: producerScope,\n gatewayScope: managedScope,\n scopeMatches: managedScope != null && scopesMatch(producerScope, managedScope),\n gatewayOpenCode: runtime === null || !options.probeOpenCode\n ? null\n : diagnoseOpenCodeRuntime(runtime),\n };\n}\n\nexport function isGatewayRunning(): boolean {\n if (!isPm2Installed()) return false;\n const proc = pm2JsonList().find((item) => item.name === PROCESS_NAME);\n const runtime = gatewayRuntimeFromProcess(proc);\n return proc?.pm2_env?.status === \"online\"\n && typeof proc.pid === \"number\"\n && runtime !== null\n && isGatewayReady(proc.pid, runtimeScope(runtime).databasePath);\n}\n\nfunction pm2StartGateway(runtime = currentGatewayRuntime(), expectedVersion?: string): void {\n try {\n accessSync(runtime.bunPath, constants.X_OK);\n accessSync(runtime.gatewayEntry, constants.R_OK);\n if (!statSync(runtime.cwd).isDirectory()) throw new Error(\"cwd is not a directory\");\n } catch (error) {\n throw new Error(`[supertask] Gateway 目标运行时不可用: ${error instanceof Error ? error.message : String(error)}`);\n }\n const killTimeoutMs = gatewayKillTimeoutMs(runtime);\n requirePm2([\n \"start\",\n runtime.bunPath,\n \"--name\",\n PROCESS_NAME,\n \"--interpreter\",\n \"none\",\n \"--restart-delay\",\n \"5000\",\n \"--max-restarts\",\n \"30\",\n \"--max-memory-restart\",\n pm2MaxMemoryRestart(runtime.env),\n \"--kill-timeout\",\n String(killTimeoutMs),\n \"--cwd\",\n runtime.cwd,\n \"--\",\n runtime.gatewayEntry,\n ], \"pm2 start\", { env: runtime.env });\n const started = pm2JsonList(runtime.env).find((item) => item.name === PROCESS_NAME);\n if (started?.pm2_env?.status !== \"online\") {\n throw new Error(`[supertask] Gateway did not become online (status: ${started?.pm2_env?.status ?? \"missing\"})`);\n }\n const observedRuntime = gatewayRuntimeFromProcess(started);\n if (\n !observedRuntime\n || observedRuntime.gatewayEntry !== resolve(runtime.gatewayEntry)\n || observedRuntime.bunPath !== runtime.bunPath\n || observedRuntime.cwd !== resolve(runtime.cwd)\n || !scopesMatch(runtimeScope(observedRuntime), runtimeScope(runtime))\n ) {\n throw new Error(\"[supertask] PM2 online 记录与本次启动目标不一致,已拒绝接管\");\n }\n if (\n typeof started.pid !== \"number\"\n || !waitForGatewayReady(started.pid, runtimeScope(runtime).databasePath, runtime.env)\n ) {\n throw new Error(\"[supertask] Gateway 进程 online,但未在限定时间内就绪;请查看 pm2 logs supertask-gateway\");\n }\n // 就绪锁记录的版本必须是本次目标版本(入口指向陈旧缓存或被覆盖时会不一致);旧版 Gateway 不写版本则无法比较。\n const readyVersion = gatewayVersionFromLock(started.pid, runtimeScope(runtime).databasePath);\n if (expectedVersion !== undefined && typeof readyVersion === \"string\" && readyVersion !== expectedVersion) {\n throw new Error(`[supertask] Gateway 已就绪,但运行版本 ${readyVersion} 不是目标版本 ${expectedVersion}`);\n }\n}\n\n/**\n * 新 Gateway 启动失败后的统一回滚:清理失败进程的错误不能覆盖原始错误,也不能阻止尝试恢复旧 Gateway。\n */\nfunction rollbackFailedGatewayStart(\n error: unknown,\n targetRuntime: GatewayRuntime,\n oldRuntime: GatewayRuntime | null,\n before: string | null,\n): never {\n const message = (value: unknown) => (value instanceof Error ? value.message : String(value));\n const problems: string[] = [];\n try {\n const failed = pm2JsonList(targetRuntime.env).find((item) => item.name === PROCESS_NAME);\n if (failed) {\n requirePm2Termination(\n \"delete\",\n \"pm2 delete failed Gateway\",\n gatewayRuntimeFromProcess(failed) ?? targetRuntime,\n );\n }\n } catch (cleanupError) {\n problems.push(`清理失败的新 Gateway 失败: ${message(cleanupError)}`);\n }\n if (!oldRuntime) {\n if (problems.length === 0) throw error;\n throw new Error(`${message(error)}; ${problems.join(\"; \")}`);\n }\n try {\n pm2StartGateway(oldRuntime);\n savePm2State(oldRuntime.env);\n if (before) writeRunningVersion(before, oldRuntime.env, oldRuntime.cwd);\n } catch (rollbackError) {\n problems.push(`旧 Gateway 回滚也失败: ${message(rollbackError)}`);\n throw new Error(`${message(error)}; ${problems.join(\"; \")}`);\n }\n throw new Error(`${message(error)}; ${[...problems, \"已回滚到旧 Gateway\"].join(\"; \")}`);\n}\n\n/**\n * install / upgrade / ensureGateway 共用的受保护替换与回滚骨架:\n * 预检超时与 OpenCode → 删除旧进程 → 启动并等待新进程就绪 → 持久化 dump 与版本;失败自动回滚完整旧环境。\n */\nfunction replaceGatewayProcess(params: {\n existing: Pm2Process | undefined;\n oldRuntime: GatewayRuntime | null;\n targetRuntime: GatewayRuntime;\n version: string;\n before: string | null;\n deleteAction: string;\n controlAlreadyVerified?: boolean;\n}): void {\n const { existing, oldRuntime, targetRuntime, version, before, deleteAction } = params;\n if (!params.controlAlreadyVerified) assertRuntimeCanControlPm2(oldRuntime, existing);\n gatewayKillTimeoutMs(targetRuntime);\n gatewayTerminationCommandTimeoutMs(targetRuntime);\n assertOpenCodeRuntime(targetRuntime);\n if (existing) requirePm2Termination(\"delete\", deleteAction, oldRuntime!);\n\n try {\n pm2StartGateway(targetRuntime, version);\n savePm2State(targetRuntime.env);\n writeRunningVersion(version, targetRuntime.env, targetRuntime.cwd);\n } catch (error) {\n rollbackFailedGatewayStart(error, targetRuntime, oldRuntime, before);\n }\n}\n\nexport function stopGatewayForMaintenance(): GatewayMaintenanceState {\n if (!isPm2Installed()) return { wasRunning: false };\n\n const proc = pm2JsonList().find((item) => item.name === PROCESS_NAME);\n const runtime = gatewayRuntimeFromProcess(proc);\n const managedCurrentDatabase = proc?.pm2_env?.status === \"online\"\n && typeof proc.pid === \"number\"\n && runtime !== null\n && scopesMatch(currentScope(), runtimeScope(runtime))\n && isGatewayReady(proc.pid, runtimeScope(runtime).databasePath);\n if (!managedCurrentDatabase) return { wasRunning: false };\n\n assertRuntimeCanControlPm2(runtime, proc);\n assertPm2KillTimeoutCoversShutdown(runtime);\n const state: GatewayMaintenanceState = { wasRunning: true, env: runtime.env, cwd: runtime.cwd };\n try {\n requirePm2Termination(\"stop\", \"pm2 stop Gateway for database maintenance\", runtime);\n } catch (error) {\n // PM2 可能已开始停止 Gateway 后 CLI 才超时或失败;维护尚未开始,按“失败也恢复原状态”尝试恢复。\n try {\n restartGatewayAfterMaintenance(state);\n } catch (restartError) {\n const original = error instanceof Error ? error.message : String(error);\n const restart = restartError instanceof Error ? restartError.message : String(restartError);\n throw new Error(`${original};Gateway 自动恢复也失败:${restart}`);\n }\n throw error;\n }\n return state;\n}\n\nexport function restartGatewayAfterMaintenance(state: GatewayMaintenanceState): boolean {\n if (!state.wasRunning) return false;\n\n const env = state.env ?? process.env;\n const cwd = state.cwd ?? process.cwd();\n requirePm2([\"start\", PROCESS_NAME], \"pm2 restart Gateway after database maintenance\", { env });\n const started = pm2JsonList(env).find((item) => item.name === PROCESS_NAME);\n if (started?.pm2_env?.status !== \"online\") {\n throw new Error(\n `[supertask] Gateway 数据库维护后未恢复 online(状态:${started?.pm2_env?.status ?? \"missing\"})`,\n );\n }\n if (typeof started.pid !== \"number\" || !waitForGatewayReady(started.pid, databasePath(env, cwd), env)) {\n throw new Error(\"[supertask] Gateway 数据库维护后已 online,但未在限定时间内就绪;请查看 pm2 logs supertask-gateway\");\n }\n return true;\n}\n\nexport function withGatewayMaintenance<T>(\n keepStopped: boolean,\n operation: () => T,\n guard?: GatewayMaintenanceWorkGuard,\n): GatewayMaintenanceResult<T> {\n return withManagementLock(() => {\n const baseline = guard?.assertIdleBeforeStop();\n const state = stopGatewayForMaintenance();\n if (guard && baseline !== undefined) {\n try {\n guard.assertNoRunsStartedSince(baseline);\n } catch (error) {\n // 维护未开始,无论 keepStopped 都恢复原状态;恢复失败不得吞掉原始错误。\n if (state.wasRunning) {\n try {\n restartGatewayAfterMaintenance(state);\n } catch (restartError) {\n const original = error instanceof Error ? error.message : String(error);\n const restart = restartError instanceof Error ? restartError.message : String(restartError);\n throw new Error(`${original};Gateway 自动恢复也失败:${restart}`);\n }\n }\n throw error;\n }\n }\n let result: T;\n try {\n result = operation();\n } catch (error) {\n if (state.wasRunning && !keepStopped) {\n try {\n restartGatewayAfterMaintenance(state);\n } catch (restartError) {\n const original = error instanceof Error ? error.message : String(error);\n const restart = restartError instanceof Error ? restartError.message : String(restartError);\n throw new Error(`${original};Gateway 自动恢复也失败:${restart}`);\n }\n }\n throw error;\n }\n\n let restarted = false;\n if (state.wasRunning && !keepStopped) {\n try {\n restarted = restartGatewayAfterMaintenance(state);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new Error(`数据库维护已完成,但 Gateway 自动重启失败:${message}`);\n }\n }\n return {\n result,\n wasRunning: state.wasRunning,\n restarted,\n keptStopped: state.wasRunning && keepStopped,\n };\n });\n}\n\nexport function install(): void {\n return withManagementLock(installUnlocked);\n}\n\nfunction installUnlocked(): void {\n if (!isPm2Installed() && !installPm2()) {\n throw new Error(\"[supertask] Failed to install pm2. Please install it manually: npm install -g pm2\");\n }\n\n const existing = pm2JsonList().find((item) => item.name === PROCESS_NAME);\n const oldRuntime = gatewayRuntimeFromProcess(existing);\n const targetRuntime = oldRuntime\n ? refreshGatewayExecutionEnvironment(oldRuntime, resolveGatewayEntry())\n : currentGatewayRuntime();\n const before = getRunningVersion(oldRuntime?.env ?? process.env, oldRuntime?.cwd);\n if (oldRuntime && !scopesMatch(currentScope(), runtimeScope(oldRuntime))) {\n throw new Error(\"[supertask] 当前 CLI 与 PM2 Gateway 的数据库/配置/OpenCode 运行作用域不一致,已拒绝覆盖\");\n }\n\n replaceGatewayProcess({\n existing,\n oldRuntime,\n targetRuntime,\n version: getPackageVersion(),\n before,\n deleteAction: \"pm2 delete existing Gateway\",\n });\n\n if (!ensurePm2LogRotation(targetRuntime.env)) {\n console.warn(\"[supertask] pm2-logrotate 安装或配置失败;Gateway 已运行,但请执行 `supertask doctor` 检查日志治理。\");\n }\n if (process.platform === \"darwin\") {\n const path = installMacLaunchAgent(targetRuntime);\n console.log(`[supertask] macOS LaunchAgent installed: ${path}`);\n } else {\n const startup = pm2Exec([\"startup\"], { env: targetRuntime.env });\n if (startup.output) console.log(startup.output);\n if (process.platform === \"linux\" && (!startup.ok || !isLinuxStartupConfigured(targetRuntime.env, targetRuntime.cwd, targetRuntime))) {\n throw new Error(\"[supertask] pm2 startup 未完成或 systemd 自启未生效;Gateway 当前已运行,但安装未达到可重启恢复标准\");\n }\n }\n\n console.log(\"[supertask] Gateway installed and running.\");\n console.log(\"[supertask] Manage with: pm2 status / pm2 logs supertask-gateway\");\n}\n\nexport function uninstall(): void {\n return withManagementLock(uninstallUnlocked);\n}\n\nfunction uninstallUnlocked(): void {\n if (!isPm2Installed()) throw new Error(\"[supertask] pm2 is not installed\");\n const existing = pm2JsonList().find((item) => item.name === PROCESS_NAME);\n const runtime = gatewayRuntimeFromProcess(existing);\n assertRuntimeCanControlPm2(runtime, existing);\n if (existing) requirePm2Termination(\"delete\", \"pm2 delete Gateway\", runtime!);\n savePm2State(runtime?.env);\n if (process.platform === \"darwin\") removeMacLaunchAgent();\n console.log(\"[supertask] Gateway removed from pm2. Other pm2 startup entries were preserved.\");\n}\n\nexport function upgrade(target?: {\n gatewayEntry: string;\n version: string;\n}): { before: string | null; after: string; restarted: boolean } {\n return withManagementLock(() => upgradeUnlocked(target));\n}\n\nfunction upgradeUnlocked(target?: {\n gatewayEntry: string;\n version: string;\n}): { before: string | null; after: string; restarted: boolean } {\n if (!isPm2Installed()) {\n throw new Error(\"[supertask] pm2 is not installed. Run `supertask install` first.\");\n }\n\n const existing = pm2JsonList().find((item) => item.name === PROCESS_NAME);\n const oldRuntime = existing\n ? (gatewayRuntimeFromProcess(existing)\n ?? (process.env.SUPERTASK_GATEWAY_ENTRY ? currentGatewayRuntime(resolveGatewayEntry()) : null))\n : null;\n const before = getRunningVersion(oldRuntime?.env ?? process.env, oldRuntime?.cwd);\n const currentVersion = target?.version ?? getPackageVersion();\n const targetRuntime = oldRuntime\n ? refreshGatewayExecutionEnvironment(\n oldRuntime,\n target?.gatewayEntry ?? oldRuntime.gatewayEntry,\n )\n : currentGatewayRuntime(target?.gatewayEntry ?? resolveGatewayEntry());\n\n replaceGatewayProcess({\n existing,\n oldRuntime,\n targetRuntime,\n version: currentVersion,\n before,\n deleteAction: \"pm2 delete old Gateway\",\n });\n\n return { before, after: currentVersion, restarted: true };\n}\n\nexport function ensureGateway(): EnsureGatewayResult {\n return withManagementLock(ensureGatewayUnlocked);\n}\n\nfunction ensureGatewayUnlocked(): EnsureGatewayResult {\n if (!isPm2Installed()) {\n return { ok: false, reason: \"pm2-not-installed\" };\n }\n\n const currentVersion = getPackageVersion();\n const processList = pm2JsonList();\n const existing = processList.find((item) => item.name === PROCESS_NAME);\n const oldRuntime = gatewayRuntimeFromProcess(existing);\n if (oldRuntime && !scopesMatch(currentScope(), runtimeScope(oldRuntime))) {\n throw new Error(\"[supertask] 当前 OpenCode/CLI 与 PM2 Gateway 的数据库、配置或 OpenCode 可执行文件作用域不一致,已拒绝继续写入\");\n }\n assertRuntimeCanControlPm2(oldRuntime, existing);\n const lockedVersion = existing && typeof existing.pid === \"number\" && oldRuntime\n ? gatewayVersionFromLock(existing.pid, runtimeScope(oldRuntime).databasePath)\n : undefined;\n if (\n existing?.pm2_env?.status === \"online\"\n && typeof existing.pid === \"number\"\n && oldRuntime !== null\n && isGatewayReady(existing.pid, runtimeScope(oldRuntime).databasePath)\n && (\n lockedVersion === currentVersion\n || (\n lockedVersion === undefined\n && getRunningVersion(oldRuntime.env, oldRuntime.cwd) === currentVersion\n )\n )\n ) {\n return { ok: true, action: \"already-running\" };\n }\n\n const targetRuntime = oldRuntime\n ? { ...oldRuntime, gatewayEntry: resolve(resolveGatewayEntry()) }\n : currentGatewayRuntime();\n const before = getRunningVersion(oldRuntime?.env ?? process.env, oldRuntime?.cwd);\n\n replaceGatewayProcess({\n existing,\n oldRuntime,\n targetRuntime,\n version: currentVersion,\n before,\n deleteAction: \"pm2 delete stale Gateway\",\n controlAlreadyVerified: true,\n });\n\n return { ok: true, action: existing ? \"restarted\" : \"started\" };\n}\n"],"mappings":";;;;;;;;;;AAAA,SAAS,UAAU,iBAAiB;AACpC;AAAA,EACI;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OACG;AACP,SAAS,eAAe;AACxB,SAAS,WAAW,SAAS,YAAY,MAAM,eAAe;AAC9D,SAAS,qBAAqB;AAC9B,SAAS,gBAAgB;AAEzB,IAAM,YAAY,QAAQ,cAAc,YAAY,GAAG,CAAC;AAEjD,IAAM,eAAe;AACrB,IAAM,yBAAyB;AAE/B,IAAM,8BAA8B;AACpC,IAAM,wBAAwB;AAuF9B,SAAS,sBAA8B;AAC1C,QAAM,WAAW,QAAQ,IAAI;AAC7B,MAAI,UAAU;AACV,QAAI,CAAC,WAAW,QAAQ,EAAG,OAAM,IAAI,MAAM,wCAAwC,QAAQ,EAAE;AAC7F,WAAO;AAAA,EACX;AAEA,QAAM,aAAa;AAAA,IACf,KAAK,WAAW,qBAAqB;AAAA,IACrC,KAAK,WAAW,qBAAqB;AAAA,EACzC;AACA,QAAM,QAAQ,WAAW,KAAK,CAAC,cAAc,WAAW,SAAS,CAAC;AAClE,MAAI,CAAC,MAAO,OAAM,IAAI,MAAM,iDAAiD,WAAW,KAAK,IAAI,CAAC,EAAE;AACpG,SAAO;AACX;AAEO,SAAS,YAAY,KAAgC;AACxD,SAAO,QAAQ,IAAI,QAAQ,QAAQ,CAAC;AACxC;AAEO,SAAS,YAAY,OAAe,KAAqB;AAC5D,SAAO,QAAQ,KAAK,KAAK;AAC7B;AAEO,SAAS,aAAa,MAAyB,QAAQ,KAAK,MAAM,QAAQ,IAAI,GAAW;AAC5F,SAAO,IAAI,oBACL,YAAY,IAAI,mBAAmB,GAAG,IACtC,KAAK,YAAY,GAAG,GAAG,gC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,SAAS,QAAQ,YAAY,aAChE,uBAAuB,SAAS,KAAK,aAAa,UAAU,EAAE,YAAY,IAC1E;AACN,MACI,UAAU,SAAS,WAAW,YAC3B,OAAO,SAAS,QAAQ,YACxB,eAAe,QACf,eAAe,SAAS,KAAK,aAAa,UAAU,EAAE,YAAY,MAEjE,kBAAkB,kBAEd,kBAAkB,UACf,kBAAkB,WAAW,KAAK,WAAW,GAAG,MAAM,iBAGnE;AACE,WAAO,EAAE,IAAI,MAAM,QAAQ,kBAAkB;AAAA,EACjD;AAEA,QAAM,gBAAgB,aAChB,EAAE,GAAG,YAAY,cAAcA,SAAQ,oBAAoB,CAAC,EAAE,IAC9D,sBAAsB;AAC5B,QAAM,SAAS,kBAAkB,YAAY,OAAO,QAAQ,KAAK,YAAY,GAAG;AAEhF,wBAAsB;AAAA,IAClB;AAAA,IACA;AAAA,IACA;AAAA,IACA,SAAS;AAAA,IACT;AAAA,IACA,cAAc;AAAA,IACd,wBAAwB;AAAA,EAC5B,CAAC;AAED,SAAO,EAAE,IAAI,MAAM,QAAQ,WAAW,cAAc,UAAU;AAClE;","names":["spawnSync","existsSync","readFileSync","join","resolve","Database","Database","mkdirSync","dirname","join","resolve","spawnSync","existsSync","Database","readFileSync","spawnSync","accessSync","constants","existsSync","mkdirSync","readFileSync","writeFileSync","dirname","join","resolve","fileURLToPath","__dirname","dirname","fileURLToPath","existsSync","resolve","join","readFileSync","accessSync","constants","spawnSync","mkdirSync","writeFileSync","accessSync","constants","statSync","resolve","accessSync","constants","statSync","resolve"]}
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/core/launch-protocol.ts"],"sourcesContent":["export const LEGACY_GUARDIAN_LAUNCH_PROTOCOL = 'gated-v2-guardian';\nexport const TOKEN_GUARDIAN_LAUNCH_PROTOCOL = 'gated-v3-token-guardian';\nexport const LAUNCH_IDENTITY_ARGUMENT = '--supertask-launch-identity';\nexport const DRAIN_PROOF_MESSAGE_TYPE = 'supertask-drained';\nexport const DRAIN_PROOF_ACK_MESSAGE_TYPE = 'supertask-drained-ack';\nexport const MANAGED_RUN_ENV = 'SUPERTASK_MANAGED_RUN';\nexport const MANAGED_RUN_ENV_VALUE = '1';\n\nexport function isLaunchIdentity(value: string | null | undefined): value is string {\n return value != null\n && /^gateway-[1-9]\\d*:launch:[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i.test(value);\n}\n\nexport function drainProofForIdentity(launchIdentity: string) {\n return { type: DRAIN_PROOF_MESSAGE_TYPE, identity: launchIdentity } as const;\n}\n\nexport function drainProofAckForIdentity(launchIdentity: string) {\n return { type: DRAIN_PROOF_ACK_MESSAGE_TYPE, identity: launchIdentity } as const;\n}\n\nexport function isMatchingDrainProof(message: unknown, launchIdentity: string): boolean {\n if (typeof message !== 'object' || message == null) return false;\n const candidate = message as Record<string, unknown>;\n return candidate.type === DRAIN_PROOF_MESSAGE_TYPE\n && candidate.identity === launchIdentity;\n}\n\nexport function isMatchingDrainProofAck(message: unknown, launchIdentity: string): boolean {\n if (typeof message !== 'object' || message == null) return false;\n const candidate = message as Record<string, unknown>;\n return candidate.type === DRAIN_PROOF_ACK_MESSAGE_TYPE\n && candidate.identity === launchIdentity;\n}\n"],"mappings":";;;;AAAO,IAAM,kCAAkC;AACxC,IAAM,iCAAiC;AACvC,IAAM,2BAA2B;AACjC,IAAM,2BAA2B;AACjC,IAAM,+BAA+B;AACrC,IAAM,kBAAkB;AACxB,IAAM,wBAAwB;AAE9B,SAAS,iBAAiB,OAAmD;AAChF,SAAO,SAAS,QACT,iGAAiG,KAAK,KAAK;AACtH;AAMO,SAAS,yBAAyB,gBAAwB;AAC7D,SAAO,EAAE,MAAM,8BAA8B,UAAU,eAAe;AAC1E;AAEO,SAAS,qBAAqB,SAAkB,gBAAiC;AACpF,MAAI,OAAO,YAAY,YAAY,WAAW,KAAM,QAAO;AAC3D,QAAM,YAAY;AAClB,SAAO,UAAU,SAAS,4BACnB,UAAU,aAAa;AAClC;","names":[]}
@@ -1,16 +0,0 @@
1
- #!/usr/bin/env bun
2
-
3
- import {
4
- DatabaseMaintenanceConflictError,
5
- DatabaseMaintenanceService
6
- } from "./chunk-DIJEKFBV.js";
7
- import "./chunk-ZBH7YWXF.js";
8
- import "./chunk-YB7MYTE5.js";
9
- import "./chunk-EQWICVCJ.js";
10
- import "./chunk-YGELD2E5.js";
11
- import "./chunk-3PIYMBV3.js";
12
- export {
13
- DatabaseMaintenanceConflictError,
14
- DatabaseMaintenanceService
15
- };
16
- //# sourceMappingURL=database-maintenance.service-F3IZU52F.js.map
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../src/worker/index.ts","../../src/worker/run-output.ts","../../src/gateway/watchdog/heartbeat.ts","../../src/gateway/watchdog/cleanup.ts","../../src/gateway/watchdog/index.ts","../../src/gateway/scheduler/index.ts","../../src/gateway/index.ts"],"sourcesContent":["import { TaskService } from '@core/services/task.service';\nimport { TaskRunService } from '@core/services/task-run.service';\nimport { spawn, type ChildProcess } from 'child_process';\nimport type { GatewayConfig } from '@gateway/config';\nimport type { Task } from '@core/db/schema';\nimport {\n markGatewayActivity,\n markGatewayFailure,\n markGatewaySuccess,\n} from '@gateway/health';\nimport { gatewayEvents } from '@gateway/events';\nimport {\n inspectSpawnedProcessTreePresence,\n signalRecordedProcessTreeWithResult,\n waitForSpawnedProcessTreeExit,\n} from '@core/process-control';\nimport { fileURLToPath } from 'url';\nimport { existsSync } from 'fs';\nimport { dirname, join } from 'path';\nimport { randomUUID } from 'crypto';\nimport {\n drainProofAckForIdentity,\n isMatchingDrainProof,\n LAUNCH_IDENTITY_ARGUMENT,\n MANAGED_RUN_ENV,\n MANAGED_RUN_ENV_VALUE,\n TOKEN_GUARDIAN_LAUNCH_PROTOCOL,\n} from '@core/launch-protocol';\nimport { validateTaskWorkingDirectory } from '@core/task-working-directory';\nimport { normalizeTaskBatchId } from '@core/task-batch';\nimport { RunOutput } from './run-output';\nimport {\n buildOpenCodeRunArgs,\n detectOpenCodeVersion,\n OpenCodeInvocationError,\n openCodeExecutable,\n} from '@core/opencode-cli';\n\nconst DEFAULT_MAX_OUTPUT_CHARS = 64 * 1024;\nconst FORBIDDEN_AGENT = 'supertask-runner';\n\ninterface WorkerEngineOptions {\n opencodeBin?: string;\n maxOutputChars?: number;\n settlementRetryDelaysMs?: number[];\n settlementRetryIntervalMs?: number;\n}\n\ninterface TaskTermination {\n kind: 'cancel' | 'failure' | 'shutdown';\n message: string;\n}\n\ninterface RunningTask {\n task: Task;\n runId: number;\n launchIdentity: string;\n child: ChildProcess;\n commandContext: string;\n output: RunOutput;\n timeoutTimer: ReturnType<typeof setTimeout> | null;\n termination: TaskTermination | null;\n terminationPromise: Promise<boolean> | null;\n settlementPromise: Promise<boolean> | null;\n guardianDrained: boolean;\n quarantined: boolean;\n settled: boolean;\n}\n\nexport interface InterruptedTaskRun {\n taskId: number;\n runId: number;\n}\n\nexport function runCommandContext(executable: string, args: string[], cwd: string): string {\n return JSON.stringify({\n type: 'supertask_command',\n executable,\n args,\n cwd,\n });\n}\n\nexport function assertWorkerProcessIsolationSupported(\n platform: NodeJS.Platform = process.platform,\n): void {\n if (platform === 'win32') {\n throw new Error(\n 'Windows Worker 已安全禁用:当前运行时无法用 Job Object 提供等价的受管进程隔离与排空证明',\n );\n }\n}\n\nexport class WorkerEngine {\n private activeBatchIds = new Set<string>();\n private runningTasks = new Map<number, RunningTask>();\n private stopped = false;\n private wakePending = false;\n private consecutiveIdlePolls = 0;\n private unsubscribeWake: (() => void) | null = null;\n private pollTimer: ReturnType<typeof setTimeout> | null = null;\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n private pollCyclePromise: Promise<void> | null = null;\n private shutdownDeadlineMs: number | null = null;\n private settlementRetryWakeups = new Set<() => void>();\n private cfg: GatewayConfig['worker'];\n private opencodeBin: string;\n private maxOutputChars: number;\n private settlementRetryDelaysMs: number[];\n private settlementRetryIntervalMs: number;\n\n constructor(cfg: GatewayConfig, options: WorkerEngineOptions = {}) {\n this.cfg = cfg.worker;\n this.opencodeBin = options.opencodeBin ?? openCodeExecutable();\n this.maxOutputChars = options.maxOutputChars ?? DEFAULT_MAX_OUTPUT_CHARS;\n this.settlementRetryDelaysMs = options.settlementRetryDelaysMs ?? [250, 1_000, 4_000];\n this.settlementRetryIntervalMs = options.settlementRetryIntervalMs ?? 5_000;\n }\n\n start() {\n assertWorkerProcessIsolationSupported();\n this.stopped = false;\n this.wakePending = false;\n this.consecutiveIdlePolls = 0;\n this.shutdownDeadlineMs = null;\n this.unsubscribeWake?.();\n this.unsubscribeWake = gatewayEvents.registerWakeHandler((reason) => this.wake(reason));\n markGatewayActivity('worker');\n this.poll();\n this.heartbeatTimer = setInterval(() => {\n this.runDetached(this.updateHeartbeats(), 'worker heartbeat cycle failed');\n }, this.cfg.heartbeatIntervalMs);\n }\n\n wake(_reason?: string) {\n if (this.stopped) return;\n this.consecutiveIdlePolls = 0;\n if (this.pollCyclePromise) {\n this.wakePending = true;\n return;\n }\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n this.pollTimer = null;\n }\n this.pollTimer = setTimeout(() => {\n this.pollTimer = null;\n this.poll();\n }, 0);\n }\n\n async stop(gracePeriodMs = 0): Promise<InterruptedTaskRun[]> {\n this.stopped = true;\n this.wakePending = false;\n this.unsubscribeWake?.();\n this.unsubscribeWake = null;\n this.shutdownDeadlineMs = Date.now() + Math.max(0, gracePeriodMs);\n for (const wake of [...this.settlementRetryWakeups]) wake();\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n this.pollTimer = null;\n }\n\n if (this.pollCyclePromise) await this.pollCyclePromise;\n\n if (gracePeriodMs > 0 && this.runningTasks.size > 0) {\n const deadline = Date.now() + gracePeriodMs;\n while (\n [...this.runningTasks.values()].some((entry) => !(\n entry.termination?.kind === 'shutdown'\n && (entry.child.exitCode !== null || entry.child.signalCode !== null)\n ))\n && Date.now() < deadline\n ) {\n await Bun.sleep(Math.min(50, deadline - Date.now()));\n }\n }\n\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n\n const interrupted: InterruptedTaskRun[] = [];\n const entries = [...this.runningTasks.values()];\n await Promise.all(entries.map(async (entry) => {\n if (entry.settled) {\n if (entry.settlementPromise) await entry.settlementPromise;\n return;\n }\n\n const termination = entry.termination ?? {\n kind: 'shutdown' as const,\n message: 'Gateway shutdown',\n };\n const terminated = await this.terminateEntry(entry, termination);\n if (terminated && termination.kind === 'shutdown') {\n interrupted.push({ taskId: entry.task.id, runId: entry.runId });\n }\n }));\n return interrupted;\n }\n\n getRunningTaskIds(): number[] {\n return [...this.runningTasks.keys()];\n }\n\n getRunningCount(): number {\n return this.runningTasks.size;\n }\n\n ownsRun(taskId: number, runId: number): boolean {\n return this.runningTasks.get(taskId)?.runId === runId;\n }\n\n private nextPollDelayMs(): number {\n const base = this.cfg.pollIntervalMs;\n if (base < 500 || this.consecutiveIdlePolls <= 1 || this.runningTasks.size > 0) {\n return base;\n }\n const maxIdleMs = Math.max(base, Math.min(base * 2, 2_500));\n const step = Math.min(this.consecutiveIdlePolls - 1, 3);\n return Math.max(base, Math.min(maxIdleMs, Math.round(base * (1 + step * 0.5))));\n }\n\n private poll() {\n if (this.stopped) return;\n if (this.pollTimer) {\n clearTimeout(this.pollTimer);\n this.pollTimer = null;\n }\n this.wakePending = false;\n markGatewayActivity('worker');\n\n this.pollCyclePromise = this.tryDispatch()\n .then(({ healthy, dispatched }) => {\n if (dispatched > 0) this.consecutiveIdlePolls = 0;\n else this.consecutiveIdlePolls += 1;\n if (healthy) markGatewaySuccess('worker');\n })\n .catch((err) => {\n this.consecutiveIdlePolls = 0;\n markGatewayFailure('worker', err);\n this.logError('worker poll failed', err);\n })\n .finally(() => {\n this.pollCyclePromise = null;\n if (this.stopped) return;\n if (this.wakePending) {\n this.wakePending = false;\n this.pollTimer = setTimeout(() => {\n this.pollTimer = null;\n this.poll();\n }, 0);\n return;\n }\n this.pollTimer = setTimeout(() => {\n this.pollTimer = null;\n this.poll();\n }, this.nextPollDelayMs());\n });\n }\n\n private async tryDispatch(): Promise<{ healthy: boolean; dispatched: number }> {\n await TaskService.resetOrphanRunningToPending();\n await this.reconcileCancelledTasks();\n await this.reconcileQuarantinedTasks();\n\n let dispatched = 0;\n\n // 隔离中的 run 继续占用并发名额、批次和数据库 running 状态,只阻止同批次重入;\n // 其他批次照常调度,Worker 仍在返回值中报告不健康,避免单个遗留进程组冻结整个队列。\n while (!this.stopped && this.runningTasks.size < this.cfg.maxConcurrency) {\n const databaseRunningCount = await TaskService.countRunning();\n if (databaseRunningCount >= this.cfg.maxConcurrency) break;\n // 先确认 OpenCode 可用且版本可识别再抢占任务:不可用时不消耗任务重试次数,\n // 也不会在“数据库已 running、Worker 尚未登记”的窗口里等待外部命令。\n const openCode = await detectOpenCodeVersion(this.opencodeBin);\n if (this.stopped) break;\n\n let task: Task | null;\n try {\n task = await TaskService.claimNext({ excludedBatchIds: [...this.activeBatchIds] });\n } catch (err) {\n this.logError('task claim failed', err);\n throw err;\n }\n if (!task) break;\n if (this.stopped) {\n await TaskService.resetRunningToPending([task.id]);\n break;\n }\n\n dispatched += 1;\n const batchId = normalizeTaskBatchId(task.batchId);\n if (batchId) this.activeBatchIds.add(batchId);\n gatewayEvents.emitTaskChanged({\n taskId: task.id,\n cwd: task.cwd,\n status: 'running',\n reason: 'task-claimed',\n });\n\n let runId: number | null = null;\n try {\n const launchIdentity = `gateway-${process.pid}:launch:${randomUUID()}`;\n const run = await TaskRunService.create({\n taskId: task.id,\n model: this.resolveModel(task.model),\n variant: this.resolveVariant(task.variant),\n status: 'running',\n workerPid: process.pid,\n lockedAt: Date.now(),\n lockedBy: launchIdentity,\n launchProtocol: TOKEN_GUARDIAN_LAUNCH_PROTOCOL,\n });\n runId = run.id;\n\n if (this.stopped) {\n await TaskRunService.fail(run.id, 'Gateway shutdown before spawn');\n await TaskService.resetRunningToPending([task.id]);\n this.releaseBatch(task);\n break;\n }\n\n if (task.agent === FORBIDDEN_AGENT) {\n const message = `禁止执行递归 Agent: ${FORBIDDEN_AGENT}`;\n await TaskService.failRun(task.id, run.id, message, { setDeadLetter: true });\n this.releaseBatch(task);\n continue;\n }\n\n try {\n validateTaskWorkingDirectory(task.cwd);\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n await TaskService.failRun(task.id, run.id, message, { setDeadLetter: true });\n this.releaseBatch(task);\n continue;\n }\n\n let args: string[];\n try {\n args = buildOpenCodeRunArgs(openCode.major, {\n agent: task.agent,\n model: this.resolveModel(task.model),\n variant: this.resolveVariant(task.variant),\n prompt: task.prompt,\n title: task.name,\n });\n } catch (error) {\n if (!(error instanceof OpenCodeInvocationError)) throw error;\n await TaskService.failRun(task.id, run.id, `${error.message}(OpenCode ${openCode.version})`, { setDeadLetter: true });\n this.releaseBatch(task);\n continue;\n }\n\n await this.spawnTask(task, run.id, launchIdentity, args);\n } catch (err) {\n this.releaseBatch(task);\n const message = `Worker 启动任务失败:${err instanceof Error ? err.message : String(err)}`;\n try {\n if (runId == null) {\n await TaskService.fail(task.id, message);\n } else {\n const failed = await TaskService.failRun(task.id, runId, message);\n if (!failed) {\n await TaskRunService.fail(runId, `${message}\\n任务状态已被其他操作改变`);\n }\n }\n } catch (failErr) {\n this.logError('failed to compensate task startup', failErr, task.id);\n }\n this.logError('task dispatch failed', err, task.id);\n }\n }\n return {\n healthy: ![...this.runningTasks.values()].some((entry) => entry.quarantined),\n dispatched,\n };\n }\n\n private launcherEntry(): string {\n const extension = import.meta.url.endsWith('.ts') ? 'ts' : 'js';\n const moduleDir = dirname(fileURLToPath(import.meta.url));\n const candidates = [\n join(moduleDir, `launcher.${extension}`),\n join(moduleDir, `../worker/launcher.${extension}`),\n ];\n const entry = candidates.find((candidate) => existsSync(candidate));\n if (!entry) throw new Error(`Worker launcher 不存在:${candidates.join(', ')}`);\n return entry;\n }\n\n private async spawnTask(task: Task, runId: number, launchIdentity: string, args: string[]): Promise<void> {\n const cwd = task.cwd || process.cwd();\n\n const child = spawn(process.execPath, [\n this.launcherEntry(),\n LAUNCH_IDENTITY_ARGUMENT,\n launchIdentity,\n this.opencodeBin,\n ...args,\n ], {\n cwd,\n env: {\n ...process.env,\n PWD: cwd,\n [MANAGED_RUN_ENV]: MANAGED_RUN_ENV_VALUE,\n },\n stdio: ['pipe', 'pipe', 'pipe', 'ipc'],\n detached: process.platform !== 'win32',\n });\n const entry: RunningTask = {\n task,\n runId,\n launchIdentity,\n child,\n commandContext: runCommandContext(this.opencodeBin, args, cwd),\n output: new RunOutput(\n this.maxOutputChars,\n (sessionId) => {\n TaskRunService.updateSessionId(runId, sessionId).catch((err) => {\n this.logError('sessionId update failed', err, task.id);\n });\n },\n (stream, line) => {\n gatewayEvents.emitRunLog(runId, task.id, stream, line);\n },\n ),\n timeoutTimer: null,\n termination: null,\n terminationPromise: null,\n settlementPromise: null,\n guardianDrained: false,\n quarantined: false,\n settled: false,\n };\n this.runningTasks.set(task.id, entry);\n\n child.stdout?.setEncoding('utf8');\n child.stderr?.setEncoding('utf8');\n child.stdout?.on('data', (chunk: string) => entry.output.push('stdout', chunk));\n child.stderr?.on('data', (chunk: string) => entry.output.push('stderr', chunk));\n child.on('message', (message: unknown) => {\n if (isMatchingDrainProof(message, entry.launchIdentity)) {\n entry.guardianDrained = true;\n try {\n child.send(drainProofAckForIdentity(entry.launchIdentity));\n } catch (error) {\n this.logError('drain proof acknowledgment failed', error, task.id);\n }\n }\n });\n let spawnError: Error | null = null;\n let started = false;\n const spawned = new Promise<void>((resolve, reject) => {\n child.once('spawn', () => {\n started = true;\n resolve();\n });\n // 常驻监听:Bun 在向已退出子进程 send() 时异步触发 'error'。启动后的错误只记录,\n // 不能被当成“无法启动”,也不能因没有监听器而抛出未处理 'error' 终止 Gateway。\n child.on('error', (error) => {\n if (started) {\n this.logError('launcher process error', error, task.id);\n return;\n }\n spawnError = error;\n reject(error);\n });\n });\n child.once('close', (code, signal) => {\n this.handleChildClose(entry, code, signal, spawnError);\n });\n\n try {\n await spawned;\n } catch (error) {\n entry.settled = true;\n this.runningTasks.delete(task.id);\n this.releaseBatch(task);\n throw error;\n }\n\n const childPid = child.pid;\n if (!childPid) {\n entry.settled = true;\n this.runningTasks.delete(task.id);\n this.releaseBatch(task);\n throw new Error('launcher 未返回 PID');\n }\n\n let pidRecorded = false;\n try {\n pidRecorded = await TaskRunService.updatePid(\n runId,\n process.pid,\n childPid,\n launchIdentity,\n ) !== null;\n } catch (error) {\n await this.terminateForFailure(\n entry,\n `记录 Worker PID 失败:${error instanceof Error ? error.message : String(error)}`,\n );\n return;\n }\n if (!pidRecorded) {\n await this.terminateForFailure(entry, '记录 Worker PID 失败:run 已不再处于 running 状态');\n return;\n }\n\n if (this.stopped) {\n entry.termination = { kind: 'shutdown', message: 'Gateway shutdown' };\n try {\n child.stdin?.end();\n } catch {\n }\n return;\n }\n\n if (!child.stdin) {\n await this.terminateForFailure(entry, '放行 OpenCode 失败:launcher stdin 不可用');\n return;\n }\n gatewayEvents.emitRunStarted({\n runId,\n taskId: task.id,\n cwd: task.cwd,\n model: this.resolveModel(task.model),\n variant: this.resolveVariant(task.variant),\n });\n try {\n await new Promise<void>((resolve, reject) => {\n child.stdin!.end('START\\n', (error?: Error | null) => {\n if (error) reject(error);\n else resolve();\n });\n });\n } catch (error) {\n await this.terminateForFailure(\n entry,\n `放行 OpenCode 失败:${error instanceof Error ? error.message : String(error)}`,\n );\n return;\n }\n\n if (entry.settled || entry.termination) return;\n\n const timeoutMs = task.timeoutMs ?? this.cfg.taskTimeoutMs;\n if (timeoutMs > 0) {\n entry.timeoutTimer = setTimeout(() => {\n this.runDetached(\n this.terminateForFailure(entry, `任务超时(${timeoutMs}ms)`, 'SIGKILL'),\n 'timeout termination failed',\n entry.task.id,\n );\n }, timeoutMs);\n entry.timeoutTimer.unref?.();\n }\n }\n\n private handleChildClose(\n entry: RunningTask,\n code: number | null,\n signal: NodeJS.Signals | null,\n spawnError: Error | null,\n ): void {\n if (entry.settled || entry.termination) return;\n\n if (!entry.guardianDrained) {\n const pid = entry.child.pid;\n const presence = pid == null\n ? spawnError == null ? 'unknown' : 'not-running'\n : inspectSpawnedProcessTreePresence(pid);\n const message = 'guardian 未提供受管进程组排空证明';\n if (presence !== 'not-running') {\n if (entry.timeoutTimer) {\n clearTimeout(entry.timeoutTimer);\n entry.timeoutTimer = null;\n }\n entry.termination = { kind: 'failure', message };\n entry.quarantined = true;\n markGatewayFailure(\n 'worker',\n new Error(`${message};任务 #${entry.task.id} 保持隔离`),\n );\n return;\n }\n this.runDetached(\n this.settleEntry(entry, null, message),\n 'task settlement failed',\n entry.task.id,\n );\n return;\n }\n\n const pid = entry.child.pid;\n if (pid != null && inspectSpawnedProcessTreePresence(pid) !== 'not-running') {\n if (entry.timeoutTimer) {\n clearTimeout(entry.timeoutTimer);\n entry.timeoutTimer = null;\n }\n const message = 'guardian 退出后受管进程组仍存活或状态不明';\n entry.guardianDrained = false;\n entry.termination = { kind: 'failure', message };\n entry.quarantined = true;\n markGatewayFailure(\n 'worker',\n new Error(`${message};任务 #${entry.task.id} 保持隔离`),\n );\n return;\n }\n\n const failure = code === 0\n ? undefined\n : `${spawnError ? '无法启动 opencode' : 'opencode 退出码'} ${spawnError?.message ?? code ?? 'null'}${signal ? `,信号 ${signal}` : ''}`\n + `(agent=${entry.task.agent},model=${this.resolveModel(entry.task.model) ?? 'Agent/默认配置'},variant=${this.resolveVariant(entry.task.variant) ?? 'Agent/模型默认配置'},cwd=${entry.task.cwd ?? process.cwd()})`;\n this.runDetached(\n this.settleEntry(entry, code, failure),\n 'task settlement failed',\n entry.task.id,\n );\n }\n\n private settleEntry(\n entry: RunningTask,\n code: number | null,\n failure?: string,\n ): Promise<boolean> {\n if (entry.settlementPromise) return entry.settlementPromise;\n if (entry.settled) return Promise.resolve(false);\n entry.settled = true;\n if (entry.timeoutTimer) {\n clearTimeout(entry.timeoutTimer);\n entry.timeoutTimer = null;\n }\n\n const settlement = this.commitEntryWithRetry(entry, code, failure)\n .finally(() => {\n this.runningTasks.delete(entry.task.id);\n this.releaseBatch(entry.task);\n if (!this.stopped) this.wake('task-settled');\n });\n entry.settlementPromise = settlement;\n return settlement;\n }\n\n private async commitEntryWithRetry(\n entry: RunningTask,\n code: number | null,\n failure?: string,\n ): Promise<boolean> {\n for (let attempt = 0; ; attempt += 1) {\n try {\n await this.commitEntry(entry, code, failure);\n return true;\n } catch (error) {\n markGatewayFailure('worker', error);\n const shortRetryDelayMs = this.settlementRetryDelaysMs[attempt];\n let retryDelayMs = shortRetryDelayMs ?? this.settlementRetryIntervalMs;\n if (this.stopped) {\n const remainingMs = Math.max(0, (this.shutdownDeadlineMs ?? 0) - Date.now());\n if (remainingMs === 0) return false;\n retryDelayMs = Math.min(retryDelayMs, remainingMs);\n }\n this.logError(\n `task settlement failed; retrying in ${retryDelayMs}ms`,\n error,\n entry.task.id,\n );\n await this.waitForSettlementRetry(retryDelayMs);\n }\n }\n }\n\n private waitForSettlementRetry(delayMs: number): Promise<void> {\n return new Promise((resolve) => {\n let timer: ReturnType<typeof setTimeout>;\n const finish = () => {\n clearTimeout(timer);\n this.settlementRetryWakeups.delete(finish);\n resolve();\n };\n timer = setTimeout(finish, delayMs);\n this.settlementRetryWakeups.add(finish);\n });\n }\n\n private async commitEntry(\n entry: RunningTask,\n code: number | null,\n failure?: string,\n ): Promise<void> {\n const termination = entry.termination;\n if (termination?.kind === 'shutdown') return;\n\n if (termination?.kind === 'cancel') {\n const output = this.outputWithCommand(entry);\n const log = `${termination.message}${output ? `\\n${output}` : ''}`;\n await TaskRunService.fail(entry.runId, log);\n gatewayEvents.emitRunFinished({\n runId: entry.runId,\n taskId: entry.task.id,\n status: 'failed',\n taskStatus: 'cancelled',\n cwd: entry.task.cwd,\n });\n gatewayEvents.emitTaskChanged({\n taskId: entry.task.id,\n cwd: entry.task.cwd,\n status: 'cancelled',\n reason: 'run-cancelled',\n });\n console.log(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'info',\n msg: 'running task cancelled',\n taskId: entry.task.id,\n }));\n return;\n }\n\n const currentRun = await TaskRunService.getById(entry.runId);\n if (!currentRun || currentRun.status !== 'running') return;\n\n const output = this.outputWithCommand(entry);\n const log = failure\n ? `${failure}${output ? `\\n${output}` : ''}`\n : output;\n\n if (code === 0 && !failure) {\n const completed = await TaskService.completeRun(entry.task.id, entry.runId, log);\n if (completed) {\n gatewayEvents.emitRunFinished({\n runId: entry.runId,\n taskId: entry.task.id,\n status: 'done',\n taskStatus: 'done',\n cwd: entry.task.cwd,\n });\n gatewayEvents.emitTaskChanged({\n taskId: entry.task.id,\n cwd: entry.task.cwd,\n status: 'done',\n reason: 'run-done',\n });\n console.log(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'info',\n msg: 'task done',\n taskId: entry.task.id,\n }));\n return;\n }\n\n await TaskRunService.fail(entry.runId, '任务或执行记录状态已被其他操作改变');\n gatewayEvents.emitRunFinished({\n runId: entry.runId,\n taskId: entry.task.id,\n status: 'failed',\n cwd: entry.task.cwd,\n });\n return;\n }\n\n const failed = await TaskService.failRun(entry.task.id, entry.runId, log);\n if (!failed) {\n await TaskRunService.fail(\n entry.runId,\n `${log}${log ? '\\n' : ''}任务状态已被其他操作改变`,\n );\n this.logError('task failure state transition rejected', failure ?? 'unknown failure', entry.task.id);\n gatewayEvents.emitRunFinished({\n runId: entry.runId,\n taskId: entry.task.id,\n status: 'failed',\n cwd: entry.task.cwd,\n });\n return;\n }\n gatewayEvents.emitRunFinished({\n runId: entry.runId,\n taskId: entry.task.id,\n status: 'failed',\n taskStatus: failed.status,\n cwd: entry.task.cwd,\n });\n gatewayEvents.emitTaskChanged({\n taskId: entry.task.id,\n cwd: entry.task.cwd,\n status: failed.status,\n reason: 'run-failed',\n });\n console.error(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'error',\n msg: 'task failed',\n taskId: entry.task.id,\n error: failure,\n }));\n }\n\n private async reconcileCancelledTasks() {\n for (const entry of [...this.runningTasks.values()]) {\n try {\n const task = await TaskService.getById(entry.task.id);\n if (task?.status === 'cancelled') await this.cancelEntry(entry);\n } catch (err) {\n this.logError('cancel reconciliation failed', err, entry.task.id);\n }\n }\n }\n\n private async reconcileQuarantinedTasks() {\n for (const entry of [...this.runningTasks.values()]) {\n if (!entry.quarantined || !entry.termination) continue;\n await this.terminateEntry(entry, entry.termination);\n }\n }\n\n private async cancelEntry(entry: RunningTask) {\n await this.terminateEntry(entry, { kind: 'cancel', message: '任务已取消' });\n }\n\n private async updateHeartbeats() {\n for (const entry of this.runningTasks.values()) {\n if (entry.quarantined) continue;\n try {\n await TaskRunService.heartbeat(entry.runId);\n } catch (err) {\n this.logError('heartbeat update failed', err, entry.task.id);\n }\n }\n }\n\n private async terminateForFailure(\n entry: RunningTask,\n message: string,\n initialSignal: NodeJS.Signals = 'SIGTERM',\n ): Promise<boolean> {\n return this.terminateEntry(entry, { kind: 'failure', message }, initialSignal);\n }\n\n private terminateEntry(\n entry: RunningTask,\n termination: TaskTermination,\n initialSignal: NodeJS.Signals = 'SIGTERM',\n ): Promise<boolean> {\n if (entry.terminationPromise) return entry.terminationPromise;\n if (entry.settled) return entry.settlementPromise ?? Promise.resolve(false);\n\n entry.termination ??= termination;\n if (entry.timeoutTimer) {\n clearTimeout(entry.timeoutTimer);\n entry.timeoutTimer = null;\n }\n entry.quarantined = true;\n\n const terminationPromise = this.completeTermination(entry, initialSignal)\n .finally(() => {\n if (!entry.settled && entry.terminationPromise === terminationPromise) {\n entry.terminationPromise = null;\n }\n });\n entry.terminationPromise = terminationPromise;\n return terminationPromise;\n }\n\n private async completeTermination(\n entry: RunningTask,\n initialSignal: NodeJS.Signals,\n ): Promise<boolean> {\n const termination = entry.termination;\n if (!termination) return false;\n\n try {\n const exited = await this.killEntry(entry, initialSignal);\n if (!exited) {\n markGatewayFailure(\n 'worker',\n new Error(`${termination.message};任务 #${entry.task.id} 的进程无法确认退出`),\n );\n return false;\n }\n entry.quarantined = false;\n return await this.settleEntry(\n entry,\n null,\n termination.kind === 'failure' ? termination.message : undefined,\n );\n } catch (error) {\n markGatewayFailure('worker', error);\n this.logError('task termination failed', error, entry.task.id);\n return false;\n }\n }\n\n private async killEntry(\n entry: RunningTask,\n initialSignal: NodeJS.Signals = 'SIGTERM',\n ): Promise<boolean> {\n const pid = entry.child.pid;\n // 只有绑定当前 run 身份的独立 IPC 证明且内核确认进程组不存在时,才可直接视为排空。\n if (entry.guardianDrained\n && (entry.child.exitCode !== null || entry.child.signalCode !== null)\n && (!pid || inspectSpawnedProcessTreePresence(pid) === 'not-running')) return true;\n if (!pid) return false;\n\n const initialResult = this.signalEntry(entry, initialSignal);\n if (initialResult === 'not-running') return true;\n if (initialResult !== 'signalled') return false;\n if (await waitForSpawnedProcessTreeExit(pid, 2_500)) return true;\n if (initialSignal === 'SIGKILL') return false;\n if (entry.guardianDrained\n && (entry.child.exitCode !== null || entry.child.signalCode !== null)\n && inspectSpawnedProcessTreePresence(pid) === 'not-running') return true;\n\n const forcedResult = this.signalEntry(entry, 'SIGKILL');\n if (forcedResult === 'not-running') return true;\n if (forcedResult !== 'signalled') return false;\n return waitForSpawnedProcessTreeExit(pid, 2_500);\n }\n\n private signalEntry(entry: RunningTask, signal: NodeJS.Signals) {\n const pid = entry.child.pid;\n if (!pid) return 'not-running' as const;\n\n return signalRecordedProcessTreeWithResult(\n pid,\n signal,\n this.opencodeBin,\n TOKEN_GUARDIAN_LAUNCH_PROTOCOL,\n entry.launchIdentity,\n );\n }\n\n private releaseBatch(task: Task) {\n const batchId = normalizeTaskBatchId(task.batchId);\n if (batchId) this.activeBatchIds.delete(batchId);\n }\n\n private outputWithCommand(entry: RunningTask): string {\n entry.output.flush();\n const output = entry.output.text().trim();\n return `${entry.commandContext}${output ? `\\n${output}` : ''}`;\n }\n\n private resolveModel(taskModel: string | null): string | null {\n const normalized = taskModel?.trim();\n if (!normalized || normalized === 'default') return null;\n return normalized;\n }\n\n private resolveVariant(taskVariant: string | null): string | null {\n return taskVariant?.trim() || null;\n }\n\n private runDetached(operation: Promise<unknown>, message: string, taskId?: number): void {\n operation.catch((error) => {\n markGatewayFailure('worker', error);\n this.logError(message, error, taskId);\n });\n }\n\n private logError(message: string, error: unknown, taskId?: number) {\n console.error(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'error',\n msg: message,\n taskId,\n error: error instanceof Error ? error.message : String(error),\n }));\n }\n}\n","const SESSION_ID_PATTERN = /^ses_[A-Za-z0-9_]+$/;\n\ntype OutputStream = 'stdout' | 'stderr';\n\n/**\n * Collects a bounded, line-coherent tail of OpenCode output.\n * stdout and stderr are buffered per stream so a chunk from one stream\n * never lands inside a JSON line of the other, and the session ID is\n * taken from the first top-level stdout event only: later events may\n * echo child/subagent session IDs inside tool output.\n */\nexport class RunOutput {\n private lines: string[] = [];\n private head = 0;\n private totalChars = 0;\n private readonly partial: Record<OutputStream, string> = { stdout: '', stderr: '' };\n private sessionId: string | null = null;\n\n constructor(\n private readonly maxChars: number,\n private readonly onSessionId: (sessionId: string) => void,\n private readonly onLine?: (stream: OutputStream, line: string) => void,\n ) {}\n\n push(stream: OutputStream, chunk: string): void {\n const lines = (this.partial[stream] + chunk).split('\\n');\n let rest = lines.pop() ?? '';\n if (rest.length > this.maxChars) {\n lines.push(rest);\n rest = '';\n }\n this.partial[stream] = rest;\n for (const line of lines) this.appendLine(stream, line);\n }\n\n flush(): void {\n for (const stream of ['stdout', 'stderr'] as const) {\n const rest = this.partial[stream];\n this.partial[stream] = '';\n if (rest) this.appendLine(stream, rest);\n }\n }\n\n text(): string {\n if (this.head >= this.lines.length) return '';\n return this.head === 0 ? this.lines.join('') : this.lines.slice(this.head).join('');\n }\n\n private appendLine(stream: OutputStream, line: string): void {\n const clean = line.endsWith('\\r') ? line.slice(0, -1) : line;\n this.pushBoundedLine(`${clean}\\n`);\n if (this.onLine) {\n try {\n this.onLine(stream, clean);\n } catch {\n }\n }\n if (stream === 'stdout' && this.sessionId === null) this.detectSessionId(clean);\n }\n\n private pushBoundedLine(entry: string): void {\n if (this.maxChars <= 0) return;\n if (entry.length >= this.maxChars) {\n const truncated = entry.slice(-this.maxChars);\n this.lines = [truncated];\n this.head = 0;\n this.totalChars = truncated.length;\n return;\n }\n\n this.lines.push(entry);\n this.totalChars += entry.length;\n\n while (this.totalChars > this.maxChars && this.head < this.lines.length) {\n const first = this.lines[this.head];\n if (this.totalChars - first.length >= this.maxChars) {\n this.totalChars -= first.length;\n this.lines[this.head] = '';\n this.head += 1;\n } else {\n const overflow = this.totalChars - this.maxChars;\n this.lines[this.head] = first.slice(overflow);\n this.totalChars = this.maxChars;\n break;\n }\n }\n\n if (this.head >= 1024 && this.head * 2 >= this.lines.length) {\n this.lines = this.lines.slice(this.head);\n this.head = 0;\n }\n }\n\n private detectSessionId(line: string): void {\n if (!line.startsWith('{') || !line.includes('ses_')) return;\n let event: unknown;\n try {\n event = JSON.parse(line);\n } catch {\n return;\n }\n const sessionId = topLevelSessionId(event);\n if (!sessionId) return;\n this.sessionId = sessionId;\n this.onSessionId(sessionId);\n }\n}\n\nexport function topLevelSessionId(event: unknown): string | null {\n if (event === null || typeof event !== 'object' || Array.isArray(event)) return null;\n const record = event as Record<string, unknown>;\n const value = record.sessionID ?? record.sessionId;\n return typeof value === 'string' && SESSION_ID_PATTERN.test(value) ? value : null;\n}\n","import { openCodeExecutable } from '@core/opencode-cli';\nimport { TaskRunService } from '@core/services/task-run.service';\nimport { TaskService } from '@core/services/task.service';\nimport {\n inspectSpawnedProcessTreePresence,\n isProcessAlive,\n signalRecordedProcessTreeWithResult,\n waitForSpawnedProcessTreeExit,\n} from '@core/process-control';\nimport { gatewayEvents } from '@gateway/events';\nimport {\n LEGACY_GUARDIAN_LAUNCH_PROTOCOL,\n TOKEN_GUARDIAN_LAUNCH_PROTOCOL,\n} from '@core/launch-protocol';\n\nexport async function checkHeartbeats(\n heartbeatTimeoutMs: number,\n isOwnedRun: (taskId: number, runId: number) => boolean = () => false,\n shouldStop: () => boolean = () => false,\n) {\n const staleRuns = await TaskRunService.getStaleRuns(heartbeatTimeoutMs);\n const result = {\n staleRuns: staleRuns.length,\n recoveredRuns: 0,\n quarantinedRuns: 0,\n failedRuns: 0,\n };\n if (staleRuns.length === 0) return result;\n\n for (const run of staleRuns) {\n // 让锁心跳、停机信号和 Worker 定时器能在大量隔离记录之间运行;\n // 单次 OS 进程探测有界后,停机最多再等待当前这一条。\n await Bun.sleep(1);\n if (shouldStop()) break;\n if (isOwnedRun(run.taskId, run.runId)) continue;\n try {\n if (run.launchProtocol != null\n && run.launchProtocol !== LEGACY_GUARDIAN_LAUNCH_PROTOCOL\n && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {\n console.warn(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'warn',\n msg: 'unknown launch protocol remains quarantined',\n taskId: run.taskId,\n runId: run.runId,\n launchProtocol: run.launchProtocol,\n remediation: '升级到支持该协议的 SuperTask 版本;禁止使用 run abandon 绕过未知协议',\n }));\n result.quarantinedRuns += 1;\n continue;\n }\n if (run.childPid != null\n && run.launchProtocol !== TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {\n if (run.childPid > 0\n && !isProcessAlive(run.childPid)\n && inspectSpawnedProcessTreePresence(run.childPid) === 'not-running') {\n // 旧协议没有不可复用的进程身份,绝不向存活或状态不明的 PID/PGID 发信号;\n // 仅在进程与进程组均明确不存在时才安全收敛数据库状态。\n } else {\n console.warn(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'warn',\n msg: 'stale run has no per-run process identity; run remains quarantined',\n taskId: run.taskId,\n runId: run.runId,\n childPid: run.childPid,\n launchProtocol: run.launchProtocol,\n remediation: '旧启动协议不能排除 PID 复用,禁止自动终止;请人工确认进程与数据状态',\n }));\n result.quarantinedRuns += 1;\n continue;\n }\n }\n if (run.childPid == null && run.launchProtocol == null) {\n console.warn(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'warn',\n msg: 'legacy stale run has no recorded child pid; run remains quarantined',\n taskId: run.taskId,\n runId: run.runId,\n remediation: {\n taskCwd: run.taskCwd,\n owner: run.ownerAlive\n ? `owner PID ${run.workerPid} 仍存活,必须先确认并停止对应进程`\n : 'owner PID 已退出或未记录',\n cancelCommand: run.taskStatus === 'cancelled'\n ? null\n : run.taskCwd == null\n ? `任务没有记录 cwd,请在 Dashboard 取消任务 #${run.taskId}`\n : `在 ${run.taskCwd} 执行: supertask cancel --id ${run.taskId}`,\n abandonCommand: `确认没有遗留 OpenCode 进程后执行: supertask run abandon --id ${run.runId} --confirm ABANDON`,\n },\n }));\n result.quarantinedRuns += 1;\n continue;\n }\n if (run.childPid != null\n && run.childPid > 0\n && run.launchProtocol === TOKEN_GUARDIAN_LAUNCH_PROTOCOL) {\n const expectedExecutable = openCodeExecutable();\n const signalResult = signalRecordedProcessTreeWithResult(\n run.childPid,\n 'SIGKILL',\n expectedExecutable,\n run.launchProtocol,\n run.lockedBy,\n );\n if (signalResult === 'signalled') {\n const exited = await waitForSpawnedProcessTreeExit(run.childPid);\n if (!exited) {\n console.warn(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'warn',\n msg: 'stale child process did not exit; task remains quarantined',\n taskId: run.taskId,\n runId: run.runId,\n childPid: run.childPid,\n }));\n result.quarantinedRuns += 1;\n continue;\n }\n } else if (signalResult !== 'not-running') {\n console.warn(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'warn',\n msg: 'stale child process could not be safely terminated; task remains quarantined',\n taskId: run.taskId,\n runId: run.runId,\n childPid: run.childPid,\n reason: signalResult,\n }));\n result.quarantinedRuns += 1;\n continue;\n }\n }\n\n const recovery = await TaskService.recoverRun(\n run.taskId,\n run.runId,\n `执行所有者退出或心跳超时 (${heartbeatTimeoutMs / 1000}s),Watchdog 已确认子进程结束`,\n );\n if (!recovery) continue;\n result.recoveredRuns += 1;\n gatewayEvents.emitRunFinished({\n runId: run.runId,\n taskId: run.taskId,\n status: 'failed',\n taskStatus: recovery.status,\n cwd: run.taskCwd,\n });\n gatewayEvents.emitTaskChanged({\n taskId: run.taskId,\n cwd: run.taskCwd,\n status: recovery.status,\n reason: 'watchdog-recover',\n });\n if (recovery.status === 'pending' && (recovery.retryAfterMs == null || recovery.retryAfterMs <= Date.now())) {\n gatewayEvents.requestWake('watchdog-recover');\n }\n\n if (recovery.status === 'dead_letter') {\n console.log(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'warn',\n msg: 'task dead_letter',\n taskId: run.taskId,\n runId: run.runId,\n retryCount: recovery.retryCount,\n maxRetries: run.taskMaxRetries,\n }));\n } else {\n console.log(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'warn',\n msg: 'task retry scheduled',\n taskId: run.taskId,\n runId: run.runId,\n retryCount: recovery.retryCount,\n retryAfterMs: recovery.retryAfterMs == null\n ? null\n : Math.max(0, recovery.retryAfterMs - Date.now()),\n }));\n }\n } catch (err) {\n result.failedRuns += 1;\n console.error(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'error',\n msg: 'failed to process stale run',\n runId: run.runId,\n taskId: run.taskId,\n error: err instanceof Error ? err.message : String(err),\n }));\n }\n }\n return result;\n}\n","import { TaskService } from '@core/services/task.service';\nimport { TaskTemplateService } from '@core/services/task-template.service';\n\nexport async function cleanupOldRecords(\n retentionDays: number,\n shouldStop: () => boolean = () => false,\n) {\n const deletedTasks = await TaskService.deleteOlderThan(retentionDays, shouldStop);\n const deletedDelayedTemplates = await TaskTemplateService.deleteExpiredDelayed(\n retentionDays,\n shouldStop,\n );\n\n if (deletedTasks > 0 || deletedDelayedTemplates > 0) {\n console.log(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'info',\n msg: 'cleanup completed',\n deletedTasks,\n deletedDelayedTemplates,\n }));\n }\n\n return deletedTasks;\n}\n","import { checkHeartbeats } from './heartbeat';\nimport { cleanupOldRecords } from './cleanup';\nimport type { GatewayConfig } from '@gateway/config';\nimport {\n markGatewayActivity,\n markGatewayFailure,\n markGatewaySuccess,\n} from '../health';\n\nexport class Watchdog {\n private stopped = false;\n private heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n private cleanupTimer: ReturnType<typeof setInterval> | null = null;\n private checkingHeartbeats = false;\n private cleaning = false;\n private heartbeatCheckPromise: Promise<void> | null = null;\n private cleanupPromise: Promise<void> | null = null;\n\n constructor(\n private cfg: GatewayConfig,\n private isOwnedRun: (taskId: number, runId: number) => boolean = () => false,\n ) {}\n\n start() {\n this.stopped = false;\n markGatewayActivity('watchdog');\n this.heartbeatTimer = setInterval(\n () => this.runHeartbeatCheck(),\n this.cfg.watchdog.checkIntervalMs,\n );\n this.cleanupTimer = setInterval(\n () => this.runCleanup(),\n this.cfg.watchdog.cleanupIntervalMs,\n );\n void this.runHeartbeatCheck();\n }\n\n async stop(): Promise<void> {\n this.stopped = true;\n if (this.heartbeatTimer) {\n clearInterval(this.heartbeatTimer);\n this.heartbeatTimer = null;\n }\n if (this.cleanupTimer) {\n clearInterval(this.cleanupTimer);\n this.cleanupTimer = null;\n }\n await Promise.all([\n this.heartbeatCheckPromise,\n this.cleanupPromise,\n ]);\n }\n\n private runHeartbeatCheck(): Promise<void> {\n if (this.stopped) return Promise.resolve();\n if (this.heartbeatCheckPromise) return this.heartbeatCheckPromise;\n this.checkingHeartbeats = true;\n markGatewayActivity('watchdog');\n const operation = (async () => {\n try {\n const result = await checkHeartbeats(\n this.cfg.watchdog.heartbeatTimeoutMs,\n this.isOwnedRun,\n () => this.stopped,\n );\n if (result.quarantinedRuns > 0 || result.failedRuns > 0) {\n throw new Error(\n `Watchdog 有 ${result.quarantinedRuns} 个隔离 run、${result.failedRuns} 个恢复失败 run`,\n );\n }\n markGatewaySuccess('watchdog');\n } catch (err) {\n markGatewayFailure('watchdog', err);\n console.error(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'error',\n msg: 'watchdog heartbeat check failed',\n error: err instanceof Error ? err.message : String(err),\n }));\n } finally {\n this.checkingHeartbeats = false;\n }\n })();\n this.heartbeatCheckPromise = operation.finally(() => {\n this.heartbeatCheckPromise = null;\n });\n return this.heartbeatCheckPromise;\n }\n\n private runCleanup(): Promise<void> {\n if (this.stopped) return Promise.resolve();\n if (this.cleanupPromise) return this.cleanupPromise;\n this.cleaning = true;\n markGatewayActivity('watchdogCleanup');\n const operation = (async () => {\n try {\n await cleanupOldRecords(\n this.cfg.watchdog.retentionDays,\n () => this.stopped,\n );\n markGatewaySuccess('watchdogCleanup');\n } catch (err) {\n markGatewayFailure('watchdogCleanup', err);\n console.error(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'error',\n msg: 'watchdog cleanup failed',\n error: err instanceof Error ? err.message : String(err),\n }));\n } finally {\n this.cleaning = false;\n }\n })();\n this.cleanupPromise = operation.finally(() => {\n this.cleanupPromise = null;\n });\n return this.cleanupPromise;\n }\n}\n","import {\n DUE_TEMPLATE_BATCH_SIZE,\n getDueTemplates,\n cloneTaskFromTemplate,\n initializeNextRunAt,\n type DueTemplateCursor,\n} from './job-templates';\nimport type { GatewayConfig } from '@gateway/config';\nimport { db, schema } from '@core/db';\nimport { and, asc, eq, gt, isNull } from 'drizzle-orm';\nimport {\n markGatewayActivity,\n markGatewayFailure,\n markGatewaySuccess,\n} from '../health';\nimport { gatewayEvents } from '../events';\n\nexport class Scheduler {\n private stopped = false;\n private ticking = false;\n private tickPromise: Promise<void> | null = null;\n private timer: ReturnType<typeof setInterval> | null = null;\n private dueSweep: { cutoffNow: number; cursor: DueTemplateCursor | null } | null = null;\n\n constructor(private cfg: GatewayConfig) {}\n\n async start() {\n if (!this.cfg.scheduler.enabled) return;\n this.stopped = false;\n markGatewayActivity('scheduler');\n\n await this.initializeTemplates();\n if (this.stopped) return;\n markGatewaySuccess('scheduler');\n\n this.timer = setInterval(() => {\n void this.tick();\n }, this.cfg.scheduler.checkIntervalMs);\n }\n\n async stop(): Promise<void> {\n this.stopped = true;\n if (this.timer) {\n clearInterval(this.timer);\n this.timer = null;\n }\n if (this.tickPromise) {\n await this.tickPromise;\n }\n }\n\n private tick(): Promise<void> {\n if (this.stopped || this.ticking) return this.tickPromise ?? Promise.resolve();\n const run = this.runTick().finally(() => {\n if (this.tickPromise === run) this.tickPromise = null;\n });\n this.tickPromise = run;\n return run;\n }\n\n private async runTick(): Promise<void> {\n if (this.stopped || this.ticking) return;\n markGatewayActivity('scheduler');\n this.ticking = true;\n let hadFailure = false;\n try {\n const sweep = this.dueSweep ?? { cutoffNow: Date.now(), cursor: null };\n const dueTemplates = await getDueTemplates(sweep.cursor, sweep.cutoffNow);\n const lastTemplate = dueTemplates.at(-1);\n for (const tmpl of dueTemplates) {\n if (this.stopped) break;\n try {\n const task = await cloneTaskFromTemplate(tmpl.id, tmpl.nextRunAt!);\n if (task) {\n gatewayEvents.emitTaskChanged({\n taskId: task.id,\n cwd: task.cwd,\n status: task.status,\n reason: 'scheduler-clone',\n });\n gatewayEvents.emitTemplateChanged({\n templateId: tmpl.id,\n reason: 'scheduler-clone',\n });\n gatewayEvents.requestWake('scheduler-clone');\n console.log(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'info',\n msg: 'scheduled task created',\n templateId: tmpl.id,\n taskId: task.id,\n }));\n }\n } catch (err) {\n hadFailure = true;\n markGatewayFailure('scheduler', err);\n console.error(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'error',\n msg: 'failed to clone from template',\n templateId: tmpl.id,\n error: err instanceof Error ? err.message : String(err),\n }));\n }\n }\n if (!this.stopped) {\n this.dueSweep = dueTemplates.length < DUE_TEMPLATE_BATCH_SIZE\n || lastTemplate?.nextRunAt == null\n ? null\n : {\n cutoffNow: sweep.cutoffNow,\n cursor: { nextRunAt: lastTemplate.nextRunAt, id: lastTemplate.id },\n };\n if (!hadFailure) markGatewaySuccess('scheduler');\n }\n } catch (err) {\n markGatewayFailure('scheduler', err);\n console.error(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'error',\n msg: 'scheduler tick failed',\n error: err instanceof Error ? err.message : String(err),\n }));\n } finally {\n this.ticking = false;\n }\n }\n\n private async initializeTemplates() {\n const { taskTemplates } = schema;\n const batchSize = 100;\n let cursor = 0;\n\n while (!this.stopped) {\n const templates = await db\n .select({ id: taskTemplates.id })\n .from(taskTemplates)\n .where(and(\n eq(taskTemplates.enabled, true),\n isNull(taskTemplates.nextRunAt),\n gt(taskTemplates.id, cursor),\n ))\n .orderBy(asc(taskTemplates.id))\n .limit(batchSize);\n if (templates.length === 0) break;\n\n for (const tmpl of templates) {\n if (this.stopped) break;\n await initializeNextRunAt(tmpl.id);\n }\n cursor = templates.at(-1)!.id;\n if (templates.length < batchSize) break;\n await Bun.sleep(0);\n }\n }\n}\n","import { sqlite, closeDb } from '@core/db';\nimport { loadConfig, type GatewayConfig } from './config';\nimport { WorkerEngine, assertWorkerProcessIsolationSupported } from '@worker/index';\nimport { Watchdog } from './watchdog';\nimport { Scheduler } from './scheduler';\nimport { TaskService } from '@core/services/task.service';\nimport { initializeGatewayHealth, resetGatewayHealth } from './health';\nimport { gatewayEvents } from './events';\nimport { identifyGatewayProcess, isProcessAlive } from '@core/process-control';\nimport { getPackageVersion } from '@core/package-version';\n\nconst STALE_THRESHOLD_MS = 30_000;\nconst MAX_TRANSIENT_HEARTBEAT_ERRORS = 2;\nexport const GATEWAY_DASHBOARD_IDLE_TIMEOUT_SECONDS = 60;\n\nexport type LockHeartbeatStatus = 'ok' | 'lost' | 'error';\n\nexport interface LockHeartbeatResult {\n status: LockHeartbeatStatus;\n error?: string;\n}\n\nexport function assertNoOrphanRunningTaskRuns(): void {\n const orphanRunningRun = sqlite.query(\n \"SELECT 1 AS found FROM task_runs AS r LEFT JOIN tasks AS t ON t.id = r.task_id WHERE r.status = 'running' AND t.id IS NULL LIMIT 1\",\n ).get() as { found: number } | null;\n if (orphanRunningRun) {\n throw new Error('检测到失去父任务的孤立 running 执行记录,请先修复数据库再启动 Gateway');\n }\n}\n\nexport interface GatewayShutdownFailure {\n step: string;\n error: string;\n}\n\nexport async function runGatewayShutdownStep(\n failures: GatewayShutdownFailure[],\n step: string,\n operation: () => void | Promise<void>,\n): Promise<void> {\n try {\n await operation();\n } catch (error) {\n failures.push({\n step,\n error: error instanceof Error ? error.message : String(error),\n });\n }\n}\n\nexport function resolveGatewayShutdownExitCode(\n requestedExitCode: number,\n failures: GatewayShutdownFailure[],\n): number {\n return failures.length > 0 ? 1 : requestedExitCode;\n}\n\nexport function acquireLock(): boolean {\n const now = Date.now();\n const pid = process.pid;\n\n try {\n sqlite.exec('BEGIN IMMEDIATE');\n\n const existing = sqlite.prepare('SELECT id, pid, heartbeat_at FROM gateway_lock WHERE id = 1').get() as {\n id: number;\n pid: number;\n heartbeat_at: number;\n } | undefined;\n\n if (existing) {\n const lockHolderAlive = existing.pid !== pid && isProcessAlive(existing.pid);\n if (lockHolderAlive) {\n const identity = identifyGatewayProcess(existing.pid);\n const lockIsFresh = now - existing.heartbeat_at < STALE_THRESHOLD_MS;\n if (lockIsFresh || identity !== 'mismatch') {\n sqlite.exec('ROLLBACK');\n console.error(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'fatal',\n msg: 'another Gateway instance is already running',\n existingPid: existing.pid,\n identity,\n }));\n return false;\n }\n\n console.warn(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'warn',\n msg: 'taking over stale Gateway lock from a reused PID',\n existingPid: existing.pid,\n }));\n }\n\n sqlite.exec('DELETE FROM gateway_lock WHERE id = 1');\n }\n\n sqlite.exec(\n 'INSERT INTO gateway_lock (id, pid, acquired_at, heartbeat_at, ready_at) VALUES (1, ?, ?, ?, NULL)',\n [pid, now, now],\n );\n sqlite.exec('COMMIT');\n return true;\n } catch (err) {\n try { sqlite.exec('ROLLBACK'); } catch {}\n console.error(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'fatal',\n msg: 'failed to acquire lock',\n error: err instanceof Error ? err.message : String(err),\n }));\n return false;\n }\n}\n\nexport function releaseLock() {\n try {\n sqlite.exec('DELETE FROM gateway_lock WHERE pid = ?', [process.pid]);\n } catch {}\n}\n\nexport function updateLockHeartbeatResult(): LockHeartbeatResult {\n try {\n const result = sqlite.query(\n 'UPDATE gateway_lock SET heartbeat_at = ? WHERE id = 1 AND pid = ?',\n ).run(Date.now(), process.pid);\n return result.changes === 1 ? { status: 'ok' } : { status: 'lost' };\n } catch (error) {\n return {\n status: 'error',\n error: error instanceof Error ? error.message : String(error),\n };\n }\n}\n\nexport function updateLockHeartbeat(): boolean {\n return updateLockHeartbeatResult().status === 'ok';\n}\n\nexport interface LockHeartbeatTracker {\n record(result: LockHeartbeatResult, now?: number): 'ok' | 'retry' | 'lost';\n}\n\nconst TRANSIENT_LOCK_HEARTBEAT_ERROR_PATTERN = /\\b(SQLITE_BUSY|SQLITE_LOCKED)\\b|database is locked|database table is locked/i;\n\nexport function isTransientLockHeartbeatError(error?: string): boolean {\n return typeof error === 'string' && TRANSIENT_LOCK_HEARTBEAT_ERROR_PATTERN.test(error);\n}\n\nexport function createLockHeartbeatTracker(\n options: {\n maxTransientErrors?: number;\n staleThresholdMs?: number;\n now?: number;\n } = {},\n): LockHeartbeatTracker {\n const maxTransientErrors = options.maxTransientErrors ?? MAX_TRANSIENT_HEARTBEAT_ERRORS;\n const staleThresholdMs = options.staleThresholdMs ?? STALE_THRESHOLD_MS;\n let consecutiveTransientErrors = 0;\n let lastOkAt = options.now ?? Date.now();\n\n return {\n record(result: LockHeartbeatResult, now = Date.now()): 'ok' | 'retry' | 'lost' {\n if (result.status === 'ok') {\n consecutiveTransientErrors = 0;\n lastOkAt = now;\n return 'ok';\n }\n if (result.status === 'lost') {\n return 'lost';\n }\n if (!isTransientLockHeartbeatError(result.error)) {\n return 'lost';\n }\n consecutiveTransientErrors += 1;\n if (consecutiveTransientErrors <= maxTransientErrors && now - lastOkAt < staleThresholdMs) {\n return 'retry';\n }\n return 'lost';\n },\n };\n}\n\nfunction markGatewayReady() {\n const now = Date.now();\n const result = sqlite.query(\n 'UPDATE gateway_lock SET heartbeat_at = ?, ready_at = ?, version = ? WHERE id = 1 AND pid = ?',\n ).run(now, now, getPackageVersion(), process.pid);\n if (result.changes !== 1) {\n throw new Error('Gateway 在就绪前失去了数据库单实例锁');\n }\n}\n\nfunction markGatewayNotReady() {\n try {\n sqlite.exec('UPDATE gateway_lock SET ready_at = NULL WHERE pid = ?', [process.pid]);\n } catch {}\n}\n\nexport interface GatewayDashboardServer {\n stop(closeActiveConnections?: boolean): void | Promise<void>;\n}\n\nexport interface GatewayRuntimeDeps {\n assertIsolationSupported?: () => void;\n loadConfig?: () => GatewayConfig;\n acquireLock?: () => boolean;\n releaseLock?: () => void;\n updateLockHeartbeatResult?: () => LockHeartbeatResult;\n markGatewayReady?: () => void;\n markGatewayNotReady?: () => void;\n assertNoOrphanRunningTaskRuns?: () => void;\n resetOrphanRunningToPending?: () => Promise<number>;\n resolveBlockedDependencies?: () => Promise<number>;\n interruptRun?: (taskId: number, runId: number, reason: string) => Promise<boolean>;\n closeDb?: () => void;\n createWorker?: (cfg: GatewayConfig) => Pick<WorkerEngine, 'start' | 'stop' | 'ownsRun'>;\n createWatchdog?: (\n cfg: GatewayConfig,\n ownsRun: (taskId: number, runId: number) => boolean,\n ) => Pick<Watchdog, 'start' | 'stop'>;\n createScheduler?: (cfg: GatewayConfig) => Pick<Scheduler, 'start' | 'stop'>;\n startDashboard?: (cfg: GatewayConfig) => Promise<GatewayDashboardServer>;\n heartbeatIntervalMs?: number;\n registerProcessHandlers?: boolean;\n exit?: (code: number) => void;\n onReadyForTest?: (controls: {\n shutdown: (signal: string, exitCode?: number) => Promise<void>;\n runHeartbeatTick: () => void;\n }) => void;\n}\n\nexport async function runGatewayMain(deps: GatewayRuntimeDeps = {}): Promise<void> {\n const assertIsolation = deps.assertIsolationSupported ?? assertWorkerProcessIsolationSupported;\n const loadGatewayConfig = deps.loadConfig ?? loadConfig;\n const acquireGatewayLock = deps.acquireLock ?? acquireLock;\n const releaseGatewayLock = deps.releaseLock ?? releaseLock;\n const checkLockHeartbeat = deps.updateLockHeartbeatResult ?? updateLockHeartbeatResult;\n const markReady = deps.markGatewayReady ?? markGatewayReady;\n const markNotReady = deps.markGatewayNotReady ?? markGatewayNotReady;\n const checkOrphanRuns = deps.assertNoOrphanRunningTaskRuns ?? assertNoOrphanRunningTaskRuns;\n const resetOrphans = deps.resetOrphanRunningToPending ?? (() => TaskService.resetOrphanRunningToPending());\n const resolveDeps = deps.resolveBlockedDependencies ?? (() => TaskService.resolveBlockedDependencies());\n const interruptRun = deps.interruptRun ?? ((taskId, runId, reason) => TaskService.interruptRun(taskId, runId, reason));\n const closeDatabase = deps.closeDb ?? closeDb;\n const createWorker = deps.createWorker ?? ((cfg) => new WorkerEngine(cfg));\n const createWatchdog = deps.createWatchdog ?? ((cfg, ownsRun) => new Watchdog(cfg, ownsRun));\n const createScheduler = deps.createScheduler ?? ((cfg) => new Scheduler(cfg));\n const exitProcess = deps.exit ?? ((code: number) => { process.exit(code); });\n const heartbeatIntervalMs = deps.heartbeatIntervalMs ?? 10_000;\n const registerProcessHandlers = deps.registerProcessHandlers ?? true;\n\n console.log(JSON.stringify({ ts: new Date().toISOString(), level: 'info', msg: 'SuperTask Gateway starting', pid: process.pid }));\n\n assertIsolation();\n // 配置校验必须在占锁前执行,防止非法配置抛错时泄漏 gateway_lock。\n const cfg = loadGatewayConfig();\n\n if (!acquireGatewayLock()) {\n exitProcess(1);\n return;\n }\n\n const worker = createWorker(cfg);\n const watchdog = createWatchdog(cfg, (taskId, runId) => worker.ownsRun(taskId, runId));\n const scheduler = createScheduler(cfg);\n let heartbeatTimer: ReturnType<typeof setInterval> | null = null;\n let dashboardServer: GatewayDashboardServer | null = null;\n let shuttingDown = false;\n const heartbeatTracker = createLockHeartbeatTracker();\n\n const shutdown = async (signal: string, exitCode = 0) => {\n if (shuttingDown) return;\n shuttingDown = true;\n const failures: GatewayShutdownFailure[] = [];\n\n try {\n console.log(JSON.stringify({ ts: new Date().toISOString(), level: 'info', msg: `received ${signal}, shutting down...` }));\n\n if (heartbeatTimer) {\n clearInterval(heartbeatTimer);\n heartbeatTimer = null;\n }\n markNotReady();\n await runGatewayShutdownStep(failures, 'dashboard.stop', () => {\n const server = dashboardServer;\n dashboardServer = null;\n return server?.stop(true);\n });\n await runGatewayShutdownStep(failures, 'scheduler.stop', () => scheduler.stop());\n await runGatewayShutdownStep(failures, 'watchdog.stop', () => watchdog.stop());\n\n let interruptedRuns: Awaited<ReturnType<WorkerEngine['stop']>> = [];\n await runGatewayShutdownStep(failures, 'worker.stop', async () => {\n interruptedRuns = await worker.stop(cfg.worker.shutdownGracePeriodMs);\n });\n\n let resetCount = 0;\n for (const run of interruptedRuns) {\n await runGatewayShutdownStep(\n failures,\n `task.interrupt:${run.taskId}:${run.runId}`,\n async () => {\n if (await interruptRun(\n run.taskId,\n run.runId,\n 'Gateway shutdown after child exit',\n )) {\n resetCount += 1;\n }\n },\n );\n }\n if (resetCount > 0) {\n console.log(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'info',\n msg: 'reset confirmed interrupted tasks to pending',\n count: resetCount,\n }));\n }\n\n await runGatewayShutdownStep(failures, 'lock.release', () => releaseGatewayLock());\n await runGatewayShutdownStep(failures, 'events.reset', () => gatewayEvents.reset());\n await runGatewayShutdownStep(failures, 'health.reset', () => resetGatewayHealth());\n await runGatewayShutdownStep(failures, 'database.close', () => closeDatabase());\n\n if (failures.length > 0) {\n console.error(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'error',\n msg: 'Gateway stopped with shutdown failures',\n failures,\n }));\n } else {\n console.log(JSON.stringify({ ts: new Date().toISOString(), level: 'info', msg: 'Gateway stopped' }));\n }\n } finally {\n exitProcess(resolveGatewayShutdownExitCode(exitCode, failures));\n }\n };\n\n const onSigterm = () => { void shutdown('SIGTERM'); };\n const onSigint = () => { void shutdown('SIGINT'); };\n const onUncaughtException = (err: Error) => {\n console.error(JSON.stringify({ ts: new Date().toISOString(), level: 'fatal', msg: 'uncaughtException', error: err.message, stack: err.stack }));\n void shutdown('uncaughtException', 1);\n };\n const onUnhandledRejection = (reason: unknown) => {\n console.error(JSON.stringify({ ts: new Date().toISOString(), level: 'fatal', msg: 'unhandledRejection', reason: String(reason) }));\n void shutdown('unhandledRejection', 1);\n };\n\n if (registerProcessHandlers) {\n process.on('SIGTERM', onSigterm);\n process.on('SIGINT', onSigint);\n process.on('uncaughtException', onUncaughtException);\n process.on('unhandledRejection', onUnhandledRejection);\n }\n\n const runHeartbeatTick = () => {\n const result = checkLockHeartbeat();\n const decision = heartbeatTracker.record(result);\n if (decision === 'ok') return;\n if (decision === 'retry') {\n console.warn(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'warn',\n msg: 'transient database lock heartbeat error, will retry within stale threshold',\n pid: process.pid,\n error: result.error,\n }));\n return;\n }\n console.error(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'fatal',\n msg: 'Gateway lost its database lock and will stop',\n pid: process.pid,\n error: result.error,\n }));\n void shutdown('database lock lost', 1);\n };\n\n heartbeatTimer = setInterval(runHeartbeatTick, heartbeatIntervalMs);\n heartbeatTimer.unref();\n\n deps.onReadyForTest?.({ shutdown, runHeartbeatTick });\n\n try {\n checkOrphanRuns();\n const recoveredOrphans = await resetOrphans();\n if (shuttingDown) return;\n if (recoveredOrphans > 0) {\n console.log(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'warn',\n msg: 'reset orphan running tasks to pending',\n count: recoveredOrphans,\n }));\n }\n await resolveDeps();\n if (shuttingDown) return;\n\n initializeGatewayHealth({\n workerPollIntervalMs: cfg.worker.pollIntervalMs,\n schedulerEnabled: cfg.scheduler.enabled,\n schedulerCheckIntervalMs: cfg.scheduler.checkIntervalMs,\n watchdogCheckIntervalMs: cfg.watchdog.checkIntervalMs,\n watchdogCleanupIntervalMs: cfg.watchdog.cleanupIntervalMs,\n });\n\n await scheduler.start();\n if (shuttingDown) return;\n\n if (cfg.dashboard.enabled) {\n if (deps.startDashboard) {\n dashboardServer = await deps.startDashboard(cfg);\n } else {\n const { dashboardApp, setDashboardRuntimeConfig } = await import('@web/index');\n if (shuttingDown) return;\n setDashboardRuntimeConfig(cfg);\n dashboardServer = Bun.serve({\n hostname: '127.0.0.1',\n port: cfg.dashboard.port,\n fetch: dashboardApp.fetch,\n idleTimeout: GATEWAY_DASHBOARD_IDLE_TIMEOUT_SECONDS,\n });\n }\n if (shuttingDown) {\n await dashboardServer?.stop(true);\n dashboardServer = null;\n return;\n }\n console.log(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'info',\n msg: 'Dashboard started',\n url: `http://localhost:${cfg.dashboard.port}`,\n }));\n }\n\n if (shuttingDown) return;\n watchdog.start();\n worker.start();\n markReady();\n\n console.log(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'info',\n msg: 'Gateway started',\n maxConcurrency: cfg.worker.maxConcurrency,\n schedulerEnabled: cfg.scheduler.enabled,\n }));\n } catch (error) {\n console.error(JSON.stringify({\n ts: new Date().toISOString(),\n level: 'fatal',\n msg: 'Gateway startup failed',\n error: error instanceof Error ? error.message : String(error),\n }));\n await shutdown('startup failure', 1);\n }\n}\n\nasync function main() {\n await runGatewayMain();\n}\n\nexport { main };\n\nif (import.meta.main) {\n main();\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAEA,SAAS,aAAgC;AAczC,SAAS,qBAAqB;AAC9B,SAAS,kBAAkB;AAC3B,SAAS,SAAS,YAAY;AAC9B,SAAS,kBAAkB;;;ACnB3B,IAAM,qBAAqB;AAWpB,IAAM,YAAN,MAAgB;AAAA,EAOnB,YACqB,UACA,aACA,QACnB;AAHmB;AACA;AACA;AAAA,EAClB;AAAA,EAHkB;AAAA,EACA;AAAA,EACA;AAAA,EATb,QAAkB,CAAC;AAAA,EACnB,OAAO;AAAA,EACP,aAAa;AAAA,EACJ,UAAwC,EAAE,QAAQ,IAAI,QAAQ,GAAG;AAAA,EAC1E,YAA2B;AAAA,EAQnC,KAAK,QAAsB,OAAqB;AAC5C,UAAM,SAAS,KAAK,QAAQ,MAAM,IAAI,OAAO,MAAM,IAAI;AACvD,QAAI,OA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AAAA,UACV,MAAM,IAAI,UAAU;AAAA,UACpB,OAAO,aAAa;AAAA,UACpB,aAAa;AAAA,QACjB,CAAC;AAAA,MACL;AACA,UAAI,cAAc;AACd,cAAM,iBAAiB,KAAK,IAAI;AAChC,0BAAkB;AAClB;AAAA,MACJ;AACA,cAAQ,IAAI,KAAK,UAAU;AAAA,QACvB,KAAI,oBAAI,KAAK,GAAE,YAAY;AAAA,QAC3B,OAAO;AAAA,QACP,KAAK;AAAA,QACL,KAAK,oBAAoB,IAAI,UAAU,IAAI;AAAA,MAC/C,CAAC,CAAC;AAAA,IACN;AAEA,QAAI,aAAc;AAClB,aAAS,MAAM;AACf,WAAO,MAAM;AACb,cAAU;AAEV,YAAQ,IAAI,KAAK,UAAU;AAAA,MACvB,KAAI,oBAAI,KAAK,GAAE,YAAY;AAAA,MAC3B,OAAO;AAAA,MACP,KAAK;AAAA,MACL,gBAAgB,IAAI,OAAO;AAAA,MAC3B,kBAAkB,IAAI,UAAU;AAAA,IACpC,CAAC,CAAC;AAAA,EACN,SAAS,OAAO;AACZ,YAAQ,MAAM,KAAK,UAAU;AAAA,MACzB,KAAI,oBAAI,KAAK,GAAE,YAAY;AAAA,MAC3B,OAAO;AAAA,MACP,KAAK;AAAA,MACL,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;AAAA,IAChE,CAAC,CAAC;AACF,UAAM,SAAS,mBAAmB,CAAC;AAAA,EACvC;AACJ;AAEA,eAAe,OAAO;AAClB,QAAM,eAAe;AACzB;AAIA,IAAI,YAAY,MAAM;AAClB,OAAK;AACT;","names":["pid","output","log","cfg"]}
@@ -1,15 +0,0 @@
1
- #!/usr/bin/env bun
2
-
3
- import {
4
- LegacyRunAbandonConflictError,
5
- TaskRunService
6
- } from "./chunk-5VKFECHP.js";
7
- import "./chunk-ZBH7YWXF.js";
8
- import "./chunk-YB7MYTE5.js";
9
- import "./chunk-YGELD2E5.js";
10
- import "./chunk-3PIYMBV3.js";
11
- export {
12
- LegacyRunAbandonConflictError,
13
- TaskRunService
14
- };
15
- //# sourceMappingURL=task-run.service-QMDINJKG.js.map
@@ -1,12 +0,0 @@
1
- #!/usr/bin/env bun
2
-
3
- import {
4
- TaskTemplateService
5
- } from "./chunk-CMEP6IB4.js";
6
- import "./chunk-EQWICVCJ.js";
7
- import "./chunk-YGELD2E5.js";
8
- import "./chunk-3PIYMBV3.js";
9
- export {
10
- TaskTemplateService
11
- };
12
- //# sourceMappingURL=task-template.service-SZBKGLCB.js.map