zcode-stdio-tap.mjs 6.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257
  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. const credentialReplies = new Set();
  96. return function recordLine(direction, raw, bytes) {
  97. const parsed =
  98. direction === "agent-stderr" ? { message: null, parseError: null } : tryParseJsonLine(raw);
  99. const meta = extractProtocolMeta(parsed.message);
  100. const message = parsed.message;
  101. const replyKey = `${direction}:${typeof meta.id}:${meta.id}`;
  102. if (meta.method === "interaction/requestCredentialCipher") {
  103. const replyDirection = direction === "agent-to-app" ? "app-to-agent" : "agent-to-app";
  104. credentialReplies.add(`${replyDirection}:${typeof meta.id}:${meta.id}`);
  105. // 加解密载荷含凭据明文;调试抓包只保留元数据,转发的原始字节不变。
  106. parsed.message = {
  107. jsonrpc: message.jsonrpc,
  108. id: meta.id,
  109. method: meta.method,
  110. params: "<redacted>",
  111. };
  112. raw = JSON.stringify(parsed.message);
  113. } else if (!meta.method && credentialReplies.delete(replyKey)) {
  114. parsed.message = { jsonrpc: message.jsonrpc, id: meta.id, result: "<redacted>" };
  115. raw = JSON.stringify(parsed.message);
  116. }
  117. const record = {
  118. ts: new Date().toISOString(),
  119. workspaceKey,
  120. proxyPid: process.pid,
  121. pid: childPid,
  122. direction,
  123. bytes,
  124. raw,
  125. message: parsed.message,
  126. parseError: parsed.parseError,
  127. ...meta,
  128. };
  129. stream.write(`${JSON.stringify(record)}\n`);
  130. };
  131. }
  132. function createLineTap(direction, recordLine) {
  133. const decoder = new StringDecoder("utf8");
  134. let pending = "";
  135. return {
  136. push(chunk) {
  137. pending += decoder.write(chunk);
  138. const lines = pending.split("\n");
  139. pending = lines.pop() ?? "";
  140. for (const line of lines) {
  141. recordLine(
  142. direction,
  143. line.endsWith("\r") ? line.slice(0, -1) : line,
  144. Buffer.byteLength(line),
  145. );
  146. }
  147. },
  148. flush() {
  149. const tail = `${pending}${decoder.end()}`;
  150. pending = "";
  151. if (tail.length > 0) {
  152. recordLine(
  153. direction,
  154. tail.endsWith("\r") ? tail.slice(0, -1) : tail,
  155. Buffer.byteLength(tail),
  156. );
  157. }
  158. },
  159. };
  160. }
  161. const config = parseArgs(process.argv.slice(2));
  162. const dir = join(config.logDir, workspaceHash(config.workspaceKey));
  163. mkdirSync(dir, { recursive: true });
  164. const child = spawn(config.command, config.args, {
  165. cwd: process.cwd(),
  166. env: process.env,
  167. stdio: ["pipe", "pipe", "pipe"],
  168. windowsHide: true,
  169. });
  170. const logFilePath = join(
  171. dir,
  172. `${new Date().toISOString().replace(/[:.]/g, "-")}-proxy-${process.pid}-agent-${child.pid ?? "unknown"}.ndjson`,
  173. );
  174. writeFileSync(join(dir, "latest.txt"), `${logFilePath}\n`);
  175. const stream = createWriteStream(logFilePath, { flags: "a" });
  176. const recordLine = createRecorder({
  177. childPid: child.pid ?? null,
  178. stream,
  179. workspaceKey: config.workspaceKey,
  180. });
  181. const stdinTap = createLineTap("app-to-agent", recordLine);
  182. const stdoutTap = createLineTap("agent-to-app", recordLine);
  183. const stderrTap = createLineTap("agent-stderr", recordLine);
  184. child.on("error", (error) => {
  185. recordLine(
  186. "agent-stderr",
  187. `[tap] spawn failed: ${error.message}`,
  188. Buffer.byteLength(error.message),
  189. );
  190. process.stderr.write(`[zcode-stdio-tap] spawn failed: ${error.message}\n`);
  191. });
  192. child.stdout.on("data", (chunk) => {
  193. process.stdout.write(chunk);
  194. stdoutTap.push(chunk);
  195. });
  196. child.stderr.on("data", (chunk) => {
  197. process.stderr.write(chunk);
  198. stderrTap.push(chunk);
  199. });
  200. process.stdin.on("data", (chunk) => {
  201. stdinTap.push(chunk);
  202. if (!child.stdin.write(chunk)) {
  203. process.stdin.pause();
  204. }
  205. });
  206. child.stdin.on("drain", () => {
  207. process.stdin.resume();
  208. });
  209. process.stdin.on("end", () => {
  210. stdinTap.flush();
  211. child.stdin.end();
  212. });
  213. function forwardSignal(signal) {
  214. if (!child.killed) {
  215. child.kill(signal);
  216. }
  217. }
  218. process.on("SIGINT", () => forwardSignal("SIGINT"));
  219. process.on("SIGTERM", () => forwardSignal("SIGTERM"));
  220. child.on("close", (code, signal) => {
  221. stdinTap.flush();
  222. stdoutTap.flush();
  223. stderrTap.flush();
  224. stream.end(() => {
  225. process.exit(code ?? (signal ? 1 : 0));
  226. });
  227. });