protocol-console.ts 768 B

1234567891011121314151617181920
  1. import { Console } from "node:console";
  2. /**
  3. * 为独占 stdout 的 CLI(stdio protocol / TUI)安装 console 输出边界。
  4. *
  5. * app-server/agent-server 的 stdout 只能承载 ZCode Protocol NDJSON 帧,但三方
  6. * SDK 可能通过 console.* 写普通文本。如果不在加载这些依赖之前分离输出,
  7. * 任意一行日志都会被 Host 当作 JSON 解析,或直接覆盖 TUI 当前光标处的画面。
  8. */
  9. export function installStderrConsoleBoundary(stderr: NodeJS.WritableStream): () => void {
  10. const originalConsole = globalThis.console;
  11. globalThis.console = new Console({ stdout: stderr, stderr });
  12. let restored = false;
  13. return () => {
  14. if (restored) return;
  15. restored = true;
  16. globalThis.console = originalConsole;
  17. };
  18. }