zcode-stdio-tap.mjs 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. #!/usr/bin/env node
  2. import { createHash } from "node:crypto";
  3. import { createWriteStream, mkdirSync, writeFileSync } from "node:fs";
  4. import { homedir } from "node:os";
  5. import { join } from "node:path";
  6. import { StringDecoder } from "node:string_decoder";
  7. import { spawn } from "node:child_process";
  8. function printUsageAndExit() {
  9. process.stderr.write(
  10. [
  11. "Usage: zcode-stdio-tap.mjs --workspace-key <key> [--log-dir <dir>] -- <command> [...args]",
  12. "",
  13. ].join("\n"),
  14. );
  15. process.exit(2);
  16. }
  17. function parseArgs(argv) {
  18. const separatorIndex = argv.indexOf("--");
  19. if (separatorIndex < 0) {
  20. printUsageAndExit();
  21. }
  22. const options = argv.slice(0, separatorIndex);
  23. const commandAndArgs = argv.slice(separatorIndex + 1);
  24. if (commandAndArgs.length === 0) {
  25. printUsageAndExit();
  26. }
  27. let workspaceKey = "";
  28. let logDir = process.env.ZCODE_STDIO_TAP_LOG_DIR?.trim() || "";
  29. for (let index = 0; index < options.length; index += 1) {
  30. const option = options[index];
  31. if (option === "--workspace-key") {
  32. workspaceKey = options[index + 1] ?? "";
  33. index += 1;
  34. continue;
  35. }
  36. if (option === "--log-dir") {
  37. logDir = options[index + 1] ?? "";
  38. index += 1;
  39. continue;
  40. }
  41. printUsageAndExit();
  42. }
  43. if (!workspaceKey.trim()) {
  44. printUsageAndExit();
  45. }
  46. return {
  47. command: commandAndArgs[0],
  48. args: commandAndArgs.slice(1),
  49. logDir: logDir || join(homedir(), ".zcode", "v2", "dev", "stdio-traffic"),
  50. workspaceKey,
  51. };
  52. }
  53. function workspaceHash(workspaceKey) {
  54. return createHash("sha256").update(workspaceKey).digest("hex").slice(0, 12);
  55. }
  56. function tryParseJsonLine(raw) {
  57. const trimmed = raw.trim();
  58. if (!trimmed) {
  59. return { message: null, parseError: null };
  60. }
  61. try {
  62. return { message: JSON.parse(trimmed), parseError: null };
  63. } catch (error) {
  64. return {
  65. message: null,
  66. parseError: error instanceof Error ? error.message : String(error),
  67. };
  68. }
  69. }
  70. function extractProtocolMeta(message) {
  71. if (!message || typeof message !== "object") {
  72. return {};
  73. }
  74. const params = "params" in message && typeof message.params === "object" ? message.params : null;
  75. const payload =
  76. params && "payload" in params && typeof params.payload === "object" ? params.payload : null;
  77. return {
  78. id: "id" in message ? message.id : undefined,
  79. method: "method" in message ? message.method : undefined,
  80. sessionId:
  81. params && "sessionId" in params
  82. ? params.sessionId
  83. : payload && "sessionId" in payload
  84. ? payload.sessionId
  85. : undefined,
  86. inputId:
  87. params && "inputId" in params
  88. ? params.inputId
  89. : payload && "inputId" in payload
  90. ? payload.inputId
  91. : undefined,
  92. };
  93. }
  94. function createRecorder({ childPid, stream, workspaceKey }) {
  95. return function recordLine(direction, raw, bytes) {
  96. const parsed =
  97. direction === "agent-stderr" ? { message: null, parseError: null } : tryParseJsonLine(raw);
  98. const meta = extractProtocolMeta(parsed.message);
  99. const record = {
  100. ts: new Date().toISOString(),
  101. workspaceKey,
  102. proxyPid: process.pid,
  103. pid: childPid,
  104. direction,
  105. bytes,
  106. raw,
  107. message: parsed.message,
  108. parseError: parsed.parseError,
  109. ...meta,
  110. };
  111. stream.write(`${JSON.stringify(record)}\n`);
  112. };
  113. }
  114. function createLineTap(direction, recordLine) {
  115. const decoder = new StringDecoder("utf8");
  116. let pending = "";
  117. return {
  118. push(chunk) {
  119. pending += decoder.write(chunk);
  120. const lines = pending.split("\n");
  121. pending = lines.pop() ?? "";
  122. for (const line of lines) {
  123. recordLine(
  124. direction,
  125. line.endsWith("\r") ? line.slice(0, -1) : line,
  126. Buffer.byteLength(line),
  127. );
  128. }
  129. },
  130. flush() {
  131. const tail = `${pending}${decoder.end()}`;
  132. pending = "";
  133. if (tail.length > 0) {
  134. recordLine(
  135. direction,
  136. tail.endsWith("\r") ? tail.slice(0, -1) : tail,
  137. Buffer.byteLength(tail),
  138. );
  139. }
  140. },
  141. };
  142. }
  143. const config = parseArgs(process.argv.slice(2));
  144. const dir = join(config.logDir, workspaceHash(config.workspaceKey));
  145. mkdirSync(dir, { recursive: true });
  146. const child = spawn(config.command, config.args, {
  147. cwd: process.cwd(),
  148. env: process.env,
  149. stdio: ["pipe", "pipe", "pipe"],
  150. windowsHide: true,
  151. });
  152. const logFilePath = join(
  153. dir,
  154. `${new Date().toISOString().replace(/[:.]/g, "-")}-proxy-${process.pid}-agent-${child.pid ?? "unknown"}.ndjson`,
  155. );
  156. writeFileSync(join(dir, "latest.txt"), `${logFilePath}\n`);
  157. const stream = createWriteStream(logFilePath, { flags: "a" });
  158. const recordLine = createRecorder({
  159. childPid: child.pid ?? null,
  160. stream,
  161. workspaceKey: config.workspaceKey,
  162. });
  163. const stdinTap = createLineTap("app-to-agent", recordLine);
  164. const stdoutTap = createLineTap("agent-to-app", recordLine);
  165. const stderrTap = createLineTap("agent-stderr", recordLine);
  166. child.on("error", (error) => {
  167. recordLine(
  168. "agent-stderr",
  169. `[tap] spawn failed: ${error.message}`,
  170. Buffer.byteLength(error.message),
  171. );
  172. process.stderr.write(`[zcode-stdio-tap] spawn failed: ${error.message}\n`);
  173. });
  174. child.stdout.on("data", (chunk) => {
  175. process.stdout.write(chunk);
  176. stdoutTap.push(chunk);
  177. });
  178. child.stderr.on("data", (chunk) => {
  179. process.stderr.write(chunk);
  180. stderrTap.push(chunk);
  181. });
  182. process.stdin.on("data", (chunk) => {
  183. stdinTap.push(chunk);
  184. if (!child.stdin.write(chunk)) {
  185. process.stdin.pause();
  186. }
  187. });
  188. child.stdin.on("drain", () => {
  189. process.stdin.resume();
  190. });
  191. process.stdin.on("end", () => {
  192. stdinTap.flush();
  193. child.stdin.end();
  194. });
  195. function forwardSignal(signal) {
  196. if (!child.killed) {
  197. child.kill(signal);
  198. }
  199. }
  200. process.on("SIGINT", () => forwardSignal("SIGINT"));
  201. process.on("SIGTERM", () => forwardSignal("SIGTERM"));
  202. child.on("close", (code, signal) => {
  203. stdinTap.flush();
  204. stdoutTap.flush();
  205. stderrTap.flush();
  206. stream.end(() => {
  207. process.exit(code ?? (signal ? 1 : 0));
  208. });
  209. });