im-text-sanitize.ts 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147
  1. /**
  2. * Shared IM-outbound text sanitizers for agent-emitted XML tags that have
  3. * no native IM representation.
  4. *
  5. * P0-3 minimal stopgap: agent reply text may contain `<media src=... />`
  6. * (single media reference) or `<deliver-assets>...</deliver-assets>`
  7. * (multi-asset wrapper) blocks. The real out-of-band media upload pipeline
  8. * (P2) is not built yet, so without a sanitizer these tags reach the user
  9. * as literal text — e.g. `<media src="/tmp/foo.png" caption="Architecture diagram" />`
  10. * showing up verbatim in Feishu / Telegram / WeChat. This helper rewrites
  11. * those tags to short human-readable placeholders so the user at least
  12. * sees a meaningful hint that "the agent intended to deliver media".
  13. *
  14. * Lives in `@mavis/shared` because TWO outbound surfaces need it:
  15. *
  16. * 1. `IMGatewayChannelClient.sanitizeForIM` (Feishu / WeChat via the
  17. * electron-side IM gateway).
  18. * 2. `collectChannelResponseFromSse` (Telegram and the mock outbound,
  19. * which never pass through the electron sanitizer).
  20. *
  21. * Replacement rules:
  22. *
  23. * - `<media ... />` (or opening tag, self-closing or not) → either
  24. * `[Media: <caption>]` (when `caption` attr is set), or
  25. * `[Media: <filename>]` (basename of `src`, query string stripped),
  26. * or `[Media]` when neither is available.
  27. * - `<deliver-assets>...</deliver-assets>` → `[N delivered assets]` where N
  28. * counts inner `<media>`/`<asset>` children, falling back to
  29. * `[Delivered assets]` when the count is zero or indeterminate.
  30. *
  31. * The replacement is single-pass and does NOT try to fully parse the XML
  32. * — agents may emit malformed or streaming-truncated tags, and the goal
  33. * is "do not leak literal `<media`" rather than "render media correctly".
  34. * The full media path is P2.
  35. *
  36. * NOTE: This helper deliberately leaves `<think>` and `<genui-*>` blocks
  37. * alone. The IM gateway has its own strip step for those (see
  38. * `IMGatewayChannelClient.sanitizeForIM`); the Telegram path keeps the
  39. * tags by design today (P0 scope is media only). Callers that need both
  40. * should compose: strip first, then call `placeholderMediaTags`.
  41. */
  42. /**
  43. * Pull an attribute value out of a tag-open string.
  44. *
  45. * Handles double-quoted (`attr="value"`), single-quoted (`attr='value'`)
  46. * and unquoted (`attr=value`) forms. Returns `undefined` when the
  47. * attribute is absent or malformed. Attribute names are case-insensitive.
  48. */
  49. function readAttr(tagOpen: string, attr: string): string | undefined {
  50. const re = new RegExp(`\\b${attr}\\s*=\\s*(?:"([^"]*)"|'([^']*)'|([^\\s>]+))`, 'iu');
  51. const m = tagOpen.match(re);
  52. if (!m) return undefined;
  53. return m[1] ?? m[2] ?? m[3];
  54. }
  55. /**
  56. * Reduce a `src` value to a user-friendly filename. Strips query string
  57. * and fragment, splits on `/` or `\`, takes the last segment. Returns
  58. * `undefined` for an empty or whitespace-only result.
  59. */
  60. function srcToFilename(src: string | undefined): string | undefined {
  61. if (!src) return undefined;
  62. const stripped = src.split('?')[0]?.split('#')[0] ?? '';
  63. const parts = stripped.split(/[\\/]/u);
  64. const last = parts[parts.length - 1]?.trim();
  65. if (!last) return undefined;
  66. return last;
  67. }
  68. /**
  69. * Format a single `<media …/>` (or `<media …>` opening tag) as a
  70. * placeholder string for IM display.
  71. *
  72. * Priority order:
  73. * 1. `caption` attribute value (trimmed, non-empty)
  74. * 2. basename of `src` (query stripped)
  75. * 3. `[Media]` fallback
  76. */
  77. function mediaTagPlaceholder(tagOpen: string): string {
  78. const caption = readAttr(tagOpen, 'caption')?.trim();
  79. if (caption) return `[媒体: ${caption}]`;
  80. const filename = srcToFilename(readAttr(tagOpen, 'src'))?.trim();
  81. if (filename) return `[媒体: ${filename}]`;
  82. return '[媒体]';
  83. }
  84. /**
  85. * Count `<media>` and `<asset>` children inside a `<deliver-assets>` block
  86. * body. Self-closing or opening tags both count. Returns the integer
  87. * count; 0 when nothing matches.
  88. */
  89. function countDeliverChildren(body: string): number {
  90. const re = /<(?:media|asset)\b[^>]*\/?>/giu;
  91. const matches = body.match(re);
  92. return matches ? matches.length : 0;
  93. }
  94. /**
  95. * Single-media tag: self-closing `<media ... />` OR opening `<media ...>`.
  96. *
  97. * The pattern intentionally accepts both because streaming-truncated
  98. * output can produce either, and either way we want the literal token
  99. * gone before it reaches an IM platform. The matcher requires either at
  100. * least one space after `media` (attributed form) or an immediate `/>`
  101. * (bare `<media/>`), so it does not collide with hypothetical
  102. * `<media-something>` neighbours.
  103. */
  104. const MEDIA_TAG_RE = /<media(?:\s+[^>]*?)?\s*\/?>/giu;
  105. /**
  106. * `<deliver-assets>` block, with or without attributes, non-greedy body.
  107. */
  108. const DELIVER_ASSETS_RE = /<deliver-assets(?:\s+[^>]*)?>[\s\S]*?<\/deliver-assets>/giu;
  109. /**
  110. * Replace `<media>` and `<deliver-assets>` XML tags in `text` with short
  111. * IM-friendly placeholder strings. See the module docstring for the full
  112. * rule set.
  113. *
  114. * Idempotent: a second call on the same input is a no-op (the placeholder
  115. * strings contain no XML).
  116. *
  117. * Order: `<deliver-assets>` is processed FIRST so its `<media>` children
  118. * are counted (not individually replaced) when they live inside a wrapper
  119. * block. Stray `<media>` tags outside any wrapper get the per-tag
  120. * placeholder pass after that.
  121. */
  122. export function placeholderMediaTags(text: string): string {
  123. if (!text) return text;
  124. let out = text;
  125. // 1. Deliver-assets wrapper → `[N delivered assets]` (N counted from inner
  126. // <media>/<asset> children, falling back to `[Delivered assets]` when 0).
  127. out = out.replace(DELIVER_ASSETS_RE, (match) => {
  128. const inner = match
  129. .replace(/^<deliver-assets(?:\s+[^>]*)?>/iu, '')
  130. .replace(/<\/deliver-assets>\s*$/iu, '');
  131. const n = countDeliverChildren(inner);
  132. return n > 0 ? `[${n} 个交付资产]` : '[交付资产]';
  133. });
  134. // 2. Standalone <media …/> tags → per-tag placeholder.
  135. out = out.replace(MEDIA_TAG_RE, (match) => mediaTagPlaceholder(match));
  136. return out;
  137. }