process-lifecycle.ts 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  1. const processGuardInstalled = new WeakSet<object>();
  2. const OUTPUT_CLOSED_ERROR_CODES = new Set([
  3. "EPIPE",
  4. "EIO",
  5. "ENXIO",
  6. "EBADF",
  7. "ERR_STREAM_DESTROYED",
  8. ]);
  9. /**
  10. * REPL cell 的同步错误由 NodeReplSession 兜底,但 fire-and-forget 的异步错误
  11. * (如未 await 的 tab.* 调用在 turn 中断时被 reject)会按 Node 默认策略击穿整个 server
  12. * 进程。子进程一死,会话内 Browser Use 从此不可用。这里把异步错误降级为 stderr 日志:
  13. * runtime 状态保留、协议 stdout 不受影响。
  14. *
  15. * 父进程退出后 stderr 会报 EPIPE。旧 handler 又把 EPIPE 堆栈写回同一条
  16. * stderr,形成 EPIPE -> uncaughtException -> stderr.write -> EPIPE 的无限循环。
  17. * 输出管道关闭表示 MCP client 已不可达,必须直接进入 shutdown,不能继续写诊断。
  18. */
  19. export function installNodeReplProcessGuards(input: {
  20. onOutputClosed: (error: Error) => void;
  21. process: Pick<NodeJS.Process, "on">;
  22. writeStderr: (text: string) => void;
  23. }): void {
  24. if (processGuardInstalled.has(input.process)) return;
  25. processGuardInstalled.add(input.process);
  26. let outputClosed = false;
  27. const describe = (reason: unknown): string =>
  28. reason instanceof Error ? (reason.stack ?? reason.message) : String(reason);
  29. const report = (kind: "uncaughtException" | "unhandledRejection", reason: unknown): void => {
  30. if (outputClosed) return;
  31. if (isOutputClosedError(reason)) {
  32. outputClosed = true;
  33. input.onOutputClosed(reason);
  34. return;
  35. }
  36. try {
  37. input.writeStderr(`node_repl ${kind} (process kept alive): ${describe(reason)}\n`);
  38. } catch (error) {
  39. if (!isOutputClosedError(error)) throw error;
  40. outputClosed = true;
  41. input.onOutputClosed(error);
  42. }
  43. };
  44. input.process.on("unhandledRejection", (reason) => {
  45. report("unhandledRejection", reason);
  46. });
  47. input.process.on("uncaughtException", (error) => {
  48. report("uncaughtException", error);
  49. });
  50. }
  51. function isOutputClosedError(error: unknown): error is Error {
  52. if (!(error instanceof Error)) return false;
  53. const code = (error as NodeJS.ErrnoException).code;
  54. return typeof code === "string" && OUTPUT_CLOSED_ERROR_CODES.has(code);
  55. }
  56. export function installNodeReplShutdownTriggers(input: {
  57. process: Pick<NodeJS.Process, "once">;
  58. shutdown: () => void;
  59. stdin: Pick<NodeJS.ReadStream, "once">;
  60. }): void {
  61. let shutdownStarted = false;
  62. const shutdownOnce = () => {
  63. if (shutdownStarted) return;
  64. shutdownStarted = true;
  65. input.shutdown();
  66. };
  67. // MCP SDK 的 stdio transport 不监听 stdin end/close。父进程异常退出时 runtime
  68. // 因此收不到生命周期终点并沦为孤儿进程。
  69. input.stdin.once("end", shutdownOnce);
  70. input.stdin.once("close", shutdownOnce);
  71. input.process.once("SIGINT", shutdownOnce);
  72. input.process.once("SIGTERM", shutdownOnce);
  73. }
  74. export async function isDirectMcpEntrypoint(
  75. importMetaUrl: string,
  76. argvPath: string | undefined,
  77. ): Promise<boolean> {
  78. if (!argvPath) return false;
  79. try {
  80. // macOS 的 /tmp、/var 等路径会解析到 /private/...;直接比较 file URL 会让
  81. // stdio 子进程误判成“被 import”,main 未启动且无错误退出。异步 realpath 同时兼容
  82. // symlink 安装目录,并避免在模块求值路径引入同步文件 IO。
  83. const [modulePath, executablePath] = await Promise.all([
  84. realpath(fileURLToPath(importMetaUrl)),
  85. realpath(argvPath),
  86. ]);
  87. return modulePath === executablePath;
  88. } catch {
  89. return false;
  90. }
  91. }
  92. import { realpath } from "node:fs/promises";
  93. import { fileURLToPath } from "node:url";