transport.ts 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322
  1. import type {
  2. ZCodeProtocolError,
  3. ZCodeProtocolMessage,
  4. ZCodeProtocolNotification,
  5. ZCodeProtocolRequest,
  6. ZCodeProtocolRequestId,
  7. ZCodeProtocolResponse,
  8. } from "@zcode/shared";
  9. import {
  10. networkCaptureControlSchema,
  11. zcodeProtocolMessageSchema,
  12. zcodeProtocolMethods,
  13. zcodeProtocolNotifications,
  14. } from "@zcode/shared";
  15. import type { Logger } from "@zcode/contracts";
  16. type ZCodeProtocolOutgoingMessage =
  17. | ZCodeProtocolError
  18. | ZCodeProtocolNotification
  19. | ZCodeProtocolRequest
  20. | ZCodeProtocolResponse;
  21. type ZCodeProtocolMessageHandler = (
  22. message: ZCodeProtocolMessage,
  23. ) => Promise<ZCodeProtocolOutgoingMessage | undefined>;
  24. const PROTOCOL_EOF_DRAIN_MS = 100;
  25. // MCP App 的请求由实例凭证和 callId 隔离;若与普通命令一起等待完成,
  26. // uiCallTool 会挡住自己的 cancel/close,真实 stdio 链路将死锁。
  27. const MCP_APP_CONCURRENT_METHODS = new Set<string>([
  28. zcodeProtocolMethods.mcpReadResource,
  29. zcodeProtocolMethods.mcpUiOpenInstance,
  30. zcodeProtocolMethods.mcpUiCloseInstance,
  31. zcodeProtocolMethods.mcpUiValidateInstance,
  32. zcodeProtocolMethods.mcpUiCallTool,
  33. zcodeProtocolMethods.mcpUiSampling,
  34. zcodeProtocolMethods.mcpUiCancelSampling,
  35. zcodeProtocolMethods.mcpUiCancelCall,
  36. zcodeProtocolMethods.mcpUiReadResource,
  37. zcodeProtocolMethods.mcpUiListResources,
  38. zcodeProtocolMethods.mcpUiListResourceTemplates,
  39. zcodeProtocolMethods.mcpUiSubscribeResource,
  40. zcodeProtocolMethods.mcpUiUnsubscribeResource,
  41. zcodeProtocolMethods.mcpUiRegisterAppTools,
  42. zcodeProtocolMethods.mcpUiUnregisterAppTools,
  43. zcodeProtocolMethods.mcpUiClaimAppToolCall,
  44. zcodeProtocolMethods.mcpUiResolveAppToolCall,
  45. ]);
  46. interface ZCodeProtocolNdjsonConnectionOptions {
  47. signal?: AbortSignal;
  48. clearPostResponseMessages?: () => void;
  49. handleMessage: ZCodeProtocolMessageHandler;
  50. input: NodeJS.ReadableStream;
  51. logger?: Logger;
  52. onTransportClosed?: (error: Error) => void;
  53. output: NodeJS.WritableStream;
  54. takePostResponseMessages?: (
  55. requestId: ZCodeProtocolRequestId,
  56. ) => readonly ZCodeProtocolOutgoingMessage[];
  57. takePostResponseBatch?: (requestId: ZCodeProtocolRequestId) => {
  58. readonly messages: readonly ZCodeProtocolOutgoingMessage[];
  59. commit(): boolean;
  60. } | null;
  61. }
  62. export class ZCodeProtocolNdjsonConnection {
  63. private buffer = "";
  64. private processing: Promise<void> = Promise.resolve();
  65. private lastQueuedMessageStarted: Promise<void> = Promise.resolve();
  66. private readonly closedPromise: Promise<void>;
  67. private resolveClosed!: () => void;
  68. private rejectClosed!: (error: Error) => void;
  69. private terminal = false;
  70. private transportCloseNotified = false;
  71. private draining = false;
  72. private drainTimer?: ReturnType<typeof setTimeout>;
  73. constructor(private readonly options: ZCodeProtocolNdjsonConnectionOptions) {
  74. this.closedPromise = new Promise((resolve, reject) => {
  75. this.resolveClosed = resolve;
  76. this.rejectClosed = reject;
  77. });
  78. }
  79. start(): void {
  80. this.options.input.on("data", this.onData);
  81. this.options.input.once("end", this.onClose);
  82. this.options.input.once("close", this.onClose);
  83. this.options.input.on("error", this.onError);
  84. this.options.output.on("error", this.onError);
  85. this.options.signal?.addEventListener("abort", this.onAbort, { once: true });
  86. if (this.options.signal?.aborted) this.onAbort();
  87. }
  88. waitForClose(): Promise<void> {
  89. return this.closedPromise;
  90. }
  91. send(message: ZCodeProtocolOutgoingMessage): void {
  92. if (this.terminal) return;
  93. // 观测可丢弃,不能在 stdout 背压时无界积压或挤占业务协议输出。
  94. if (
  95. "method" in message &&
  96. message.method === zcodeProtocolNotifications.processNetworkRequests &&
  97. ((this.options.output as NodeJS.WritableStream & { writableLength?: number })
  98. .writableLength ?? 0) >=
  99. 256 * 1024
  100. )
  101. return;
  102. try {
  103. this.options.output.write(`${JSON.stringify(message)}\n`);
  104. } catch (error) {
  105. this.onError(error instanceof Error ? error : new Error(String(error)));
  106. }
  107. }
  108. private readonly onData = (chunk: Buffer | string): void => {
  109. if (this.terminal || this.draining) return;
  110. this.buffer += typeof chunk === "string" ? chunk : chunk.toString("utf8");
  111. let newlineIndex = this.buffer.indexOf("\n");
  112. while (newlineIndex >= 0) {
  113. const line = this.buffer.slice(0, newlineIndex).trim();
  114. this.buffer = this.buffer.slice(newlineIndex + 1);
  115. if (line.length > 0) {
  116. this.dispatchLine(line);
  117. }
  118. newlineIndex = this.buffer.indexOf("\n");
  119. }
  120. };
  121. private readonly onClose = (): void => {
  122. if (this.terminal || this.draining) return;
  123. const trailing = this.buffer.trim();
  124. if (trailing.length > 0) {
  125. this.dispatchLine(trailing);
  126. this.buffer = "";
  127. }
  128. this.draining = true;
  129. this.notifyTransportClosed(new Error("ZCode Protocol client connection closed"));
  130. // EOF 保留短请求半关闭响应,但挂起 handler 不能让进程永久保活。
  131. this.drainTimer = setTimeout(() => this.finish(), PROTOCOL_EOF_DRAIN_MS);
  132. void this.processing.then(
  133. () => this.finish(),
  134. (error: Error) => this.fail(error),
  135. );
  136. };
  137. private readonly onAbort = (): void => {
  138. this.notifyTransportClosed(new Error("ZCode Protocol runtime stopping"));
  139. this.finish();
  140. };
  141. private readonly onError = (error: Error): void => {
  142. this.notifyTransportClosed(error);
  143. this.fail(error);
  144. };
  145. private notifyTransportClosed(error: Error): void {
  146. if (this.transportCloseNotified) return;
  147. this.transportCloseNotified = true;
  148. this.options.onTransportClosed?.(error);
  149. }
  150. private finish(): void {
  151. if (this.terminal) return;
  152. this.terminal = true;
  153. this.detachInput();
  154. this.options.clearPostResponseMessages?.();
  155. this.resolveClosed();
  156. }
  157. private fail(error: Error): void {
  158. if (this.terminal) return;
  159. this.terminal = true;
  160. this.notifyTransportClosed(error);
  161. this.detachInput();
  162. this.options.clearPostResponseMessages?.();
  163. this.rejectClosed(error);
  164. }
  165. private detachInput(): void {
  166. if (this.drainTimer) clearTimeout(this.drainTimer);
  167. this.options.input.off("data", this.onData);
  168. this.options.input.off("end", this.onClose);
  169. this.options.input.off("close", this.onClose);
  170. this.options.signal?.removeEventListener("abort", this.onAbort);
  171. // 错误 listener 保留到流本身结束,吸收已经排入事件循环的迟到 stream error。
  172. }
  173. private dispatchLine(line: string): void {
  174. if (this.terminal) return;
  175. const message = this.decodeLine(line);
  176. if (!message) {
  177. return;
  178. }
  179. if (
  180. !("id" in message) &&
  181. "method" in message &&
  182. message.method === zcodeProtocolMethods.processNetworkCapture
  183. ) {
  184. // 启停是进程观测控制,不等待正在执行的生成任务,也不进入 CommandInbox。
  185. if (networkCaptureControlSchema.safeParse(message.params).success) {
  186. void this.handleMessage(message).catch(() => {
  187. /* 观测失败不关闭业务连接 */
  188. });
  189. }
  190. return;
  191. }
  192. if ("id" in message && ("result" in message || "error" in message)) {
  193. // Agent 发出反向 request 前已同步登记 pending response。
  194. // 若 response 等待“最后一个排队请求开始”,后续普通请求会把等待点推到当前长请求之后,
  195. // 形成「当前请求等 response、response 等后续请求」的死锁。
  196. void this.handleMessage(message).catch((error: unknown) => {
  197. this.fail(error instanceof Error ? error : new Error(String(error)));
  198. });
  199. return;
  200. }
  201. if (this.shouldBypassProcessingQueue(message)) {
  202. // 停止/取消控制必须等它前面的普通请求真正进入 handler、建立 abort
  203. // controller,再越过该请求的异步执行;只延后一轮微任务会让控制请求提前成为空操作。
  204. void this.lastQueuedMessageStarted
  205. .then(() => this.handleMessage(message))
  206. .catch((error: unknown) => {
  207. this.fail(error instanceof Error ? error : new Error(String(error)));
  208. });
  209. return;
  210. }
  211. let markStarted!: () => void;
  212. const started = new Promise<void>((resolve) => {
  213. markStarted = resolve;
  214. });
  215. this.lastQueuedMessageStarted = started;
  216. this.processing = this.processing
  217. .then(async () => {
  218. const handling = this.handleMessage(message);
  219. markStarted();
  220. await handling;
  221. })
  222. .catch((error: unknown) => {
  223. markStarted();
  224. this.fail(error instanceof Error ? error : new Error(String(error)));
  225. });
  226. }
  227. private decodeLine(line: string): ZCodeProtocolMessage | null {
  228. let decoded: unknown;
  229. try {
  230. decoded = JSON.parse(line);
  231. } catch (error) {
  232. this.options.logger?.warn("ZCode Protocol JSON parse failed", {
  233. error: error instanceof Error ? error.message : String(error),
  234. event: "zcode_protocol.parse.failed",
  235. module: "bootstrap.zcode_protocol",
  236. status: "failed",
  237. });
  238. this.sendError("parse-error", -32700, "Parse error");
  239. return null;
  240. }
  241. const parsed = zcodeProtocolMessageSchema.safeParse(decoded);
  242. if (!parsed.success) {
  243. this.sendError("invalid-message", -32600, "Invalid ZCode Protocol message", {
  244. issues: parsed.error.issues,
  245. });
  246. return null;
  247. }
  248. return parsed.data;
  249. }
  250. private shouldBypassProcessingQueue(message: ZCodeProtocolMessage): boolean {
  251. // 模型任务占住串行队列时,停止/取消请求必须仍能进入 server,
  252. // 才能把底层 AbortSignal 传给真实模型请求。控制面只旁路当前执行,普通请求仍保持串行。
  253. return (
  254. "id" in message &&
  255. "method" in message &&
  256. (message.method === zcodeProtocolMethods.sessionStop ||
  257. message.method === zcodeProtocolMethods.workspaceCancelGenerateText ||
  258. MCP_APP_CONCURRENT_METHODS.has(message.method))
  259. );
  260. }
  261. private async handleMessage(message: ZCodeProtocolMessage): Promise<void> {
  262. if (this.terminal) return;
  263. const response = await this.options.handleMessage(message);
  264. if (response) {
  265. // 确定性时序:先一次性 take 当前 request 的 outbox,再连续写 response
  266. // 与 notification。禁止 queueMicrotask/setTimeout 或依赖底层分包先后。
  267. const postResponseBatch =
  268. "id" in response && ("result" in response || "error" in response)
  269. ? (this.options.takePostResponseBatch?.(response.id) ?? {
  270. messages: this.options.takePostResponseMessages?.(response.id) ?? [],
  271. commit: () => true,
  272. })
  273. : { messages: [], commit: () => true };
  274. // output EPIPE 可能发生在 subscribe handler 在途期间。fail() 已清过
  275. // 当时的 outbox,但迟到 handler 仍可能新建 request entry;这里先 take 精确释放,
  276. // terminal 时不再写 response/initial,避免 close 后引用泄漏或继续写坏流。
  277. if (this.terminal) return;
  278. this.send(response);
  279. for (const postResponseMessage of postResponseBatch.messages) {
  280. this.send(postResponseMessage);
  281. }
  282. // 旧 outbox 在生成 logical frame 时已推进 publisher 水位。这里以
  283. // Writable.write() 未同步抛错作为“进入本 connection-owned queue”的 admission;
  284. // 后续异步 EPIPE 会终结整个 connection epoch,旧 subscription 不会在新管道复用。
  285. if (!this.terminal) postResponseBatch.commit();
  286. }
  287. }
  288. private sendError(id: string, code: number, message: string, data?: unknown): void {
  289. this.send({
  290. error: {
  291. code,
  292. data,
  293. message,
  294. },
  295. id,
  296. });
  297. }
  298. }