navigation-text.ts 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. // Keep the original patterns on modern engines and select the legacy path once.
  2. const EMPHASIS_PATTERNS = (() => {
  3. try {
  4. return {
  5. // eslint-disable-next-line prefer-regex-literals -- The constructor lets older iOS versions catch unsupported syntax and use the fallback.
  6. asterisk: new RegExp('(?<!\\*)\\*(?=\\S)([\\s\\S]*?\\S)\\*(?!\\*)', 'gu'),
  7. // eslint-disable-next-line prefer-regex-literals -- The constructor lets older iOS versions catch unsupported syntax and use the fallback.
  8. underscore: new RegExp('(?<!_)_(?=\\S)([\\s\\S]*?\\S)_(?!_)', 'gu'),
  9. replacement: '$1',
  10. };
  11. } catch {
  12. return {
  13. asterisk: /(^|[^*])\*(?=\S)([\s\S]*?\S)\*(?!\*)/gu,
  14. underscore: /(^|[^_])_(?=\S)([\s\S]*?\S)_(?!_)/gu,
  15. replacement: '$1$2',
  16. };
  17. }
  18. })();
  19. const CHAT_CONTEXT_BLOCK_RE =
  20. /<(user-provided-context|mavis-chat-context|html-selection-context)\b[^>]*>([\s\S]*?)(?:<\/\1\s*>|$)/giu;
  21. const NAVIGATION_BLOCK_RE =
  22. /<(agent-message|agent-context|system-reminder|peer-memory-path|engine-message|inbound-context|archon_internal_context|locale-context|runtime-data-context|permission-ask|permission-response|questionnaire-ask|questionnaire-response|deliver-assets|deliver_assets|mavis-thinking)\b[^>]*>[\s\S]*?<\/\1\s*>/giu;
  23. const MEDIA_TAG_RE = /<media\b[^>]*\/?\s*>/giu;
  24. const UNICODE_WHITESPACE_RE = /\s+/gu;
  25. const USER_COMMENT_MARKER_RE = /^User comment \(requested change\):[ \t]*(.*)$/u;
  26. const USER_REQUESTED_EDIT_MARKER_RE = /^Requested edit for this selected PPT region:[ \t]*(.*)$/u;
  27. const USER_COMMENT_SUMMARY_RE = /^\d+\.\s+Comment \d+:[ \t]*(.+)$/u;
  28. const UNTRUSTED_EVIDENCE_RE = /^Untrusted .+ evidence\b/iu;
  29. const TRANSPORT_CONTEXT_MARKER_RE =
  30. /(?:^|\n)\s*(?:# Added chat context|(?:## )?(?:Selection sessions|User requested changes|Requested edits)|User comment \(requested change\):|Requested edit for this selected PPT region:|USER REQUEST \(user-authored\):|Untrusted .+ evidence\b|UNTRUSTED PPTX LOCATOR EVIDENCE)/iu;
  31. function compactWhitespace(value: string): string {
  32. return value.trim().replace(UNICODE_WHITESPACE_RE, ' ');
  33. }
  34. function extractUserComments(blockBody: string): string[] {
  35. const lines = blockBody.replace(/\r\n?/gu, '\n').split('\n');
  36. const summaryFallbacks: string[] = [];
  37. const comments: string[] = [];
  38. for (let index = 0; index < lines.length; index += 1) {
  39. const line = lines[index]?.trim() ?? '';
  40. const summaryMatch = USER_COMMENT_SUMMARY_RE.exec(line);
  41. if (summaryMatch?.[1]) summaryFallbacks.push(summaryMatch[1].trim());
  42. const markerMatch = USER_COMMENT_MARKER_RE.exec(line);
  43. const requestedEditMatch = USER_REQUESTED_EDIT_MARKER_RE.exec(line);
  44. if (!markerMatch && !requestedEditMatch) continue;
  45. const commentLines: string[] = [];
  46. const inlineComment = (markerMatch?.[1] ?? requestedEditMatch?.[1])?.trim();
  47. if (inlineComment) commentLines.push(inlineComment);
  48. for (let cursor = index + 1; cursor < lines.length; cursor += 1) {
  49. const candidate = lines[cursor]?.trim() ?? '';
  50. if (
  51. !candidate ||
  52. UNTRUSTED_EVIDENCE_RE.test(candidate) ||
  53. USER_COMMENT_MARKER_RE.test(candidate) ||
  54. USER_REQUESTED_EDIT_MARKER_RE.test(candidate)
  55. )
  56. break;
  57. commentLines.push(candidate);
  58. }
  59. const comment = markdownToPlainText(commentLines.join('\n'));
  60. if (comment) comments.push(comment);
  61. }
  62. return comments.length > 0 ? comments : summaryFallbacks.map(markdownToPlainText);
  63. }
  64. function markdownToPlainText(markdown: string): string {
  65. return compactWhitespace(
  66. markdown
  67. .replace(/\r\n?/gu, '\n')
  68. .replace(/^[ \t]{0,3}(?:[-*_][ \t]*){3,}$/gmu, '')
  69. .replace(/^[ \t]{0,3}(?:`{3,}|~{3,})[^\n]*$/gmu, '')
  70. .replace(/^[ \t]{0,3}#{1,6}[ \t]+/gmu, '')
  71. .replace(/^[ \t]{0,3}>[ \t]?/gmu, '')
  72. .replace(/^[ \t]*(?:[-+*]|\d+[.)])[ \t]+/gmu, '')
  73. .replace(/!\[([^\]]*)\]\([^)]*\)/gu, '$1')
  74. .replace(/\[([^\]]+)\]\([^)]*\)/gu, '$1')
  75. .replace(/(`+)([\s\S]*?)\1/gu, '$2')
  76. .replace(/(\*\*|__)(?=\S)([\s\S]*?\S)\1/gu, '$2')
  77. .replace(/~~(?=\S)([\s\S]*?\S)~~/gu, '$1')
  78. .replace(EMPHASIS_PATTERNS.asterisk, EMPHASIS_PATTERNS.replacement)
  79. .replace(EMPHASIS_PATTERNS.underscore, EMPHASIS_PATTERNS.replacement)
  80. .replace(/\\([\\`*_[\]{}()#+\-.!>])/gu, '$1'),
  81. );
  82. }
  83. function isClosedContextMatch(match: RegExpMatchArray): boolean {
  84. return /<\/(user-provided-context|mavis-chat-context|html-selection-context)\s*>$/iu.test(
  85. match[0] ?? '',
  86. );
  87. }
  88. function isTransportContextMatch(match: RegExpMatchArray): boolean {
  89. return isClosedContextMatch(match) || TRANSPORT_CONTEXT_MARKER_RE.test(match[2] ?? '');
  90. }
  91. function stripContextMatches(content: string, matches: RegExpMatchArray[]): string {
  92. let result = '';
  93. let cursor = 0;
  94. for (const match of matches) {
  95. const start = match.index ?? cursor;
  96. result += content.slice(cursor, start);
  97. cursor = start + (match[0]?.length ?? 0);
  98. }
  99. return result + content.slice(cursor);
  100. }
  101. /**
  102. * Projects protocol-wrapped Markdown message content into readable navigation copy.
  103. * User-authored comments are projected first in source order, followed by any
  104. * remaining visible body text. Protocol wrappers are never exposed.
  105. */
  106. export function toNavigationPlainText(content: string | undefined): string {
  107. if (!content) return '';
  108. const contextMatches = Array.from(content.matchAll(CHAT_CONTEXT_BLOCK_RE)).filter(
  109. isTransportContextMatch,
  110. );
  111. const contextComments = contextMatches.flatMap((match) => extractUserComments(match[2] ?? ''));
  112. const visibleBody = markdownToPlainText(
  113. stripContextMatches(content, contextMatches)
  114. .replace(NAVIGATION_BLOCK_RE, '')
  115. .replace(MEDIA_TAG_RE, ''),
  116. );
  117. return markdownToPlainText([...contextComments, visibleBody].filter(Boolean).join('\n'));
  118. }