mediaMarkdown.ts 4.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. const IMAGE_EXTENSIONS = new Set([
  2. 'apng', 'avif', 'bmp', 'gif', 'heic', 'heif', 'ico', 'jfi', 'jfif', 'jif',
  3. 'jpe', 'jpeg', 'jpg', 'jxl', 'png', 'svg', 'tif', 'tiff', 'webp',
  4. ])
  5. const MEDIA_MARKER = /MEDIA:\s*/g
  6. const FENCE = /^\s{0,3}(`{3,}|~{3,})/
  7. const HEADING = /^\s{0,3}#{1,6}(?:\s|$)/
  8. type MediaMatch = { path: string; end: number }
  9. function inlineCodeRanges(line: string): Array<[number, number]> {
  10. const ranges: Array<[number, number]> = []
  11. let index = 0
  12. while (index < line.length) {
  13. if (line[index] !== '`' || line[index - 1] === '\\') {
  14. index += 1
  15. continue
  16. }
  17. const start = index
  18. while (line[index] === '`') index += 1
  19. const fence = line.slice(start, index)
  20. const end = line.indexOf(fence, index)
  21. if (end < 0) {
  22. ranges.push([start, line.length])
  23. break
  24. }
  25. ranges.push([start, end + fence.length])
  26. index = end + fence.length
  27. }
  28. return ranges
  29. }
  30. function isInRanges(index: number, ranges: Array<[number, number]>): boolean {
  31. return ranges.some(([start, end]) => index >= start && index < end)
  32. }
  33. function isSafeAbsolutePath(path: string): boolean {
  34. if (!path.startsWith('/') || path.startsWith('//') || /\0/.test(path)) return false
  35. return !path.split('/').some(segment => segment === '..' || /^%2e%2e$/i.test(segment))
  36. }
  37. function unquotedPath(line: string, start: number, streaming: boolean): MediaMatch | undefined {
  38. if (line[start] !== '/') return undefined
  39. const tail = line.slice(start)
  40. const extension = /\.[A-Za-z0-9]{1,12}(?=$|[\s,,。;;::!?!?\])}])/g
  41. const match = extension.exec(tail)
  42. if (!match) return undefined
  43. const end = start + match.index + match[0].length
  44. // A streamed unquoted path is ambiguous until the producer has emitted a
  45. // line boundary. Rendering early can turn a later path suffix into prose.
  46. if (streaming && end === line.length) return undefined
  47. return { path: line.slice(start, end), end }
  48. }
  49. function readMediaPath(line: string, start: number, streaming: boolean): MediaMatch | undefined {
  50. let cursor = start
  51. while (/\s/.test(line[cursor] ?? '')) cursor += 1
  52. const quote = line[cursor]
  53. if (quote === '"' || quote === "'" || quote === '`') {
  54. const close = line.indexOf(quote, cursor + 1)
  55. if (close < 0) return undefined
  56. return { path: line.slice(cursor + 1, close), end: close + 1 }
  57. }
  58. return unquotedPath(line, cursor, streaming)
  59. }
  60. function escapeLabel(value: string): string {
  61. return value.replace(/([\\\[\]])/g, '\\$1')
  62. }
  63. function asMarkdown(path: string): string {
  64. const fileName = path.split('/').filter(Boolean).at(-1) || '文件'
  65. const extension = fileName.split('.').at(-1)?.toLocaleLowerCase() || ''
  66. const label = escapeLabel(fileName)
  67. const destination = path.split('/').map(part => encodeURIComponent(part).replace(/\(/g, '%28').replace(/\)/g, '%29')).join('/')
  68. return IMAGE_EXTENSIONS.has(extension) ? `![${label}](${destination})` : `[${label}](${destination})`
  69. }
  70. function transformLine(line: string, streaming: boolean, terminated: boolean): string {
  71. if (HEADING.test(line) || line.includes('|')) return line
  72. const codeRanges = inlineCodeRanges(line)
  73. let output = ''
  74. let cursor = 0
  75. MEDIA_MARKER.lastIndex = 0
  76. for (let marker = MEDIA_MARKER.exec(line); marker; marker = MEDIA_MARKER.exec(line)) {
  77. const markerStart = marker.index
  78. if (isInRanges(markerStart, codeRanges)) continue
  79. const media = readMediaPath(line, markerStart + marker[0].length, streaming && !terminated)
  80. if (!media || !isSafeAbsolutePath(media.path)) continue
  81. output += line.slice(cursor, markerStart)
  82. output += asMarkdown(media.path)
  83. cursor = media.end
  84. MEDIA_MARKER.lastIndex = media.end
  85. }
  86. return cursor ? output + line.slice(cursor) : line
  87. }
  88. /**
  89. * Compatibility for historical assistant output. New agent output is already
  90. * Markdown and deliberately bypasses any message mutation at send time.
  91. */
  92. export function normalizeAssistantMediaMarkdown(content: string, streaming = false): string {
  93. let inFence = false
  94. const parts = content.split(/(\r?\n)/)
  95. return parts.map((part, index) => {
  96. if (part === '\n' || part === '\r\n') return part
  97. const fence = FENCE.exec(part)
  98. if (fence) {
  99. inFence = !inFence
  100. return part
  101. }
  102. const terminated = parts[index + 1] === '\n' || parts[index + 1] === '\r\n'
  103. return inFence ? part : transformLine(part, streaming, terminated)
  104. }).join('')
  105. }