conversationShareInlineImages.ts 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127
  1. import { createHash } from "node:crypto";
  2. import type { ConversationShareCapabilities } from "@zcode/shared";
  3. import type { WireConversationRow } from "@zcode/shared/zcode-protocol-v4";
  4. import type { ConversationShareFailureIssue } from "./conversationShare.js";
  5. /** 内嵌图片转为既有 artifact;预检和发布使用同一份确定性转换,不新增文件读取通道。 */
  6. export function materializeConversationShareInlineImages(
  7. sourceRows: readonly WireConversationRow[],
  8. capabilities: ConversationShareCapabilities,
  9. turnOrdinals: ReadonlyMap<string, number>,
  10. ): {
  11. rows: WireConversationRow[];
  12. bytesBySourceRef: Map<string, Uint8Array>;
  13. warnings: ConversationShareFailureIssue[];
  14. toolImages: Map<number, Array<{ resourceId: string; mimeType: string }>>;
  15. } {
  16. const rows: WireConversationRow[] = [];
  17. const toolImages = new Map<number, Array<{ resourceId: string; mimeType: string }>>();
  18. const bytesBySourceRef = new Map<string, Uint8Array>();
  19. const warnings: ConversationShareFailureIssue[] = [];
  20. let nextRowId = sourceRows.reduce((max, row) => Math.max(max, row.rowId), 0);
  21. for (const row of sourceRows) {
  22. if (row.kind !== "toolCall") {
  23. rows.push(row);
  24. continue;
  25. }
  26. const display = row.display?.kind === "node_repl_images" ? row.display : undefined;
  27. const media = row.output?.display?.kind === "cua" ? row.output.display.media : undefined;
  28. if (media?.some((item) => item.artifactUri && !item.data)) {
  29. // 只有资源引用、没有公开可读取字节时保持文本回退,不把本地读取权限带入分享。
  30. warnings.push({
  31. code: "content_unavailable",
  32. scope: "turn",
  33. rowId: row.rowId,
  34. productTurnId: row.productTurnId,
  35. });
  36. }
  37. const images = [
  38. ...(display?.images ?? []),
  39. ...(media ?? []).flatMap((item) =>
  40. item.data && item.mimeType.startsWith("image/")
  41. ? [{ base64: item.data.replace(/^data:[^;]+;base64,/u, ""), mimeType: item.mimeType }]
  42. : [],
  43. ),
  44. ];
  45. if (display) {
  46. const { display: _display, ...toolRow } = row;
  47. rows.push(toolRow);
  48. } else rows.push(row);
  49. for (const [index, image] of images.entries()) {
  50. const mimeType = image.mimeType.toLowerCase();
  51. const allowed = capabilities.allowed_artifacts.find(
  52. (candidate) =>
  53. candidate.type === "image" &&
  54. candidate.mime_types.some((mime) => mime.toLowerCase() === mimeType),
  55. );
  56. const extensions: Record<string, string[]> = {
  57. "image/png": ["png"],
  58. "image/jpeg": ["jpg", "jpeg"],
  59. "image/webp": ["webp"],
  60. "image/gif": ["gif"],
  61. "image/svg+xml": ["svg"],
  62. };
  63. const extension = allowed?.extensions
  64. .map((value) => value.replace(/^\./u, "").toLowerCase())
  65. .find((value) => extensions[mimeType]?.includes(value));
  66. const displayName = `tool-image-${row.rowId}-${index + 1}.${extension ?? "image"}`;
  67. const issue = {
  68. scope: "artifact" as const,
  69. rowId: row.rowId,
  70. productTurnId: row.productTurnId,
  71. turnOrdinal: row.productTurnId ? turnOrdinals.get(row.productTurnId) : undefined,
  72. artifactDisplayName: displayName,
  73. artifactType: "image",
  74. mimeType,
  75. };
  76. if (!extension) {
  77. warnings.push({
  78. ...issue,
  79. code: "artifact_type_not_allowed",
  80. allowedArtifacts: capabilities.allowed_artifacts.map((candidate) => ({
  81. type: candidate.type,
  82. extensions: candidate.extensions,
  83. mimeTypes: candidate.mime_types,
  84. })),
  85. });
  86. continue;
  87. }
  88. const bytes = Buffer.from(image.base64, "base64");
  89. // Buffer.from 对非法 base64 宽松容错,必须复核,避免分享一个已损坏的图片文件。
  90. if (
  91. !bytes.length ||
  92. bytes.toString("base64").replace(/=+$/u, "") !== image.base64.replace(/=+$/u, "")
  93. ) {
  94. warnings.push({
  95. ...issue,
  96. code: "artifact_read_failed",
  97. availability: "unknown",
  98. });
  99. continue;
  100. }
  101. const ref = `inline-tool-image:${row.rowId}:${index}`;
  102. bytesBySourceRef.set(ref, bytes);
  103. const references = toolImages.get(row.rowId) ?? [];
  104. references.push({ resourceId: ref, mimeType });
  105. toolImages.set(row.rowId, references);
  106. rows.push({
  107. kind: "artifact",
  108. rowId: ++nextRowId,
  109. turnId: row.turnId,
  110. productTurnId: row.productTurnId,
  111. createdAt: row.createdAt,
  112. createdAtSeq: row.createdAtSeq,
  113. artifactVersionId: ref,
  114. logicalArtifactKey: ref,
  115. displayName,
  116. artifactType: "image",
  117. mimeType,
  118. sizeBytes: bytes.byteLength,
  119. sha256: createHash("sha256").update(bytes).digest("hex"),
  120. ref,
  121. state: "current",
  122. });
  123. }
  124. }
  125. return { rows, bytesBySourceRef, warnings, toolImages };
  126. }