tool-result-media-projection.ts 9.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. import type { ModelMessage as AiSdkModelMessage } from "ai";
  2. import {
  3. getUnsupportedModelInputMediaKind,
  4. modelMessageContentToText,
  5. type ModelInputFormat,
  6. type ModelMessageContent,
  7. type ModelMessageContentBlock,
  8. } from "@zcode/contracts";
  9. import { containsOfficialCuaImageRefCredentialText } from "@zcode/zcode-cua/frame-contract";
  10. import { dataUrlToDataContent, unsupportedInputMediaText } from "./media-transform-policy.js";
  11. type AiSdkUserContent = Extract<AiSdkModelMessage, { role: "user" }>["content"];
  12. type AiSdkUserContentParts = Extract<AiSdkUserContent, unknown[]>;
  13. interface ToolResultMediaProjectionOptions {
  14. apiFormat?: string;
  15. providerKind?: "openai" | "anthropic" | "openai-compatible" | "gateway" | "custom";
  16. stripMedia?: boolean;
  17. inputFormat?: ModelInputFormat;
  18. toolName: string;
  19. }
  20. const CHAT_STYLE_TOOL_RESULT_PROVIDER_KINDS = new Set(["openai-compatible", "gateway"]);
  21. const TOOL_RESULT_MEDIA_INTRO_PREFIX = "Tool result media from";
  22. export function shouldTextifyStructuredToolResults(
  23. options: Pick<ToolResultMediaProjectionOptions, "apiFormat" | "providerKind">,
  24. ): boolean {
  25. if (options.apiFormat !== undefined) {
  26. return options.apiFormat === "openai-chat-completions";
  27. }
  28. // 根因:openai kind 使用 Responses API;按宽泛的 OpenAI-like 家族判断会把它
  29. // 误投影成 Chat Completions 的 tool text + synthetic user。缺少显式格式时只对
  30. // 确实使用 Chat 风格结果的 provider 回退,显式 apiFormat 仍拥有最高优先级。
  31. return (
  32. options.providerKind !== undefined &&
  33. CHAT_STYLE_TOOL_RESULT_PROVIDER_KINDS.has(options.providerKind)
  34. );
  35. }
  36. /**
  37. * tool result 是否含 video 媒体。AI SDK tool result part 没有 video 变体(image-data 之外
  38. * 只支持 file-data/pdf),所以含 video 的 tool result 在所有 provider kind(含 anthropic)
  39. * 都必须走 textify + 后置 user part 投影,否则视频内容会在 wire 边界丢失。
  40. */
  41. export function toolResultHasVideoMedia(content: ModelMessageContent): boolean {
  42. if (typeof content === "string") return false;
  43. return content.some((block) => block.type === "video");
  44. }
  45. /**
  46. * 配对规则(producer 谓词驱动):紧邻 media 块之后、且内容是受保护媒体
  47. * 凭证(producer 签发的 image_ref 等)的 text 块,视为该 media 的配对文本。
  48. * provider 投影把 media 延后为独立 user 消息时(openai-like textify),配对
  49. * 文本必须一起延后且保持顺序——留在 tool 文本里会让模型看到"引用文本"与
  50. * "被引用媒体"分属两条消息,多帧场景极易配错。
  51. * 普通文本(说明、总结)不是凭证,不参与配对——通用工具的媒体语义保持
  52. * 不变;凭证判定是 producer 帧契约的一部分,宿主经 frame-contract 引用。
  53. * Producer canonical order is image-first(raster 在前、image_ref 紧随其后)。
  54. * 配对查找从 image 向后读取其 authority,不依赖 provider 特殊截断行为。
  55. */
  56. type PairedTextOptions = Pick<ToolResultMediaProjectionOptions, "stripMedia" | "inputFormat">;
  57. function isPairedTextBlock(
  58. content: ModelMessageContentBlock[],
  59. index: number,
  60. options: PairedTextOptions,
  61. ): boolean {
  62. const block = content[index];
  63. if (block?.type !== "text" || block.text.trim().length === 0) return false;
  64. // 只有 producer 签发的媒体凭证才配对;任意相邻文本配对会改变所有工具的
  65. // 通用媒体语义(普通截图/文件预览的相邻说明不属于媒体)。
  66. if (!containsOfficialCuaImageRefCredentialText(block.text)) return false;
  67. // 跳过空白 text 寻找更早图片会破坏 producer 规定的 image -> image_ref
  68. // 直接邻接关系,并可能把已被插入块拆开的 frame_ref 重新授权。
  69. const candidate = content[index - 1];
  70. return (
  71. candidate !== undefined &&
  72. contentBlockToUserMediaParts(candidate, {
  73. ...options,
  74. toolName: "",
  75. }).length > 0
  76. );
  77. }
  78. function pairedTextIndexes(
  79. content: ModelMessageContentBlock[],
  80. options: PairedTextOptions,
  81. ): Set<number> {
  82. // stripMedia 时 media 不会延后(toToolResultMediaUserParts 直接返回空),
  83. // 配对省略不得先行——否则文本从 tool 输出消失又不出现在任何消息里。
  84. if (options.stripMedia === true) return new Set();
  85. const paired = new Set<number>();
  86. for (let index = 0; index < content.length; index += 1) {
  87. if (isPairedTextBlock(content, index, options)) paired.add(index);
  88. }
  89. return paired;
  90. }
  91. export function toStructuredToolResultText(
  92. content: ModelMessageContent,
  93. options: Pick<ToolResultMediaProjectionOptions, "inputFormat"> = {},
  94. ): string {
  95. if (typeof content === "string") return content;
  96. const paired = pairedTextIndexes(content, options);
  97. return modelMessageContentToText(
  98. content.map((block, index) => {
  99. // 配对文本随 media 一起延后(见 toToolResultMediaUserParts),这里省略
  100. // 以免模型在同一次请求里看到两份引用文本。
  101. if (paired.has(index)) return { type: "text", text: "" };
  102. const unsupportedText = unsupportedInputMediaText(block, options.inputFormat);
  103. return unsupportedText ? { type: "text", text: unsupportedText } : block;
  104. }),
  105. );
  106. }
  107. export function toToolResultMediaUserParts(
  108. content: ModelMessageContent,
  109. options: ToolResultMediaProjectionOptions,
  110. ): AiSdkUserContentParts {
  111. if (typeof content === "string" || options.stripMedia) return [];
  112. const blocks = content;
  113. const paired = pairedTextIndexes(blocks, options);
  114. const parts: AiSdkUserContentParts = [
  115. {
  116. type: "text",
  117. text: `${TOOL_RESULT_MEDIA_INTRO_PREFIX} ${options.toolName}:`,
  118. },
  119. ];
  120. // 分隔符只用于隔开"连续两段配对文本"。原判据是 parts.length > 1,隐含假设配对
  121. // 文本总是第一个入队(旧的 text-first 布局);producer 改成 image-first 后 raster
  122. // 先入队,该判据会在 image 与它的 image_ref 之间插入一个多余的空文本块。
  123. let lastPushedWasPairedText = false;
  124. for (let index = 0; index < blocks.length; index += 1) {
  125. const block = blocks[index]!;
  126. if (block.type === "text" && paired.has(index)) {
  127. // 配对文本与相邻 media 一起进入延后消息,保持原顺序。
  128. if (lastPushedWasPairedText) parts.push({ type: "text", text: "\n\n" });
  129. parts.push({ type: "text", text: block.text });
  130. lastPushedWasPairedText = true;
  131. continue;
  132. }
  133. const mediaParts = contentBlockToUserMediaParts(block, options);
  134. if (mediaParts.length === 0) continue;
  135. parts.push(...mediaParts);
  136. lastPushedWasPairedText = false;
  137. }
  138. return parts.length > 1 ? parts : [];
  139. }
  140. function contentBlockToUserMediaParts(
  141. block: ModelMessageContentBlock,
  142. options: ToolResultMediaProjectionOptions,
  143. ): AiSdkUserContentParts {
  144. switch (block.type) {
  145. case "image": {
  146. if (options.inputFormat && getUnsupportedModelInputMediaKind(block, options.inputFormat)) {
  147. return [];
  148. }
  149. const data = dataUrlToDataContent(block.dataUrl);
  150. if (!data) return [];
  151. return [{ type: "image", image: data.data, mediaType: block.mediaType }];
  152. }
  153. case "video": {
  154. if (options.inputFormat && getUnsupportedModelInputMediaKind(block, options.inputFormat)) {
  155. return [];
  156. }
  157. const data = dataUrlToDataContent(block.dataUrl);
  158. if (!data) return [];
  159. // 与 user 消息侧一致:video/* file part 交给 patch 后的 provider 包转 video_url / video block。
  160. return [{ type: "file", data: data.data, mediaType: block.mediaType }];
  161. }
  162. case "file": {
  163. if (block.text !== undefined && block.text.length > 0) return [];
  164. if (options.inputFormat && getUnsupportedModelInputMediaKind(block, options.inputFormat)) {
  165. return [];
  166. }
  167. const data = block.dataUrl ? dataUrlToDataContent(block.dataUrl) : undefined;
  168. if (!data) return [];
  169. return [
  170. {
  171. type: "file",
  172. data: data.data,
  173. filename: block.name,
  174. mediaType: block.mediaType,
  175. },
  176. ];
  177. }
  178. case "text":
  179. case "reasoning":
  180. case "tool_reference":
  181. case "resource_link":
  182. return [];
  183. }
  184. }
  185. /**
  186. * 通用 fail-closed 守卫(坐标帧引用不得以"引用在、栅格不在"到达模型):
  187. * 结构化 tool result 携带帧引用文本(如 CUA image_ref 的精确 JSON),而其媒体
  188. * 因模型不支持(或 stripMedia)无法投递时,该结果必须整体错误化——占位符替换
  189. * 会留下 actionable 引用,诱导模型对未见过画面的坐标产生动作。规则只依赖
  190. * "引用文本 + 不可投递媒体"的结构组合,不感知具体工具。
  191. */
  192. export function undeliverableFrameReferenceText(
  193. content: ModelMessageContent,
  194. options: Pick<ToolResultMediaProjectionOptions, "stripMedia" | "inputFormat">,
  195. ): string | undefined {
  196. if (!Array.isArray(content)) return undefined;
  197. // 与 MCP 归一化/hook 同一个内嵌扫描 detector——把 image_ref 包进说明文字
  198. // 不能绕过 fail-closed(安全边界不依赖 payload 形状)。
  199. const frameReferenceIndexes = content.flatMap((block, index) =>
  200. block.type === "text" && containsOfficialCuaImageRefCredentialText(block.text) ? [index] : [],
  201. );
  202. if (frameReferenceIndexes.length === 0) return undefined;
  203. const unavailable =
  204. "This tool returned a coordinate frame reference without a deliverable raster. " +
  205. "No image_ref or raster was exposed; do not use frame-bound coordinates. " +
  206. "Switch to an image-capable model and capture a new raster first.";
  207. if (options.stripMedia === true) return unavailable;
  208. // 每个凭证都必须由它直接前面的 raster 独立满足可投递性;结果中其他无关图片
  209. // 不能替 orphan ref 背书。
  210. return frameReferenceIndexes.every((index) => isPairedTextBlock(content, index, options))
  211. ? undefined
  212. : unavailable;
  213. }