notificationText.ts 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. import { basename } from 'node:path'
  2. import MarkdownIt from 'markdown-it'
  3. import type Token from 'markdown-it/lib/token.mjs'
  4. export interface NotificationTextOptions {
  5. fallback: string
  6. maximum: number
  7. }
  8. const MAXIMUM_SOURCE_CHARACTERS = 16 * 1_024
  9. const markdown = new MarkdownIt({
  10. html: false,
  11. breaks: false,
  12. linkify: false,
  13. typographer: false,
  14. })
  15. markdown.disable('smartquotes')
  16. const graphemeSegmenter = new Intl.Segmenter('zh-CN', { granularity: 'grapheme' })
  17. function sourcePrefix(value: string): string {
  18. if (value.length <= MAXIMUM_SOURCE_CHARACTERS) return value
  19. let result = value.slice(0, MAXIMUM_SOURCE_CHARACTERS)
  20. const last = result.charCodeAt(result.length - 1)
  21. if (last >= 0xD800 && last <= 0xDBFF) result = result.slice(0, -1)
  22. return result
  23. }
  24. function inlineText(tokens: readonly Token[]): string {
  25. const result: string[] = []
  26. for (const token of tokens) {
  27. if (token.type === 'text') result.push(token.content)
  28. else if (token.type === 'code_inline') result.push(token.content)
  29. else if (token.type === 'softbreak' || token.type === 'hardbreak') result.push(' ')
  30. else if (token.type === 'image') {
  31. const alt = inlineText(token.children ?? []).trim() || token.content.trim() || '图片'
  32. result.push(`🖼️ ${alt}`)
  33. } else if (token.type !== 'html_inline' && token.children?.length) {
  34. result.push(inlineText(token.children))
  35. }
  36. }
  37. return result.join('')
  38. }
  39. function markdownText(value: string): string {
  40. const result: string[] = []
  41. for (const token of markdown.parse(value, {})) {
  42. if (token.type === 'inline') {
  43. const text = inlineText(token.children ?? []).trim()
  44. if (text) result.push(text)
  45. } else if (token.type === 'fence' || token.type === 'code_block') {
  46. result.push('💻 代码片段')
  47. } else if (token.type === 'list_item_open') {
  48. result.push('•')
  49. } else if (token.type === 'th_open' || token.type === 'td_open') {
  50. result.push('•')
  51. } else if (token.type === 'hr') {
  52. result.push('•')
  53. }
  54. }
  55. return result.join(' ')
  56. }
  57. function visibleBasename(value: string): string {
  58. const unwrapped = value.replace(/^<|>$/g, '').replace(/[\])}>,.;,。;:]+$/u, '')
  59. try {
  60. const decoded = decodeURIComponent(unwrapped)
  61. return basename(decoded) || '附件'
  62. } catch {
  63. return basename(unwrapped) || '附件'
  64. }
  65. }
  66. function replaceHermesReferences(value: string): string {
  67. return value
  68. .replace(/@(terminal|tool):[^\r\n]*/giu, (_match, kind: string) => (
  69. kind.toLowerCase() === 'terminal' ? '💻 终端信息' : '🛠️ 工具信息'
  70. ))
  71. .replace(/@(file|folder|image):\s*([^\s]+)/giu, (_match, kind: string, target: string) => {
  72. const icon = kind.toLowerCase() === 'image' ? '🖼️' : kind.toLowerCase() === 'folder' ? '📁' : '📎'
  73. return `${icon} ${visibleBasename(target)}`
  74. })
  75. .replace(/@url:\s*[^\s]+/giu, '🔗 链接')
  76. }
  77. function stripUnsafeTechnicalText(value: string): string {
  78. return value
  79. .replace(/\u001B(?:\[[0-?]*[ -/]*[@-~]|\][^\u0007]*(?:\u0007|\u001B\\))/gu, '')
  80. .split(/\r?\n/u)
  81. .filter(line => !/^\s*at\s+(?:async\s+)?[^\s]+.*(?:\([^)]*:\d+:\d+\)|:\d+:\d+)\s*$/u.test(line)
  82. && !/^\s*File\s+"[^"]+",\s+line\s+\d+/u.test(line))
  83. .join('\n')
  84. }
  85. function redactRawLocations(value: string): string {
  86. return value
  87. .replace(/\bhttps?:\/\/[^\s<>()]+/giu, '🔗 链接')
  88. .replace(/\bdata:[^\s]+/giu, '🖼️ 图片')
  89. .replace(/(^|[\s((::])((?:\/[^\s/]+){2,})/gu, (_match, prefix: string, target: string) => (
  90. `${prefix}📎 ${visibleBasename(target)}`
  91. ))
  92. .replace(/\[图片:([^\]]+)\]/gu, '🖼️ $1')
  93. .replace(/\[文件:([^\]]+)\]/gu, '📎 $1')
  94. }
  95. function normalizeVisibleText(value: string): string {
  96. return value
  97. .normalize('NFC')
  98. .replace(/[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F-\u009F]/gu, '')
  99. .replace(/[\u200B\u202A-\u202E\u2060\u2066-\u2069\uFEFF]/gu, '')
  100. .replace(/<\/?[A-Za-z][^>]*>/gu, ' ')
  101. .replace(/(?:\s*•\s*){2,}/gu, ' • ')
  102. .replace(/\s+/gu, ' ')
  103. .trim()
  104. }
  105. function truncateGraphemes(value: string, maximum: number): string {
  106. const segments = [...graphemeSegmenter.segment(value)].map(segment => segment.segment)
  107. if (segments.length <= maximum) return value
  108. return `${segments.slice(0, Math.max(0, maximum - 1)).join('')}…`
  109. }
  110. /** Converts model-authored Markdown into one safe, visible notification line. */
  111. export function notificationPlainText(
  112. raw: unknown,
  113. options: NotificationTextOptions,
  114. ): string {
  115. const source = typeof raw === 'string' ? sourcePrefix(raw).trim() : ''
  116. if (!source) return options.fallback
  117. const prepared = replaceHermesReferences(stripUnsafeTechnicalText(source))
  118. const rendered = markdownText(prepared)
  119. const normalized = normalizeVisibleText(redactRawLocations(rendered))
  120. if (!normalized) return options.fallback
  121. return truncateGraphemes(normalized, options.maximum)
  122. }