runner.mjs 8.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272
  1. #!/usr/bin/env node
  2. import { spawn } from "node:child_process";
  3. import { randomBytes } from "node:crypto";
  4. import { access, readFile } from "node:fs/promises";
  5. import { createServer } from "node:net";
  6. import { networkInterfaces } from "node:os";
  7. import { dirname, join, resolve } from "node:path";
  8. import { fileURLToPath, pathToFileURL } from "node:url";
  9. const root = resolve(dirname(fileURLToPath(import.meta.url)), "..");
  10. const { version } = JSON.parse(await readFile(join(root, "package.json"), "utf8"));
  11. const serverEntry = join(root, "server", "entry-http.js");
  12. const webRoot = join(root, "web");
  13. const agentEntry = join(root, "agent", "zcode.cjs");
  14. function usage() {
  15. return `Usage:
  16. zcode --web [--host <host>] [--port <port>] [--workspace <path>] [--open|--no-open] [--token <token>|--no-token]
  17. zcode --version
  18. `;
  19. }
  20. function readArgValue(argv, arg, index) {
  21. if (arg.includes("=")) {
  22. return { nextIndex: index, value: arg.slice(arg.indexOf("=") + 1) };
  23. }
  24. const value = argv[index + 1];
  25. if (!value || value.startsWith("--")) {
  26. throw new Error(`Missing value for ${arg}`);
  27. }
  28. return { nextIndex: index + 1, value };
  29. }
  30. function parseArgs(argv) {
  31. const options = {
  32. command: "serve",
  33. host: "127.0.0.1",
  34. open: undefined,
  35. port: undefined,
  36. token: undefined,
  37. tokenEnabled: undefined,
  38. workspace: process.cwd(),
  39. };
  40. for (let index = 0; index < argv.length; index += 1) {
  41. const arg = argv[index];
  42. if (arg === "--help" || arg === "-h") {
  43. options.command = "help";
  44. continue;
  45. }
  46. if (arg === "--version" || arg === "-v") {
  47. options.command = "version";
  48. continue;
  49. }
  50. if (arg === "--host" || arg.startsWith("--host=")) {
  51. const parsed = readArgValue(argv, arg, index);
  52. options.host = parsed.value;
  53. index = parsed.nextIndex;
  54. continue;
  55. }
  56. if (arg === "--port" || arg.startsWith("--port=")) {
  57. const parsed = readArgValue(argv, arg, index);
  58. options.port = Number(parsed.value);
  59. if (!Number.isInteger(options.port) || options.port < 0 || options.port > 65535) {
  60. throw new Error("--port must be an integer between 0 and 65535");
  61. }
  62. index = parsed.nextIndex;
  63. continue;
  64. }
  65. if (arg === "--workspace" || arg.startsWith("--workspace=")) {
  66. const parsed = readArgValue(argv, arg, index);
  67. options.workspace = resolve(parsed.value);
  68. index = parsed.nextIndex;
  69. continue;
  70. }
  71. if (arg === "--open") {
  72. options.open = true;
  73. continue;
  74. }
  75. if (arg === "--no-open") {
  76. options.open = false;
  77. continue;
  78. }
  79. if (arg === "--token" || arg.startsWith("--token=")) {
  80. const parsed = readArgValue(argv, arg, index);
  81. options.token = parsed.value;
  82. options.tokenEnabled = true;
  83. index = parsed.nextIndex;
  84. continue;
  85. }
  86. if (arg === "--no-token") {
  87. options.tokenEnabled = false;
  88. continue;
  89. }
  90. throw new Error(`Unknown option "${arg}".\n${usage()}`);
  91. }
  92. return options;
  93. }
  94. function isLocalHost(host) {
  95. return host === "127.0.0.1" || host === "localhost" || host === "::1";
  96. }
  97. function shouldProtectHost(host) {
  98. return !isLocalHost(host);
  99. }
  100. function createToken() {
  101. return randomBytes(24).toString("base64url");
  102. }
  103. function pickPort(host) {
  104. return new Promise((resolvePort, reject) => {
  105. const server = createServer();
  106. server.once("error", reject);
  107. server.listen(0, host, () => {
  108. const address = server.address();
  109. const port = typeof address === "object" && address ? address.port : 0;
  110. server.close((error) => {
  111. if (error) {
  112. reject(error);
  113. return;
  114. }
  115. resolvePort(port);
  116. });
  117. });
  118. });
  119. }
  120. function formatUrl(host, port, token) {
  121. const displayHost = host === "0.0.0.0" || host === "::" ? "127.0.0.1" : host;
  122. const base = `http://${displayHost}:${port}/`;
  123. return token ? `${base}?token=${encodeURIComponent(token)}` : base;
  124. }
  125. function networkUrls(port, token) {
  126. const urls = [];
  127. for (const entries of Object.values(networkInterfaces())) {
  128. for (const entry of entries ?? []) {
  129. if (entry.internal || entry.family !== "IPv4") {
  130. continue;
  131. }
  132. const base = `http://${entry.address}:${port}/`;
  133. urls.push(token ? `${base}?token=${encodeURIComponent(token)}` : base);
  134. }
  135. }
  136. return urls;
  137. }
  138. function openBrowser(url) {
  139. const command =
  140. process.platform === "darwin" ? "open" : process.platform === "win32" ? "cmd" : "xdg-open";
  141. const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
  142. const child = spawn(command, args, {
  143. detached: true,
  144. stdio: "ignore",
  145. });
  146. child.unref();
  147. }
  148. async function assertRuntimeFiles() {
  149. for (const file of [serverEntry, agentEntry, webRoot]) {
  150. await access(file).catch((cause) => {
  151. throw new Error(`Missing runtime file: ${file}`, { cause });
  152. });
  153. }
  154. }
  155. async function serve(options) {
  156. await assertRuntimeFiles();
  157. const port = options.port && options.port > 0 ? options.port : await pickPort(options.host);
  158. const protect = options.tokenEnabled ?? shouldProtectHost(options.host);
  159. const token = protect ? (options.token ?? createToken()) : "";
  160. const open = options.open ?? isLocalHost(options.host);
  161. const localUrl = formatUrl(options.host, port, token);
  162. const child = spawn(process.execPath, [serverEntry], {
  163. cwd: options.workspace,
  164. env: {
  165. ...process.env,
  166. PORT: String(port),
  167. ZCODE_AGENT_SERVER_ARGS_JSON: JSON.stringify([agentEntry, "app-server", "--stdio"]),
  168. ZCODE_AGENT_SERVER_COMMAND: process.execPath,
  169. ZCODE_SERVER_HOST: options.host,
  170. ZCODE_SERVER_WORKSPACE: options.workspace,
  171. ZCODE_WEB_STATIC_ROOT: webRoot,
  172. // 显式关闭 token 时必须清空继承值,否则 --no-token 仍会开启后端鉴权。
  173. ZCODE_SERVER_AUTH_TOKEN: token,
  174. },
  175. stdio: ["ignore", "pipe", "pipe"],
  176. });
  177. let shuttingDown = false;
  178. child.on("error", (error) => {
  179. console.error(`Unable to start Web server: ${error.message}`);
  180. process.exit(1);
  181. });
  182. child.stdout.on("data", (chunk) => process.stdout.write(chunk));
  183. child.stderr.on("data", (chunk) => process.stderr.write(chunk));
  184. child.on("exit", (code, signal) => {
  185. if (shuttingDown) {
  186. process.exit(0);
  187. }
  188. if (signal) {
  189. process.exit(1);
  190. }
  191. process.exit(code ?? 0);
  192. });
  193. console.log("");
  194. console.log("ZCode Web is running");
  195. console.log(`Local: ${localUrl}`);
  196. if (options.host === "0.0.0.0" || options.host === "::") {
  197. for (const url of networkUrls(port, token)) {
  198. console.log(`Network: ${url}`);
  199. }
  200. }
  201. console.log("Press Ctrl+C to stop.");
  202. console.log("");
  203. if (open) {
  204. setTimeout(() => openBrowser(localUrl), 500);
  205. }
  206. const shutdown = () => {
  207. if (shuttingDown) {
  208. return;
  209. }
  210. shuttingDown = true;
  211. child.kill("SIGTERM");
  212. setTimeout(() => process.exit(0), 1500).unref();
  213. };
  214. process.on("SIGINT", shutdown);
  215. process.on("SIGTERM", shutdown);
  216. if (process.stdin.isTTY) {
  217. process.stdin.setRawMode?.(true);
  218. process.stdin.resume();
  219. process.stdin.on("data", (chunk) => {
  220. if (chunk.includes(3)) {
  221. shutdown();
  222. }
  223. });
  224. process.stdin.on("error", () => {
  225. if (!shuttingDown) {
  226. shutdown();
  227. }
  228. });
  229. }
  230. }
  231. try {
  232. const argv = process.argv.slice(2);
  233. if (argv.length === 1 && ["--version", "-v"].includes(argv[0])) {
  234. console.log(version);
  235. } else if (argv[0] === "--web") {
  236. const options = parseArgs(argv.slice(1));
  237. if (options.command === "help") console.log(usage());
  238. else if (options.command === "version") console.log(version);
  239. else await serve(options);
  240. } else {
  241. if (argv.length === 1 && ["--help", "-h"].includes(argv[0])) {
  242. console.log("Web mode: zcode --web [options] (zcode --web --help for details)\n");
  243. }
  244. // CLI 自启动子进程依赖 argv[1];统一指向真正的 Agent 入口,保留 TTY 与所有原始参数。
  245. process.argv[1] = agentEntry;
  246. await import(pathToFileURL(agentEntry).href);
  247. }
  248. } catch (error) {
  249. console.error(error instanceof Error ? error.message : String(error));
  250. process.exit(1);
  251. }