result.ts 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. import {
  2. ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY,
  3. ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY,
  4. } from "@zcode/contracts/mcp";
  5. import { isOfficialCuaImageRefText } from "@zcode/zcode-cua/frame-contract";
  6. import { CUA_APP_ASSOCIATIONS_META_KEY } from "@zcode/zcode-cua/host-display-contract";
  7. import type { NodeReplRunResult } from "@zcode/core/repl";
  8. import type { CallToolResult } from "@modelcontextprotocol/server";
  9. type EmbeddedContentBlock = CallToolResult["content"][number];
  10. interface EmbeddedMcpResult {
  11. content: EmbeddedContentBlock[];
  12. isError?: boolean;
  13. structuredContent?: Record<string, unknown>;
  14. _meta?: Record<string, unknown>;
  15. }
  16. function parseEmbeddedMcpResult(value: string): EmbeddedMcpResult | undefined {
  17. const trimmed = value.trim();
  18. const json = trimmed.startsWith("=>") ? trimmed.slice(2).trim() : trimmed;
  19. if (!json.startsWith("{")) return undefined;
  20. try {
  21. const parsed = JSON.parse(json) as unknown;
  22. if (!parsed || typeof parsed !== "object") return undefined;
  23. const candidate = parsed as Record<string, unknown>;
  24. if (!Array.isArray(candidate.content)) return undefined;
  25. if (
  26. candidate.content.some(
  27. (block) => !block || typeof block !== "object" || typeof (block as { type?: unknown }).type !== "string",
  28. )
  29. ) {
  30. return undefined;
  31. }
  32. return {
  33. content: candidate.content as EmbeddedContentBlock[],
  34. ...(typeof candidate.isError === "boolean" ? { isError: candidate.isError } : {}),
  35. ...(candidate.structuredContent && typeof candidate.structuredContent === "object"
  36. ? { structuredContent: candidate.structuredContent as Record<string, unknown> }
  37. : {}),
  38. ...(candidate._meta && typeof candidate._meta === "object"
  39. ? { _meta: candidate._meta as Record<string, unknown> }
  40. : {}),
  41. };
  42. } catch {
  43. return undefined;
  44. }
  45. }
  46. /**
  47. * 一个 cell 里多次带截图的观察,只把**最后一张** raster 交给模型。
  48. *
  49. * 模型在一个 cell 里调了两次带截图的观察,结果里就有两张图,
  50. * 被 exact-raster 门按「每个结果只允许一张最终 raster」把整帧原子否决 —— 模型一张都没拿到。
  51. *
  52. * 「最新者胜」本来就是 producer 的既定语义:坐标只对最新那张 raster 有效
  53. * (zcode-cua 的 frame-pixel-latest-only 测试即此契约),旧帧对模型没有使用价值。
  54. * 所以这里保留最后一对 image/authority、丢掉更早的,与契约一致,不是放宽门禁 ——
  55. * 真正的两张不同 raster 同时有效仍然不被允许。
  56. *
  57. * 只处理 CUA 的「图 + 紧邻权威」原子对;不带权威的图片(如 Browser Use 截图)不受影响。
  58. */
  59. function keepLatestCuaFrame(blocks: EmbeddedContentBlock[]): EmbeddedContentBlock[] {
  60. const pairStarts: number[] = [];
  61. blocks.forEach((block, index) => {
  62. if (block.type !== "image") return;
  63. const next = blocks[index + 1];
  64. if (next?.type === "text" && isOfficialCuaImageRefText(next.text)) pairStarts.push(index);
  65. });
  66. if (pairStarts.length <= 1) return blocks;
  67. const dropped = new Set(pairStarts.slice(0, -1).flatMap((start) => [start, start + 1]));
  68. return blocks.filter((_, index) => !dropped.has(index));
  69. }
  70. export function toMcpRunResult(run: NodeReplRunResult): CallToolResult {
  71. const textParts: string[] = [];
  72. // SDK 结果通过专用 sink 写入后,不能再从 run.result/console 日志解析第二份副本。
  73. // 否则模型的 JSON.stringify 会把 image base64 降成普通文本,破坏 image/image_ref 邻接关系。
  74. const structuredResults = run.structuredResults ?? [];
  75. const embedded =
  76. structuredResults.length === 0 && !run.error && run.result !== undefined
  77. ? parseEmbeddedMcpResult(run.result)
  78. : undefined;
  79. const responseMeta = { ...run.responseMeta };
  80. for (const structured of structuredResults) {
  81. if (structured._meta) Object.assign(responseMeta, structured._meta);
  82. }
  83. if (embedded?._meta) Object.assign(responseMeta, embedded._meta);
  84. // 该 key 决定 core 是否把原图落盘,不能允许 REPL 代码通过
  85. // setResponseMeta 伪造来源;只接受 NodeReplSession 根据真实 screenshot payload 生成的索引。
  86. delete responseMeta[ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY];
  87. // 同款处置:producer 的应用元数据决定工具卡显示哪个 App 的名称和图标。它经
  88. // `projectToHost` -> `nodeRepl.emitStructuredResult` 到达上面的合并循环,而那个 API 挂在模型
  89. // 可见的 sandbox globals 上 —— cell 里自己 emit 一份就能让卡片声称操作了别的应用。因此这里
  90. // 无条件丢弃,只接受 CUA bridge 从 broker 响应直接记录的 run.cuaApp。
  91. delete responseMeta[CUA_APP_ASSOCIATIONS_META_KEY];
  92. delete responseMeta[ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY];
  93. if (run.cuaApp) responseMeta[ZCODE_MCP_NODE_REPL_CUA_APP_META_KEY] = run.cuaApp;
  94. // Anthropic 兼容网关(如 bigmodel MaaS)只解析 tool_result.content 开头的连续
  95. // image block,一旦先遇到 text 就丢弃后面的图,模型只能看到 image_ref 元数据而看不到画面
  96. // (实测 [image]/[image,text] 可见,[text,image]/[text,image,text] 不可见)。
  97. // 把 image 排在 text 之前即可让图稳定到达模型;顺序在 Anthropic 规范里本就是自由的。
  98. // image 因此从 content[0] 起连续排列,image 下标与 content 下标相等,无需再做 +1 偏移。
  99. const browserScreenshotContentIndices = run.browserScreenshotImageIndices;
  100. const structuredContent = keepLatestCuaFrame(
  101. structuredResults.flatMap((structured) => structured.content as EmbeddedContentBlock[]),
  102. );
  103. const structuredContentResult = [...structuredResults]
  104. .reverse()
  105. .find((structured) => structured.structuredContent !== undefined);
  106. const structuredIsError = structuredResults.some((structured) => structured.isError === true);
  107. if (run.error) {
  108. // node_repl 若用 message-only 隐藏通用 MCP 失败前缀,只消费
  109. // 模型结果文本的分析链路无法区分成功与失败。继续只返回结构化 error.message,
  110. // 不混入错误类型、堆栈或失败前日志,并让通用 bridge 根据 isError 投影稳定标记。
  111. textParts.push(run.error.message);
  112. } else {
  113. if (run.logs) textParts.push(run.logs);
  114. if (structuredResults.length === 0 && run.result !== undefined && !embedded) {
  115. textParts.push(`=> ${run.result}`);
  116. }
  117. }
  118. const content = [
  119. ...(run.error
  120. ? []
  121. : structuredResults.length > 0
  122. ? structuredContent
  123. : (run.images ?? []).map((image) => ({
  124. type: "image" as const,
  125. data: image.base64,
  126. mimeType: image.mimeType,
  127. }))),
  128. ...(structuredResults.length > 0
  129. ? // 结构化观察已携带截图;模型再次 emitImage 同一张图时,只保留结构化结果中的副本。
  130. // 去重必须逐字节相等:保留截图原始像素及其 frame_id 绑定,不同图片仍交由帧校验拒绝。
  131. (run.images ?? [])
  132. .filter(
  133. (image) =>
  134. !structuredContent.some(
  135. (block) =>
  136. block.type === "image" &&
  137. (block as { data?: string }).data === image.base64,
  138. ),
  139. )
  140. .map((image) => ({
  141. type: "image" as const,
  142. data: image.base64,
  143. mimeType: image.mimeType,
  144. }))
  145. : []),
  146. ...(embedded?.content ?? []),
  147. ...(textParts.length > 0 ? [{ type: "text" as const, text: textParts.join("\n") }] : []),
  148. ];
  149. return {
  150. content: content.length > 0 ? content : [{ type: "text" as const, text: "(no output)" }],
  151. ...(run.error || embedded?.isError || structuredIsError ? { isError: true } : {}),
  152. ...(structuredContentResult?.structuredContent !== undefined
  153. ? { structuredContent: structuredContentResult.structuredContent }
  154. : embedded?.structuredContent !== undefined
  155. ? { structuredContent: embedded.structuredContent }
  156. : {}),
  157. ...(Object.keys(responseMeta).length > 0 ||
  158. (run.images?.length ?? 0) > 0 ||
  159. structuredContent.some((block) => block.type === "image")
  160. ? {
  161. _meta: {
  162. ...responseMeta,
  163. ...((run.images?.length ?? 0) > 0 || structuredContent.some((block) => block.type === "image")
  164. ? { "zcode/nodeReplEmittedImage": true }
  165. : {}),
  166. ...(browserScreenshotContentIndices && browserScreenshotContentIndices.length > 0
  167. ? {
  168. [ZCODE_MCP_BROWSER_SCREENSHOT_CONTENT_INDICES_META_KEY]:
  169. browserScreenshotContentIndices,
  170. }
  171. : {}),
  172. },
  173. }
  174. : {}),
  175. };
  176. }