File size: 4,171 Bytes
35743bd
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
import { spawn, type ChildProcess } from "child_process";
import fs from "fs/promises";
import fsSync from "fs";
import path from "path";
import os from "os";
import { setToolStatus, getVersionManagerTool } from "@/lib/db/versionManager";

const DEFAULT_PORT = 8317;
const GRACEFUL_TIMEOUT_MS = 5000;

function defaultConfigDir(): string {
  return process.env.CLIPROXYAPI_CONFIG_DIR || path.join(os.homedir(), ".cli-proxy-api");
}

async function writeConfig(
  configDir: string,
  port: number,
  overrides?: Record<string, unknown>
): Promise<string> {
  await fs.mkdir(configDir, { recursive: true });
  const configPath = path.join(configDir, "config.yaml");
  const config = `port: ${port}
host: 127.0.0.1
log_level: warn
`;
  await fs.writeFile(configPath, config);
  return configPath;
}

export async function startProcess(
  binaryPath: string,
  port?: number,
  configDir?: string
): Promise<{ pid: number; port: number }> {
  const existing = await getVersionManagerTool("cliproxyapi");
  if (existing?.pid) {
    const alive = isProcessRunning(existing.pid);
    if (alive) return { pid: existing.pid, port: existing.port };
  }

  const actualPort = port || DEFAULT_PORT;
  const actualConfigDir = configDir || defaultConfigDir();
  await writeConfig(actualConfigDir, actualPort);

  const child = spawn(binaryPath, ["-c", path.join(actualConfigDir, "config.yaml")], {
    detached: false,
    stdio: ["ignore", "pipe", "pipe"],
    env: { ...process.env },
  });

  child.stdout?.on("data", () => {});
  child.stderr?.on("data", () => {});

  child.on("error", async (err) => {
    await setToolStatus("cliproxyapi", "error", undefined, err.message);
  });

  child.on("exit", async (code) => {
    if (code !== 0 && code !== null) {
      await setToolStatus("cliproxyapi", "stopped", undefined, `Process exited with code ${code}`);
    }
  });

  const pid = child.pid;
  await setToolStatus("cliproxyapi", "running", pid);

  return { pid, port: actualPort };
}

export function isProcessRunning(pid: number): boolean {
  try {
    process.kill(pid, 0);
    return true;
  } catch {
    return false;
  }
}

export function stopProcess(pid: number): Promise<void> {
  return new Promise((resolve) => {
    if (!isProcessRunning(pid)) {
      resolve();
      return;
    }

    try {
      process.kill(pid, "SIGTERM");
    } catch {
      resolve();
      return;
    }

    const timer = setTimeout(() => {
      try {
        process.kill(pid, "SIGKILL");
      } catch {}
      clearInterval(check);
      resolve();
    }, GRACEFUL_TIMEOUT_MS);

    const check = setInterval(() => {
      if (!isProcessRunning(pid)) {
        clearTimeout(timer);
        clearInterval(check);
        resolve();
      }
    }, 200);
  });
}

export async function restartProcess(
  binaryPath: string,
  port?: number,
  configDir?: string,
  currentPid?: number | null
): Promise<{ pid: number; port: number }> {
  if (currentPid) {
    await stopProcess(currentPid);
    await new Promise((r) => setTimeout(r, 500));
  }
  return startProcess(binaryPath, port, configDir);
}

export async function getProcessInfo(pid: number): Promise<{
  pid: number;
  alive: boolean;
  memoryUsage?: number;
}> {
  if (!isProcessRunning(pid)) {
    return { pid, alive: false };
  }

  try {
    if (process.platform === "linux" || process.platform === "android") {
      const statusFile = `/proc/${pid}/status`;
      const content = await fs.readFile(statusFile, "utf-8");
      const match = content.match(/VmRSS:\s+(\d+)\s+kB/);
      if (match) {
        return { pid, alive: true, memoryUsage: parseInt(match[1], 10) * 1024 };
      }
    } else if (process.platform === "darwin") {
      const { execFile } = await import("child_process");
      const { promisify } = await import("util");
      const execFileAsync = promisify(execFile);
      const { stdout } = await execFileAsync("ps", ["-o", "rss=", "-p", String(pid)]);
      const rssKb = parseInt(stdout.trim(), 10);
      if (!isNaN(rssKb)) {
        return { pid, alive: true, memoryUsage: rssKb * 1024 };
      }
    }
    return { pid, alive: true };
  } catch {
    return { pid, alive: true };
  }
}