workspaceMentions.ts 1.2 KB

12345678910111213141516171819202122
  1. import type { WorkspaceAgent as Agent } from '../shared/workspace.js'
  2. export function mentionedAgents(text: string, agents: Array<Pick<Agent, 'id' | 'name'>>): string[] {
  3. if (!text.includes('@')) return []
  4. const plain = text
  5. .replace(/<quoted_message\b[^>]*>[\s\S]*?<\/quoted_message>/gi, '')
  6. .replace(/```[\s\S]*?(?:```|$)|~~~[\s\S]*?(?:~~~|$)/g, '')
  7. .replace(/`[^`]*`/g, '')
  8. .replace(/https?:\/\/\S+/g, '')
  9. .replace(/[\p{L}\p{N}._%+-]{1,64}@[\p{L}\p{N}.-]{1,255}\.[\p{L}]{2,63}/gu, '')
  10. .split('\n').filter(line => !line.trimStart().startsWith('>')).join('\n')
  11. const names = [...agents].sort((a, b) => b.name.length - a.name.length)
  12. const alternatives = [...names.map(a => a.name.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')), 'all', '所有人']
  13. const pattern = new RegExp(`(?<![A-Za-z0-9_.%+/@-])@(${alternatives.join('|')})(?![A-Za-z0-9_])`, 'giu')
  14. const result = new Set<string>()
  15. for (const match of plain.matchAll(pattern)) {
  16. const name = match[1]!
  17. if (/^(all|所有人)$/i.test(name)) { for (const a of agents) result.add(a.id) }
  18. else { const a = agents.find(a => a.name.toLocaleLowerCase() === name.toLocaleLowerCase()); if (a) result.add(a.id) }
  19. }
  20. return [...result]
  21. }