transport.ts 13 KB

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