entry-stdio.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. import { disposeServiceResourcesAndWait, getAppConfigDir } from "@zcode/services/node";
  2. import type { IChannel } from "@zcode/rpc";
  3. import {
  4. ZCODE_VERSION,
  5. TOPIC_RESOURCE_RELAY_CHANNEL,
  6. SERVICE_AUTHORITY_MODE_ENV,
  7. formatLogPrefix,
  8. formatZodError,
  9. helloAckMessageSchema,
  10. } from "@zcode/shared";
  11. import type { HelloMessage, HelloAckMessage } from "@zcode/shared";
  12. import { createStdioServer } from "./stdio.js";
  13. import { registerStdioProcessLifecycle } from "./stdio-lifecycle.js";
  14. import { createStdioServices } from "./stdioServices.js";
  15. import { ensureRemoteServerDeviceMid } from "./stdioDeviceMid.js";
  16. import {
  17. materializeBundledZCodeBuiltinProviderConfig,
  18. readBundledZCodeBuiltinProviderConfig,
  19. } from "./bundledZCodeBuiltinProviderConfig.js";
  20. // In stdio mode, all logging goes to stderr
  21. const log = (...args: unknown[]) =>
  22. console.error(formatLogPrefix("zcode-server:stdio", process.pid), ...args);
  23. const stderrConsoleLog = (...args: unknown[]) => console.error(...args);
  24. // stdio 模式下 stdout 只能承载 RPC 帧。
  25. // 之前 services 里的 info/debug 日志仍会走 console.log / console.info,
  26. // 一旦把普通文本写进 stdout,就会直接污染协议流,表现成远程调用一直 pending / loading。
  27. // 这里在 entry 层统一把普通 console 输出重定向到 stderr,确保所有服务日志都不会再打坏 RPC。
  28. console.log = stderrConsoleLog;
  29. console.info = stderrConsoleLog;
  30. console.warn = stderrConsoleLog;
  31. console.debug = stderrConsoleLog;
  32. // --version flag: print version and exit (used by deploy version check)
  33. if (process.argv.includes("--version")) {
  34. process.stdout.write(ZCODE_VERSION + "\n");
  35. process.exit(0);
  36. }
  37. async function main() {
  38. // Phase 1: Send hello message
  39. const hello: HelloMessage = {
  40. type: "zcode-hello",
  41. version: ZCODE_VERSION,
  42. platform: process.platform,
  43. arch: process.arch,
  44. pid: process.pid,
  45. };
  46. process.stdout.write(JSON.stringify(hello) + "\n");
  47. // Phase 2: Wait for hello-ack
  48. const ack = await waitForAck();
  49. log(`client connected: ${ack.clientId} (v${ack.version})`);
  50. // 远端主机没有 Desktop main,没人写 telemetry-state.json,services 发往 ZCode endpoint
  51. // 的请求缺 X-Device-Mid,Start Plan 的 billing/balance 被拒。远端 server 是本机设备身份的
  52. // 生命周期所有者,必须在 services 创建前确保 deviceMid 存在(详见 stdioDeviceMid.ts)。
  53. await ensureRemoteServerDeviceMid({ log });
  54. // Phase 3: Initialize services and start stdio RPC server
  55. let topicResourceChannel: IChannel | undefined;
  56. const zcodeBuiltinProviderConfigFilePath = await materializeBundledZCodeBuiltinProviderConfig({
  57. environmentConfigRoot: getAppConfigDir(),
  58. content: readBundledZCodeBuiltinProviderConfig(),
  59. });
  60. const { authorityModeParseResult, services } = createStdioServices({
  61. env: process.env,
  62. zcodeBuiltinProviderConfigFilePath,
  63. topicResourceRelayChannel: () => {
  64. if (!topicResourceChannel) throw new Error("Desktop topic resource channel is unavailable");
  65. return topicResourceChannel;
  66. },
  67. });
  68. if (authorityModeParseResult.invalidRawValue) {
  69. log(
  70. `${SERVICE_AUTHORITY_MODE_ENV}=${authorityModeParseResult.invalidRawValue} 非法,按默认本机 Environment 权威模式启动`,
  71. );
  72. }
  73. const stdioServer = createStdioServer(
  74. services,
  75. authorityModeParseResult.mode === "desktop-attached-remote"
  76. ? (client) => {
  77. topicResourceChannel = client.getChannel(TOPIC_RESOURCE_RELAY_CHANNEL);
  78. }
  79. : undefined,
  80. );
  81. registerStdioProcessLifecycle({
  82. stdin: process.stdin,
  83. signalSource: process,
  84. log,
  85. stopRpc: () => stdioServer.stop(),
  86. // Desktop Host 已经会等待 disposeServiceResourcesAndWait,远端 stdio
  87. // entry 却仍直接 process.exit,导致其托管的 workspace Agent 来不及完成进程树清理。
  88. // 远端 server 也是 ServiceCollection owner,退出前必须遵守同一异步回收契约。
  89. dispose: () => disposeServiceResourcesAndWait(services),
  90. exit: (code) => process.exit(code),
  91. });
  92. // ready 日志必须在退出监听注册之后;否则 SSH 恰好在 ready 后断开时,
  93. // SIGHUP/SIGTERM 仍可能落入 Node 默认处理并绕过 Agent cleanup。
  94. log("stdio mode ready");
  95. }
  96. function waitForAck(): Promise<HelloAckMessage> {
  97. return new Promise((resolve, reject) => {
  98. const timeout = setTimeout(() => {
  99. reject(new Error("Handshake timeout: no hello-ack received within 10s"));
  100. }, 10_000);
  101. let buffer = "";
  102. const onData = (chunk: Buffer) => {
  103. buffer += chunk.toString("utf-8");
  104. const newlineIdx = buffer.indexOf("\n");
  105. if (newlineIdx !== -1) {
  106. const line = buffer.slice(0, newlineIdx).trim();
  107. // Remove listener — remaining data in buffer will be consumed by RPC
  108. process.stdin.removeListener("data", onData);
  109. clearTimeout(timeout);
  110. try {
  111. const rawValue = JSON.parse(line);
  112. const result = helloAckMessageSchema.safeParse(rawValue);
  113. if (!result.success) {
  114. reject(new Error(`Invalid hello-ack: ${formatZodError(result.error)}`));
  115. return;
  116. }
  117. const msg = result.data as HelloAckMessage;
  118. // If there's remaining data after the newline, push it back
  119. const remaining = buffer.slice(newlineIdx + 1);
  120. if (remaining.length > 0) {
  121. process.stdin.unshift(Buffer.from(remaining, "utf-8"));
  122. }
  123. resolve(msg);
  124. } catch (err) {
  125. reject(new Error(`Failed to parse hello-ack: ${err}`));
  126. }
  127. }
  128. };
  129. process.stdin.on("data", onData);
  130. });
  131. }
  132. main().catch((err) => {
  133. log("fatal:", err);
  134. process.exit(1);
  135. });